Custom Search
Logiclabz
  • Home
  • C#
  • .Net C# Function to Convert XML Document into HTML String using XSLT

.Net C# Function to Convert XML Document into HTML String using XSLT

  

XML file can be transformed to HTML using XSLT. The following C# function would helps us converting XML Document to HTML String using XSLT file.

Namespace used:
	using System.Xml;
	using System.Xml.Xsl;
	public static string ConvertXML(XmlDocument InputXMLDocument, string XSLTFilePath
 , XsltArgumentList XSLTArgs)
        {
            System.IO.StringWriter sw = new System.IO.StringWriter();
            XslCompiledTransform xslTrans = new XslCompiledTransform();
            xslTrans.Load(XSLTFilePath);
            xslTrans.Transform(InputXMLDocument.CreateNavigator(), XSLTArgs, sw);
            return sw.ToString();
        }
Sample XML file
	<?xml version="1.0" encoding="utf-8" ?>
	<sexystars>
	  <category name="Bollywood">
	    <sexystar name="Antra mali" />
	    <sexystar name="Deepika Padukone" />
	    <sexystar name="Mandira Bedi" />
	  </category>
	  <category name="Hollywood">
	    <sexystar name="Jennifer Lopez" />
	    <sexystar name="Jessica Alba" />
	  </category>
	</sexystars>
Sample XSLT file
	<?xml version="1.0" encoding="UTF-8" ?>
	<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	  <xsl:output omit-xml-declaration="yes"/>
	  <xsl:template match="sexystars">
	    <div>
	      <xsl:apply-templates select="category" />
	    </div>
	  </xsl:template>
	  <xsl:template match="category">
	    <h2>
	      <xsl:value-of select="@name"/>
	    </h2>
	    <ul>
	      <xsl:apply-templates select="sexystar" />
	    </ul>
	  </xsl:template>
	  <xsl:template match="sexystar">
	    <li>
	      <xsl:value-of select="@name"/>
	    </li>
	  </xsl:template>
	</xsl:stylesheet>
ConvertXML function can be used as
	XmlDocument xDoc=new XmlDocument();
        xDoc.Load(@"C:\sample.xml");
        string returnhtml = ConvertXML(xDoc, @"C:\sample.xslt", new XsltArgumentList());
Output would be
	<div>
	  <h2>Bollywood</h2>
	    <ul>
	      <li>Antra mali</li>
	      <li>Deepika Padukone</li>
	      <li>Mandira Bedi</li>
	    </ul>
	  <h2>Hollywood</h2>
	    <ul>
	      <li>Jennifer Lopez</li>
	      <li>Jessica Alba</li>
	    </ul>
	</div>



  


Leave a reply


Comments

  • ruble sedan says:
    Mar 21, 12

    very nice!!.. thanks



Do you like this post?