如何获取XML或XElement变量中特定元素的数量

21

考虑以下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元素的计数?

3个回答

42

如果您不使用 Elements("Employees"),它会返回0 :-? - Arian
1
@Nima 根据你的样例输入,Employees 是根节点。如果你使用的是 XElement,那么查询中就不需要包含 Elements("Employee")。如果它不是根元素,那么你可以选择包含它,或者使用 xml.Descendants("Person").Elements("ID").Count(),从而避免逐个遍历 XML 元素的需要。 - Ahmad Mageed
1
这个答案还有效吗?据我所知,Descendants()Elements()都返回一个IEnumerable,它似乎没有Count()方法。我是否漏掉了一些明显的东西? - Jon Heggland

1
XmlDocument xmldoc = new XmlDocument();
 xmldoc.Load(XmlPath);
var totalItems = xmldoc.SelectNodes(
         "/root/node/LastName/").Count;

0
var cnt = element.Descendants("ID").Count();

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