如何获得XML或可变的XElement特定元素计数 [英] How to get specific element Count in XML or XElement variable

查看:305
本文介绍了如何获得XML或可变的XElement特定元素计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I declare a XElement variable and create the XML assigning it to that. How I can get count of ID elements in this XML variable in C#?

推荐答案

您可以使用 筛选后代后代元素名为ID的方法,然后计算的结果:

You can filter the descendant elements using the Descendants method with the name "ID", then count the results:

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



请注意,后裔看起来通过各级。如果你有比也有一个 ID以外的元素子元素,你想更具体。在这种情况下,数属于元素 ID 子元素,你可以使用:

Be aware that Descendants looks through all levels. If you had an element other than Person that also had an ID child element, you would want to be more specific. In that case, to count ID child elements that belong to Person elements, you would use:

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

这篇关于如何获得XML或可变的XElement特定元素计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆