Monday, September 14, 2009

Querying XML using LINQ to XML in C#

<Customers>
<Customer id="1" orderdate="4/1/1968">Paul Koch</Customer>
<Customer id="2" orderdate="7/5/1988">Bob Kelly</Customer>
<Customer id="3" orderdate="3/24/1990">Joe Healy</Customer>
</Customers>
Assume this is the XML file you want to search and it is stores in C:\ drive.
 XDocument myDoc = XDocument.Load(@"C:\sample.xml");
Ex –1 get the customer who’s having id 2
Method 1
you can use var type variable and through iteration you can get the result. this method is good when you have more than one record.
 var q = from c in myDoc.Descendants("Customer")
 where (int)c.Attribute("id") == 2
 select c;
Receiving values by iterating through foreach loop. 
 foreach (XElement item in q)
 {
 String id =item.Attribute("id").Value;
 String orderdt = item.Attribute("orderdate").Value;
 String name = item.Value;
}
Method 2
if you know it is a single value (assume id is unique for customers)
 XElement x = myDoc.Descendants("Customer").Single(c => 
 Convert.ToInt32(c.Attribute("id").Value) ==2);
 String id = x.Attribute("id").Value;
 String orderdt = x.Attribute("orderdate").Value;
 String name = x.Value;
Post a Comment