Friday 29 July 2011

Querying xml using LINQ

LINQ to XML

Suppose that instead of hard-coding our suppliers and products, we’d used the following XML file:
<?xml version="1.0"?>
<Data>
<Products>
<Product SupplierID="1">
<Name> West Side Story</Name>
<Price>9.99</Price>
</Product>
<Product SupplierID="2">
<Name>Assassins</Name>
<Price>14.99</Price>
</Product>
<Product SupplierID="1">
<Name>Frogs</Name>
<Price>9.99</Price>
</Product>
</Products>
<Suppliers>
<Supplier SupplierID="1">
<Name>Solely Sondheim</name>
</Supplier>
<Supplier SupplierID="2">
<Name>CD-by-CD-by-Sondheim</name>
</Supplier>
</Suppliers>
</Data>

The file is simple enough, but what’s the best way of extracting the data from it? How do we query it? Join on it?. The following listing shows how much work we have to do in LINQ to XML.
XDocument doc = XDocument.Load("data.xml");
var filtered = from p in doc.Descendants("Product")
join s in doc.Descendants("Supplier")
on (int)p.Attribute("SupplierID")
equals (int)s.Attribute("SupplierID")
where (decimal)p.Element("Price") > 10
orderby (string)s.Element("Name"),
(string)p.Element("Name")
select new
{
SupplierName = (string)s.Element("Name"),
ProductName = (string)p.Element("Name")
};
foreach (var v in filtered)
{
Console.WriteLine("Supplier={0}; Product={1}",
v.SupplierName, v.ProductName);
}

No comments:

Post a Comment