15.8. Transforming XML

Problem

You have a raw XML document that you need to convert into a more readable format. For example, you have personnel data that is stored as an XML document, and you need to display it on a web page or place it in a comma-delimited text file for legacy system integration. Unfortunately, not everyone wants to sort through reams of XML all day; they would rather read the data as a formatted list or within a grid with defined columns and rows. You need a method of transforming the XML data into a more readable form as well as into the comma-delimited format.

Solution

The solution for this is to use LINQ to XML to perform a transformation in C#. In the example code, you transform some personnel data from a fictitious business stored in Personnel.xml. The data is first transformed into HTML, and then into comma-delimited format:

 // LINQ way XElement personnelData = XElement.Load(@"..\..\Personnel.xml"); // Create HTML XElement personnelHtml = new XElement("html", new XElement("head"), new XElement("body", new XAttribute("title","Personnel"), new XElement("p", new XElement("table", new XAttribute("border","1"), new XElement("thead", new XElement("tr", new XElement("td","Employee Name"), new XElement("td","Employee Title"), new XElement("td","Years with Company") ) ), new XElement("tbody", from p in personnelData.Elements("Employee") select new XElement("tr", new XElement("td",p.Attribute("name").Value), new XElement("td",p.Attribute("title").Value), new XElement("td", ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.