Monday, March 02, 2009

.NET 3.5: LINQ To XML

XML has been a very flexible language to use. It can present or format data in many forms, whether it's a Word file, configuration files, WSDLs and databases. But if you're going to look at it, XML is still very hard to work with. From my experience, when I've been given an XML file, then the requirements or business rule on how I will manipulate it, you'll certainly hear a sigh.

You can manipulate an XML file by using XPath, XQuery and XSLT, but you need to study those stuffs first before you can use them. And also, creating an in-memory XML is very cumbersome. For example, I'm going to create this XML:
Photobucket
I'll show you a common way of creating this XML if I'm going to use the XmlDocument object of the DOM (Document Object Model) by Microsoft. I'll be leaning towards the C# implementation for this because I'm more familiar with it. Here it is:

PhotobucketThis style of coding is a bit long if you're just going to construct a simple XML, and it gives you a few clues about the XML tree structure. Well, the LINQ to XML gives the solution for this problem, and it will support an approach called functional construction. Here's the conversion of the code above using LINQ to XML:

Photobucket
Notice that by indenting the code construct, the XML tree show you the underlying XML. The functional construction gives you a powerful approach when you're creating XML elements, it lets you create the whole XML construct with just one statement.

Another feature that I like to include here is the Language Integrated Query for XML, that's why it's LINQ. LINQ provides you a consistent experience of querying across different data models. I'll be showing a sample query for LINQ to XML:

Photobucket
The object returnXDoc will have the root elemet "student", then have the child nodes "name" and "phone" from the sample XML I showed above.

Query expressions provide an ease-of-use layer on top of the underlying explicit dot notation similar to the way that foreach is an ease-of-use mechanism that consists of a call to GetEnumerator() and a while loop. When working with XML, you will probably find both approaches useful.

There are methods that returns an IEnumerable<object> type, you can manipulate XML (add, update or remove an element/node) and it gives you the in-line queries. Just explore this new API, LINQ to XML is very flexible and it will provide you with a modularized, simple and optimized contruct in developing applications that involves XML.

No comments: