【问题标题】:Number of Nodes with XPathDocument具有 XPathDocument 的节点数
【发布时间】:2012-10-11 23:09:19
【问题描述】:

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

我使用的代码是

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

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

我想使用类似的东西

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

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

谢谢

西蒙

【问题讨论】:

    标签: c# xml


    【解决方案1】:
    XmlNode node = myDoc.SelectSingleNode("/");
    
    int i = node.SelectNodes("descendant::*").Count;
    

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

    【讨论】:

      【解决方案2】:

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

      var doc = XDocument.Parse(xml);
      var count = doc.Descendants().Count();
      

      【讨论】:

        【解决方案3】:

        您不需要 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.
        

        【讨论】:

          猜你喜欢
          • 2013-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多