Display XML Data As HTML Using XSLT In ASP.NET MVC

Introduction
 
I got a requirement to display XML data in a style/design format. If we browse an XML file directly, then it displays the XML nodes with the data in browser. So, XSLT helps us to display XML data in a design/specific format. Here, we will discuss how XSLT can be implemented in ASP.NET MVC.

Using Code

First, we design XML and XSLT. XML file contains data and XSLT file contains how XML data will display in HTML design. Next, we create custom HTML helper to call the method which transforms XML data with XSLT content and generates HTML content.
 
XML
 
The following XML content will we use in our example. It contains countries with no. of medals won in Rio 2016 Olympic. 
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <RioMedals>  
  3.     <Country Name="America" Gold="43" Silver="37" Bronze="36"></Country>  
  4.     <Country Name="GreatBritain" Gold="27" Silver="22" Bronze="17"></Country>  
  5.     <Country Name="China" Gold="26" Silver="18" Bronze="26"></Country>  
  6.     <Country Name="Russia" Gold="17" Silver="17" Bronze="19"></Country>  
  7.     <Country Name="India" Gold="1" Silver="1" Bronze="1"></Country>  
  8. </RioMedals>  
XSLT 
 
The Extensible Stylesheet Language Transformation (XSLT) language is for transforming XML documents into XHTML documents or to other XML documents. Data transformation means parsing an input XML document into a tree of nodes and then converting the source tree into a result tree. Transformation is about data exchange. More on XSLT, visit here.
 
In below XSLT code, it creates a table and it searches country in XML content; then display name, no of medals in Gold, Silver, Bronze in rows based on countries.
  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">  
  2.     <xsl:template match="/*">  
  3.         <table cellpadding="0" cellspacing="0" border="1">  
  4.             <tr style="color: green;">  
  5.                 <th>Country</th>  
  6.                 <th>Gold</th>  
  7.                 <th>Silver</th>  
  8.                 <th>Bronze</th>  
  9.             </tr>  
  10.             <xsl:for-each select="Country">  
  11.                 <tr style="text-align: center;">  
  12.                     <td>  
  13.                         <xsl:value-of select="@Name"></xsl:value-of>  
  14.                     </td>  
  15.                     <td>  
  16.                         <xsl:value-of select="@Gold"></xsl:value-of>  
  17.                     </td>  
  18.                     <td>  
  19.                         <xsl:value-of select="@Silver"></xsl:value-of>  
  20.                     </td>  
  21.                     <td>  
  22.                         <xsl:value-of select="@Bronze"></xsl:value-of>  
  23.                     </td>  
  24.                 </tr>  
  25.             </xsl:for-each>  
  26.         </table>  
  27.     </xsl:template>  
  28. </xsl:stylesheet>  
Controller
 
In Controller(HomeController.cs), add Index() as an action. It retrieves contents from XML file and bind to ViewBag object.
  1. public ActionResult Index()  
  2. {  
  3.     string medalsXML = System.IO.File.ReadAllText(Server.MapPath("Data/Medals.xml"));  
  4.     ViewBag.Medals = medalsXML;  
  5.   
  6.     return View();  
  7. }  
View
 
We need to create custom HTML helper to view the XML content as HTML. Custom helper can be created in two ways:
 
Step 1: Using extension method HTMLHelper class
 
Create a static class called CustomHTMLHelper and create a static method RenderXml() which receives two parameters. One is XML content and second one is xslt file path. RenderXml() is an extension method which calls from View and it returns data as HtmlString type. 
  1. public static class CustomHTMLHelper  
  2. {  
  3.     /// <summary>  
  4.     /// Applies an XSL transformation to an XML document  
  5.     /// </summary>  
  6.     /// <param name="helper"></param>  
  7.     /// <param name="xml"></param>  
  8.     /// <param name="xsltPath"></param>  
  9.     /// <returns></returns>  
  10.     public static HtmlString RenderXml(this HtmlHelper helper, string xml, string xsltPath)  
  11.     {  
  12.         XsltArgumentList args = new XsltArgumentList();  
  13.         // Create XslCompiledTransform object to loads and compile XSLT file.  
  14.         XslCompiledTransform tranformObj = new XslCompiledTransform();  
  15.         tranformObj.Load(xsltPath);  
  16.   
  17.         // Create XMLReaderSetting object to assign DtdProcessing, Validation type  
  18.         XmlReaderSettings xmlSettings = new XmlReaderSettings();  
  19.         xmlSettings.DtdProcessing = DtdProcessing.Parse;  
  20.         xmlSettings.ValidationType = ValidationType.DTD;  
  21.   
  22.         // Create XMLReader object to Transform xml value with XSLT setting   
  23.         using (XmlReader reader = XmlReader.Create(new StringReader(xml), xmlSettings))  
  24.         {  
  25.             StringWriter writer = new StringWriter();  
  26.             tranformObj.Transform(reader, args, writer);  
  27.   
  28.             // Generate HTML string from StringWriter  
  29.             HtmlString htmlString = new HtmlString(writer.ToString());  
  30.             return htmlString;  
  31.         }  
  32.     }  
  33. }  
Add the below tag to Web.Config namespace section so it will available in all View pages.
  1. <add namespace=”CustomHTMLHelper” />  
Now, you can call extension method (RenderXml()) with passing xml content and xslt file path.
  1. @Html.RenderXml(ViewBag.Medals as string, Server.MapPath("Data/Medals.xslt"))    
Step 2: Using Static method
 
Create static class and add static method RenderXMLData() with parameters xml content and xslt file path. The logic is the same as above extension Helper class.
  1. public static HtmlString RenderXMLData(string xml, string xsltPath)  
  2. {  
  3.     XsltArgumentList args = new XsltArgumentList();  
  4.     // Create XslCompiledTransform object to loads and compile XSLT file.  
  5.     XslCompiledTransform tranformObj = new XslCompiledTransform();  
  6.     tranformObj.Load(xsltPath);  
  7.   
  8.     // Create XMLReaderSetting object to assign DtdProcessing, Validation type  
  9.     XmlReaderSettings xmlSettings = new XmlReaderSettings();  
  10.     xmlSettings.DtdProcessing = DtdProcessing.Parse;  
  11.     xmlSettings.ValidationType = ValidationType.DTD;  
  12.   
  13.     // Create XMLReader object to Transform xml value with XSLT setting   
  14.     using (XmlReader reader = XmlReader.Create(new StringReader(xml), xmlSettings))  
  15.     {  
  16.         StringWriter writer = new StringWriter();  
  17.         tranformObj.Transform(reader, args, writer);  
  18.   
  19.         // Generate HTML string from StringWriter  
  20.         HtmlString htmlString = new HtmlString(writer.ToString());  
  21.         return htmlString;  
  22.     }  
  23. }  
Add the below tag to Web.Config namespace section as we did before for Extension Method approach.
  1. <add namespace=”CustomHTMLHelper” />    
 Now, you can call extension method (RenderXMLData()) with passing xml content and xslt file path.
  1. @CustomHTMLHelper.RenderXMLData(ViewBag.Medals as string, Server.MapPath("Data/Medals.xslt"))  
After running the application, it shows this image(Figure 1) as output.
 
 
Figure 1:  Output XML as HTML
 
Conclusion
 
In this article, we learned how to render XML data HTML using XSLT. Secondly, we also discussed about creating Custom HTMLHelper in ASP.NET MVC.
 
Hope it helps.


Similar Articles