Prerequisite: in order to use .Count()
you need to import the namespace System.Linq
:
using System.Linq;
You can filter the descendant elements using the Descendants
method with the name "ID", then count the results:
int count = xml.Descendants("ID").Count();
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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…