C# 如何在 XML 或 XElement 变量中获取特定元素计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8764510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get specific element Count in XML or XElement variable
提问by Arian
Consider this XML:
考虑这个 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>
I declare a XElementvariable and create the XML assigning it to that. How I can get count of IDelements in this XML variable in C#?
我声明了一个XElement变量并创建了将它分配给它的 XML。如何ID在 C# 中获取此 XML 变量中的元素计数?
采纳答案by Ahmad Mageed
Prerequisite:in order to use .Count()you need to import the namespace System.Linq:
先决条件:为了使用.Count()你需要导入命名空间System.Linq:
using System.Linq;
You can filter the descendant elements using the Descendantsmethodwith the name "ID", then count the results:
您可以使用名称为“ID”的Descendants方法过滤后代元素,然后计算结果:
int count = xml.Descendants("ID").Count();
Be aware that Descendantslooks through all levels. If you had an element other than Personthat also had an IDchild element, you would want to be more specific. In that case, to count IDchild elements that belong to Personelements, you would use:
请注意,Descendants查看所有级别。如果您有一个除此之外的元素Person也有一个ID子元素,您会希望更具体。在这种情况下,要计算ID属于Person元素的子元素,您可以使用:
int count = xml.Elements("Person")
.Elements("ID")
.Count();
回答by Nuffin
var cnt = element.Descendants("ID").Count();
回答by Kasinatha Durai Avudaiyappan
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(XmlPath);
var totalItems = xmldoc.SelectNodes(
"/root/node/LastName/").Count;

