Pages

Friday, March 20, 2009

LINQ to XML

Getting Started (LINQ to XML) - a wonderful new way to work with XML files. No hurdles with XmlReader, or navigating the DOM tree with XmlDocument manually. Linq to XML extends the functionality of the DOM by supporting the the Linq queries against the model. These queries are syntactically different to XPath but provide similar functionality.

This allows queries like

XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
foreach (XElement result in doc.Elements("Root").Elements("Customers"))
Console.WriteLine(result);
The common commands for working with XML files in Linq would be:
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var query = doc.Element("Root").Element("Customers").Elements();
foreach (XElement result in query)
Console.WriteLine(result);
Samples in C# are available for download on MSDN (link). These are the same samples that come with Visual Studio 2008.

No comments: