In this post LINQ to XML - Count Elements, we
shall see how to count the number of times a particular Element is repeated in
an XML. In the post LINQ to XML parse XML Elements, we saw how to extract values from specific elements, here
we shall see on how get the number of times the Element is repeated in the XML.
Assume that we have the following XML fragment
<Employees>
<Employee>
<Name>
<FirstName>Henry</FirstName>
<LastName>Ford</LastName>
</Name>
<Age>65</Age>
<Department Name="Automobile" />
</Employee>
<Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<Department Name="Software" />
<Department Name="Software" />
</Employee>
</Employees>
Now
we will parse the XML and get the Number of times the Employee tag is repeated in
the XML
XElement xEmp = XElement.Load(@"D:\Employees.xml");
var empNames = from
emps in xEmp.Elements("Employee")
select
emps;
Response.Write("Employee
Count: " + empNames.Count() + "</br></br>");
When
this code is executed, the output will be
Employee Count: 2
That’s
it we have parsed an XML fragment using LINQ to XML and got the number of times
the Employee tag is repeated in the XML.
Related Post
No comments:
Post a Comment