Wednesday, June 6, 2012

LINQ to XML parse Child Elements


In this post LINQ to XML parse Child Elements, we shall see how to parse the values of Child elements from the 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 to extract the values from the subsequent Child elements.

Assume that we have the following XML fragment


   <Employees>
 <Employee>
<Name>
       <FirstName>Henry</FirstName>
       <LastName>Ford</LastName>
</Name>
<Age>65</Age>
  </Employee>
  <Employee>
<Name>
    <FirstName>Bill</FirstName>
    <LastName>Gates</LastName>
</Name>
<Age>55</Age>
  </Employee>
  </Employees>

  Now we will parse the XML and get the Name & Age of all the Employees from the XML, using the following code.

XElement xEmp = XElement.Load(@"D:\Employees.xml");
var empNames = from emps in xEmp.Elements("Employee")
               select emps;

foreach (XElement empDetails in empNames)
{
    Response.Write("Name: " +
    empDetails.Element("Name").Element("FirstName").Value + "
</br>");
    Response.Write("Age: " + empDetails.Element("Age").Value + "</br></br>");
}  

  When this code is executed, the output will be
  
Name: Henry
Age: 65

Name: Bill
Age: 55

Notice that the LINQ query is filtering only for the elements with name Employee, but we have iterated through the First level child node Age and extracted the values of the child elements, in the line.

empDetails.Element("Age").Value

We have also iterated through the 2nd level Name -> FirstName child elements and extracted the values of the child elements, in the line.

empDetails.Element("Name").Element("FirstName").Value

  That’s it we have parsed an XML fragment using LINQ to XML and extracted the Child Element

Search Flipkart Products:
Flipkart.com

No comments: