Display XML Data as HTML Using XSL Transformation in ASP.Net

Sometimes we get a requirement to display XML data in a style/design format. If we browse a XML file directly then it displays the XML nodes with data. So XSLT helps us to display XML data in a design/specific format.

My previous article explained XML, XSLT and CSS. To learn more XSL and the syntax refer to here.
 
How XSLT works internally

There are two main components in XSLT that helps transformations, XSLT Processor and XSL Formatter. First, the XSLT processor takes two inputs, a XML document and a XSLT stylesheet. The XSLT processor starts from the root node and then it goes for the root node's children. The processor searches the stylesheet element to see if any template element and other XSLT elements are defined. As per the defined XSLT rules it fetches data from the XML document and generates a results tree in XML format. The XML formatter takes input as a result tree and generates the final end products as HTML, text other XML format.
 
Please see Figure 1 for a better understanding.

 
Figure 1: XSL Transformation internally
 
To implement a XSL transformation in ASP.NET we need to execute the following procedure.

Step 1

In this step we will add a XML file (XMLFile1.xml) and design it.

Go to your project, Add New Item and click on Data section. Then select XML file.

xml file
Figure 2: Adding XML document in project 
 
Code
  1. <?xml version="1.0" encoding="iso-8859-1"?>   
  2. <!-- Edited by XMLSpy® -->    
  3. <breakfast_menu>    
  4.     <food>    
  5.         <name>Biriyani</name>    
  6.         <price>$5.95</price>    
  7.         <description>Rice with chicken</description>    
  8.         <calories>650</calories>    
  9.     </food>    
  10.     <food>    
  11.         <name>Juice</name>  
  12.         <price>$1.95</price>    
  13.         <description>Fruit juices like mango, banana, apple</description>    
  14.         <calories>200</calories>    
  15.     </food>    
  16. </breakfast_menu>    
Step 2

In this step we need to add a XSLT file (XSLTFile1.xslt) and design it.

Use the following preceding, Step 1, to add the XSLT file. After adding the XSLT file we need to design it.

Code
  1. <?xml version="1.0" encoding="iso-8859-1"?>    
  2. <!-- Edited by XMLSpy® -->    
  3. <html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">    
  4.     <body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">    
  5.         <xsl:for-each select="breakfast_menu/food">    
  6.             <div style="background-color:teal;color:white;padding:4px">    
  7.                 <span style="font-weight:bold">    
  8.                     <xsl:value-of select="name"/>    
  9.                 </span>    
  10.                 - <xsl:value-of select="price"/>    
  11.             </div>    
  12.             <div style="margin-left:20px;margin-bottom:1em;font-size:10pt">    
  13.                 <xsl:value-of select="description"/>    
  14.                 <span style="font-style:italic">    
  15.                     <xsl:value-of select="calories"/> (calories per serving)    
  16.                 </span>    
  17.             </div>    
  18.         </xsl:for-each>    
  19.     </body>    
  20. </html>    

In the preceding XSLT file, we are using a for-each element that will match XML nodes (breakfast_menu/food). It will collect all the nodes in XML data that match depending on the defined pattern(breakfast_menu/food) and loop over it. The value-of element displays the XML data. Lastly a div and span are added to make the display the ofdata in the design format with inline styles.

Step 3

Now we are ready with the XML and XSLT file. Next we need to write code for loading the XML data then transform and display it.                                  

Here we can implement a XSL transformation in the following two ways: 
  1. With XML Control
  2. XslCompiledTransform class Without XML control

1. With XML Control

ASP.NET has a XML control present in the Toolbox and using that control we can do the XSL transformation.

First it loads the XML content in a variable using File.ReaAllText(). Then it assigns XML content to the XML control using the DocumentContent property. Lastly it assigns a XSLT file to the XML control using the TransformSource property. Then the XML control loads XML content, transforms it into HTML content and renders it in the browser.

Please refer to the following code: 

  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     // This is being read from the same folder as this page is in.(only for demo purpose)  
  4.     // In real applications this xml might be coming from some external source or database.  
  5.     string xmlString = File.ReadAllText(Server.MapPath("XMLFile1.xml"));  
  6.   
  7.     // Define the contents of the XML control  
  8.     Xml1.DocumentContent = xmlString;  
  9.   
  10.     // Specify the XSL file to be used for transformation.  
  11.     Xml1.TransformSource = Server.MapPath("XSLTFile1.xslt");  
  12. }  

2. XslCompiledTransform class Without XML control 

In the .NET Framework a class XslCompiledTransform is present in the System.Xml.Xsl namespace that can be used to do the transformation. Then the XslCompiledTransform object calls the Load() method to load the XSLT file content into the object. Next it calls the Transform() method to create a HTML string and write data into the TextReader object.

Here I added a Label control to display the generated HTML content that is generated from XML data. The following code can be used to transform XML data from an XML file (tutorial.xml) using the XSLT file(tutorial.xslt).

Add the following namespaces:

  1. using System.Xml;  
  2. using System.Xml.Xsl;  
  3. using System.IO;  
  4. using System.Text;  
Code
  1. protected void Button2_Click(object sender, EventArgs e)    
  2. {    
  3.     Xml1.Visible = false;    
  4.     ltlTutorial.Visible = true;    
  5.     
  6.     // Getting file path    
  7.     string strXSLTFile = Server.MapPath("XSLTFile1.xslt");    
  8.     string strXMLFile = Server.MapPath("XMLFile1.xml");    
  9.     
  10.     // Creating XSLCompiled object    
  11.     XslCompiledTransform objXSLTransform = new XslCompiledTransform();    
  12.     objXSLTransform.Load(strXSLTFile);    
  13.     
  14.     // Creating StringBuilder object to hold html data and creates TextWriter object to hold data from XslCompiled.Transform method    
  15.     StringBuilder htmlOutput = new StringBuilder();    
  16.     TextWriter htmlWriter = new StringWriter(htmlOutput);    
  17.     
  18.     // Creating XmlReader object to read XML content    
  19.     XmlReader reader = XmlReader.Create(strXMLFile);    
  20.     
  21.     // Call Transform() method to create html string and write in TextWriter object.    
  22.     objXSLTransform.Transform(reader, null, htmlWriter);    
  23.     ltlTutorial.Text = htmlOutput.ToString();    
  24.     
  25.     // Closing xmlreader object    
  26.     reader.Close();    
  27. }   
Now our code is ready to display XML data in design format. In Step 3 I used two options to do XSL transformations, so you can use any one of them.

Browse the aspx file and you can see output as in Figure 3.
 
           
Figure 3: Output of XSL Transformation in ASP.NET
 
If you go to the aspx view source then you will see the HTML tags generated and bind it to the label control.

Please see Figure 4 showing how the XSL transformation generates HTML output depending on the defined XSLT rules.
 
  
 Figure 4: HTML output after XSL Transformation
 
Conclusion

XML is one of the most commonly used data formats in the software industry. Any system that interacts with multiple other components will always use XML as the underlying communication or data format. The introduction of XSLT is one big advantage to XML where XML can be transformed into a presentable format. In this way the .NET Framework helps developers do XSLT transformations.
 
You can download the source code attached with the article.
 
I hope this helps you to understand the implementation of XSLT to display XML data.
 
Happy Coding!


Similar Articles