0

我正在尝试使用 XPathDocument 计算 xml 文档中的所有节点

我使用的代码是

var xmlPathDoc = new XPathDocument(new StringReader(xml));
XPathNavigator documentNav = xmlPathDoc.CreateNavigator();

当我不知道节点的名称时,有没有办法计算这些

我想用类似的东西

int nodeCount = documentNav.Select("/").Count;

但不确定要在选择部分放什么

谢谢

西蒙

4

3 回答 3

3
XmlNode node = myDoc.SelectSingleNode("/");

int i = node.SelectNodes("descendant::*").Count;

另请参阅Count Total Number of XmlNodes in C#

于 2012-10-11T15:07:56.800 回答
2

您可以使用XDocument.Descendents和计算它们:

var doc = XDocument.Parse(xml);
var count = doc.Descendants().Count();
于 2012-10-11T15:00:01.600 回答
0

您不需要 XPath。首先获取 DOM 对象并获取所有元素的节点列表并获取其计数。

public virtual XmlNodeList GetElementsByTagName(String tagname )


    Returns a NodeList of all the Elements with a given tag name in the order 
    in which they are encountered in a preorder traversal of the Document tree.

        Parameters:
            tagname - The name of the tag to match on. The special value "*"
            matches all tags. 
        Returns:
            A new NodeList object containing all the matched Elements.
于 2012-10-11T15:01:47.270 回答