17.8. Transforming XML to HTML

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 in a text file. 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 transposing the XML data into a more readable form.

Solution

The solution for this is to use an XSLT stylesheet to transform the XML into another format using the XslTransform class. In the example code, we are transforming some personnel data from a fictitious business stored in Personnel.xml. First, we load the stylesheet for generating HTML output, then we perform the transformation to HTML via XSLT using the PersonnelHTML.xsl stylesheet. After that, we transform the data to comma-delimited format using the PersonnelCSV.xsl stylesheet:

public static void TransformXML( ) { // Create a resolver with default credentials. XmlUrlResolver resolver = new XmlUrlResolver( ); resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; // transform the personnel.xml file to html XslTransform transform = new XslTransform( ); // load up the stylesheet transform.Load(@"..\..\PersonnelHTML.xsl",resolver); // perform the transformation transform.Transform(@"..\..\Personnel.xml",@"..\..\Personnel.html",resolver); // transform the personnel.xml file ...

Get C# Cookbook 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.