Wednesday, June 6, 2012

LINQ to XML parse XML Elements


In this post LINQ to XML parse XML Elements, we shall see how to parse a XML fragment and extract the Element values from the XML. In the post XElement Example, we have seen how to create XMLs using the XElement file, here we will see on how to parse the same XML  and extract the Element values.

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 list of Names from the XML, using the following code.

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

foreach (XElement fName in empNames)
{
Response.Write(fName.Element("FirstName").Value + ", " +   fName.Element("LastName").Value + "</br>");
}

  When this code is executed, the following output will be Printed.    
Henry, Ford
Bill, Gates

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

Search Flipkart Products:
Flipkart.com

No comments: