Tuesday, January 24, 2012

Reading Xml Elements contained within a XML using LINQ

In today's post i will read an XML file whose root node contains only XML elements. And this task will be achieved with the help of LINQ in C#.

Following Customer.xml file will be used for this sample demonstration:-

<?xml version="1.0" encoding="utf-8" ?>
    <Name>Steve Smith</Name>
    <CompanyName>Star Infotech Ltd</CompanyName>
    <JobTitle>Project Manager</JobTitle>
    <Address>133, 13th Floor, 2nd Street</Address>
    <City>New York</City>
    <Country>United States</Country>

 //Loading the customers xml into the XDocument object:
XDocument xDoc = 
            XDocument.Load(AppDomain.CurrentDomain.BaseDirectory+ "/Customers.xml");

//retreiving all the elements which are part of root node Customer
IEnumerable<XElement> custDetails = 
                                                    from row in xDoc.Descendants("Customer").Elements()
                                                    select row;

 foreach (XElement xEle in custDetails)
     //Displaying the Customer details one Xml Element at a time


You can see the details of the customer in the console output window.

Its really amazing how easy and helpful LINQ is to work with XML.

Happy Coding............

No comments :

Post a Comment