Sunday, January 22, 2017

How to convert XML to HTML

HTML
||
||
XML

Recently one of my client come up with a feature like "Display received XML into HTML by adding CSS. JSON data recieved from Server using AJAX and data pasted into UI dynamically.

As per this new requirement API calls return XML format, that need to pasted in UI dynamically. After doing some search, I understood that applications which store/use data in XML uses XSLT to convert to HTML.

There are so many tags available from XSLT which will help to convert XML to HTML based on data available in XML and conditions.

XSLT have conditional tags which are every interesting feature from XSLT. We all know all tag based languages used for data transfer and UI purposes. 

<xsl:if test="conditional_expression">
.... other conditions and HTML and content....</xsl:if>

XSLT loading in browser using Javascript.


if (window.ActiveXObject || "ActiveXObject" in window)
        {
// Loading XML file in IE
            var xml = new ActiveXObject("Microsoft.XMLDOM")
            xml.async = false
            xml.load(page + ".xml")

// Load the XSL file in IE
            var xsl = new ActiveXObject("Microsoft.XMLDOM")
            xsl.async = false
            xsl.load(page1 + ".xsl")

// Transform in IE
            return  (xml.transformNode(xsl))
        }
        else if (document.implementation && document.implementation.createDocument)
        {
            xsltProcessor = new XSLTProcessor();
            xsltProcessor.importStylesheet(xsl);
            resultDocument = xsltProcessor.transformToFragment(xml, document);
        }
    return (new XMLSerializer().serializeToString(resultDocument));