计算XDocument上的子节点数

13

有没有一种方法可以计算XDocument上的子节点?

我查找了计数方法或属性,但没有找到。

谢谢 Leo


我发现可以使用xdocument.Root.Nodes().Count()的方法,但我不确定这是否是最佳实践。谢谢。 - MammothOne
请澄清。XDocument是包含XML数据的文档。您想知道文档中行的总数吗?还是您想知道文档根元素的子节点? - Daniel Hilgarth
Daniel,谢谢你的回复。这正是我正在寻找的内容。 doc.Descendants().Count(); 谢谢 Thomas。 - MammothOne
然后,您应该将Thomas的回答设置为答案。 - Evren Kuzucuoglu
GFK,我尝试了一下,但我猜在设定的答案生效前需要等待10分钟。 - MammothOne
2个回答

24
var doc = XDocument.Load(fileName);
int descendantsCount = doc.Descendants().Count(); // counts ALL descendants elements
int childrenCount = doc.Root.Elements().Count(); // counts direct children of the root element

3

如果您知道元素的名称永远不会更改并且它们始终存在,可以选择...

与此相反
XDocument xD = XDocument.Load(XmlFullFileName);
XElement xE_ParameterSets = xD.Root.Element("Report").Element("ParameterSets");
int index = ((IEnumerable<XElement>)xE_ParameterSets.Elements()).Count();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接