【问题标题】:How to get specific element Count in XML or XElement variable如何获取 XML 或 XElement 变量中的特定元素计数
【发布时间】:2012-02-04 13:50:09
【问题描述】:

考虑这个 XML:

<Employees>
    <Person>
        <ID>1000</ID>
        <Name>Nima</Name>
        <LName>Agha</LName>
    </Person>
    <Person>
        <ID>1001</ID>
        <Name>Ligha</Name>
        <LName>Ligha</LName>
    </Person>
    <Person>
        <ID>1002</ID>
        <Name>Jigha</Name>
        <LName>Jigha</LName>
    </Person>
    <Person>
        <ID>1003</ID>
        <Name>Aba</Name>
        <LName>Aba</LName>
    </Person>
</Employees>

我声明了一个XElement 变量并创建了将其分配给该变量的XML。如何在 C# 中获取此 XML 变量中 ID 元素的计数?

【问题讨论】:

    标签: c# xml linq xelement


    【解决方案1】:

    先决条件:要使用.Count(),您需要导入命名空间System.Linq

    using System.Linq;
    

    您可以使用名称为“ID”的Descendants method 过滤后代元素,然后计算结果:

    int count = xml.Descendants("ID").Count();
    

    请注意,Descendants 会查看所有级别。如果您有一个除 Person 之外的元素也有一个 ID 子元素,那么您会想要更具体。在这种情况下,要计算属于 Person 元素的 ID 子元素,您可以使用:

    int count = xml.Elements("Person")
                   .Elements("ID")
                   .Count();
    

    【讨论】:

    • 如果你不使用 Elemets("Employees") 它返回 0 :-?
    • @Nima 基于您的示例输入,Employees 是根节点,如果您使用的是 XElement,则无需 Elements("Employee") 成为查询的一部分。如果它不是根元素,那么您可以包含它,或者改用xml.Descendants("Person").Elements("ID").Count(),从而避免逐个元素遍历 XML 元素的需要。
    • 这个答案仍然是最新的吗?据我所知,Descendants()Elements()都返回一个IEnumerable,它似乎没有Count()方法。我错过了什么明显的东西吗?
    【解决方案2】:
    XmlDocument xmldoc = new XmlDocument();
     xmldoc.Load(XmlPath);
    var totalItems = xmldoc.SelectNodes(
             "/root/node/LastName/").Count;
    

    【讨论】:

      【解决方案3】:
      var cnt = element.Descendants("ID").Count();
      

      【讨论】:

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