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", ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access