LINQ to XML: A Mild Success Story
In a project I am working on I’ve come to discover the need to stitch together multiple data sources. The product itself needs to maintain a certain level of information within a database but it must also sync with a standalone application that is exporting its data.
Initially I thought this would be a nightmare to handle. Getting the exported data as XML, looping and parsing through the XML document and creating a new class and inserting it into the proper table so my project can use it. Thankfully I am all about LINQ these days (with the exception of LINQ-to-SQL) and LINQ to XML made my life amazingly simple.
Let’s take the following XML file:
<PecanProject> <Products> <Product> <Id>1</Id> <Name>Black Widget</Name> <Price>0.86</Price> </Product> <Product> <Id>2</Id> <Name>Yellow Widget</Name> <Price>0.99</Price> </Product> <Product> <Id>3</Id> <Name>Green Widget</Name> <Price>1.25</Price> </Product> <Product> <Id>4</Id> <Name>Red Widget</Name> <Price>1.11</Price> </Product> </Products> </PecanProject>
Traditionally this sort of file would be easier to work with than a plain text file but it certainly isn’t elegant. Using LINQ to XML I can very elegantly select from the XML as though it were a normal data source and then map the results into a class.
Here is how:
var doc = XElement.Load("filename.xml"); var projectList = from prod in doc.Descendants("Product") select new Product { Id = (int)prod.Element("Id"), Name = (string)prod.Element("Name"), Price = (double)prod.Element("Price"), }; foreach (var product in projectList) { // Do something with your new product. PerformActionOnProduct(product); }
This of course assumes a Product class that has three public properties named Id, Name, and Price.
This was amazingly swift, easy to code, easy to read, and will be easy to maintain. Not only that but you can actually perform calculations on the incoming code. I, for example, am importing Customers and send the address id to the address repository to actually return the proper class, rather than just the id.
It is a very clean way of doing things. I am in love.