Transform XML using XSLT document to HTML output in IE

Hi All,

I was developing a JavaScript function that takes an xml document for a HTTP response and i want to transform it to HTML in my page or web part (in SharePoint world).

I had code that uses transformNode that is not supported by IE anymore starting from version 9 and i am using IE 11.

Actually, i spend a quite number of hours to find out what is the best way to load an XML document and transform it using a XSLT file into a HTML output in IE 11 since i was getting different errors.

You will find a lot of posts/blogs are referring to this code snippet to transform xml using xslt file in IE:

var xml = new ActiveXObject("Microsoft.XMLDOM"); 
var xslt = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
xml.load("data.xml");
xslt.load("data.xls");

var processor = new ActiveXObject("Msxml2.XSLTemplate");
processor.stylesheet = xslt;

var objXSLTProc = processor.createProcessor();
objXSLTProc.input = xml;
objXSLTProc.transform();
var output = objXSLTProc.output;

Above code doesn’t work in IE 11, for 2 reasons:
1) IE 11 doesn’t support load method! you have to use loadXML instead.
2) you have to get the string representations of both xml and xslt to be able to use loadXML and then process the output.

Here is the code snippet that works with IE 11:

function transformXml(xml)
{

var loadedXslt = LoadXSLTDocumentInIE(“myxslt.xslt”);

  // Load the XML Document
  var xmlDoc = new ActiveXObject(“Msxml2.DOMDocument.3.0″);
  xmlDoc.async = false;
  xmlDoc.resolveExternals = false;
  xmlDoc.loadXML((new XMLSerializer()).serializeToString(xml));
   console.log(xmlDoc.parseError.reason); // for debugging, to make sure there is no errors after loading the document.

    // Load the XSL file
    var xslt = new ActiveXObject(“Msxml2.XSLTemplate”);
    var xslDoc = new ActiveXObject(“Msxml2.FreeThreadedDOMDocument”);
    xslDoc.async = false;
    xslDoc.loadXML(loadedXslt.responseText);
    xslt.stylesheet = xslDoc;

    var xslProc = xslt.createProcessor();
    xslProc.input = xmlDoc;
    xslProc.transform();
    return xslProc.output;

}

// function to load XSLT document by name, this document has to be accessible through the web browser.
function loadXSLTDocumentInIE(fileName) {
   xhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
   try {
        xhttp.responseType = “msxml-document”;
    } catch (e) {
        //console.log(“couldn’t set the response type msxml in IE”);
    }
    xhttp.open(“GET”, fileName, false);
    xhttp.send(“”);
    return xhttp;
}


This code works like a champ in IE 11 :)

Hope this helps.





Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>