O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required