Trying to render XSLT stylesheet that's coming from API, thought it's working fine on Chrome, FF except IE.
I tried using the example from w3c which works but that's calling the XML and XSLT from a file, where as mine is coming from AJAX call success response.
W3school sample XSLT sample
My version is this
function getJson() {
$.get(url)..
var json2XMLResult = J2XML.json2xml_str(data);
getResultXsl(json2XMLResult )
}
function getResultXsl(json2xml) {
$.get(url)
.then(function (data) {
let resDefinition = data.Results.ResponseDisplayDefinition;
let xmlString = '<?xml version="1.0"?><Response>' + json2xml + '</Response>';
if (typeof DOMParser != "undefined") {
parseXml = function (xmlStr) {
return (new DOMParser()).parseFromString(xmlStr, "text/xml");
};
}
else if (typeof ActiveXObject != "undefined" &&
new ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function (xmlStr) {
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
}
else {
throw new Error("No XML parser found");
}
displayResult(xmlString, resDefinition);
})
}
Displaying XSLT in the html, the alert() below does show whether you're trying to render it on Chrome or IE,
function displayResult(xmlStrToConvert, xslStrToConvert) {
var xmlConverted = parseXml(xmlStrToConvert);
var xslConverted = parseXml(xslStrToConvert);
if (window.ActiveXObject || "ActiveXObject" in window) {
alert('It is IE but not showing anything');
var ex = xmlConverted.transformNode(xslConverted)
$('#xmlJson').append(ex);
} else {
alert('its not IE');
// code for Chrome, Firefox, Opera, etc.
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xslConverted);
var resultDocument = xsltProcessor.transformToFragment(xmlConverted, document);
$('#xmlJson').append(resultDocument);
}
}
Also tried var ex= xmlConverted.transformToFragment(xslConverted, document);
Can someone point-out what's wrong with this? Also couldn't open dev tool on IE11 which is harder to debug, but I can tell its something wrong with my code above.
Edit
Ajax Call with beforeSend can someone check if the below code is fine, though the transformNode() is returning Object doesn't support property or method 'transformNode' or XSLTProcessor() not defined
function transformXML(json2xml) {
$.ajax({
type: 'GET',
url: window.parent.__env.apiManagement + 'Preview/TypeDefinition?objectName=' + apiObjectResponse,
beforeSend: function (xhr, settings) {
if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
xhr = new XMLHttpRequest();
}
try { xhr.responseType = "msxml-document"; } catch (err) { }
},
success: function (data, status, xhr) {
var parseXml = new DOMParser();
var xslStylesheet = parseXml.parseFromString(data.Results.ResponseDisplayDefinition, "text/xml");
var xmlString = '<?xml version="1.0"?><Response>' + json2xml + '</Response>';
var convertedXML = parseXml.parseFromString(xmlString, "text/xml");
// // cross-browser logic omitted for simplicity
if(window.ActiveXObject || xhr.responseType == "msxml-document") {
var ex = convertedXML.transformNode(xslStylesheet);
console.log('>>> ', convertedXML)
alert(xmlString)
$('#xmlJson').append(ex);
}
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument) {
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xslStylesheet);
var resultDocument = xsltProcessor.transformToFragment(convertedXML, document);
$('#xmlJson').append(resultDocument);
}
}
});
}
IE 11 supports DOMParser but using it builds an IE XML DOM document which does not have any support for XSLT. So you at least need to change the order of checks, if you are coding for IE and want to do XSLT then make sure you create an MSXML DOM document using ActiveXObject, then you can use transformNode on it.
As you seem to want to parse XML and XSLT from strings and then use client-side XSLT transformation I would suggest to use an approach like in https://martin-honnen.github.io/xslt/2016/test2016123001.html, which does
function parseXmlStringForTransformation(xml) {
try {
var doc = new ActiveXObject('Msxml2.DOMDocument.6.0');
doc.loadXML(xml);
return doc;
}
catch (e) {
var domParser = new DOMParser();
var doc = domParser.parseFromString(xml, 'application/xml');
return doc;
}
}
and then uses XSLTProcessor where supported or the corresponding MSXML 6 ActiveX XSLT API to run the transformation:
function transform(xmlDoc, xslDoc, xsltParams, targetElement) {
if (typeof XSLTProcessor !== 'undefined') {
var proc = new XSLTProcessor();
proc.importStylesheet(xslDoc);
for (var prop in xsltParams) {
proc.setParameter(null, prop, xsltParams[prop]);
}
var resultFrag = proc.transformToFragment(xmlDoc, targetElement.ownerDocument);
targetElement.textContent = '';
targetElement.appendChild(resultFrag);
}
else {
var template = new ActiveXObject('Msxml2.XslTemplate.6.0');
template.stylesheet = xslDoc;
var proc = template.createProcessor();
for (var prop in xsltParams) {
proc.addParameter(prop, xsltParams[prop]);
}
proc.input = xmlDoc;
proc.transform();
var resultHTML = proc.output;
targetElement.innerHTML = resultHTML;
}
}
You can then use that as in
document.addEventListener('DOMContentLoaded', function() {
transform(
parseXmlStringForTransformation('<root>...<\/root>'),
parseXmlStringForTransformation('<xsl:stylesheet ...>...<\/xsl:stylesheet>'),
{ }, // empty parameter object if you don't want to pass parameters from Javascript to XSLT
document.getElementById('d1') // target element in your HTML to insert the transformation result into
);
})
Related
I have a form where I get a XML, manipulate it as the user fill the form, and eventually transform this manipulated XML through a XSL. I need this solution to work in Chrome, Firefox and Internet Explorer 8 to 11 without compatibility mode.
I wrote a JSFiddle with the code I have working successfully to IE 9 (or at least without user complains), Chrome and Firefox. But I have an issue on IE 11. When my code tries to perform transformNode from ActiveXObject. I've tried some suggestions I've found in several sites, including here, but some simply doesn't worked or started throwing exceptions when my code tried to manipulate the XML. So I need help on getting this code working properly.
Here is the JSFiddle: https://jsfiddle.net/mfedatto/6nsc5bf1/
HTML
<div id="wrapper"></div>
<div id="console"></div>
JavaScript
try {
function getXmlDom(content) {
var xmlDom;
if (typeof window.DOMParser != "undefined") {
trace.push("Creating DOMParser");
xmlDom = (new window.DOMParser()).parseFromString(content, "text/xml");
trace.push("DOMParser created");
}
else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
try {
trace.push("Creating MSXML2.DOMDocument.6.0");
xmlDoc = new ActiveXObject("MSXML2.DOMDocument.6.0");
trace.push("MSXML2.DOMDocument.6.0 created");
}
catch (ex) {
trace.push("Creating Microsoft.XMLHTTP");
xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
trace.push("Microsoft.XMLHTTP created");
}
xmlDom.async = "false";
try { xmlDoc.responseType = "msxml-document"; } catch (ex) { }
trace.push("Loading XML content");
xmlDom.loadXML(content);
trace.push("XML content loaded");
}
else {
throw new Error("No XML parser found");
}
return xmlDom;
}
function xslTransformTo(xsl, xml, wrapper) {
if ((window.ActiveXObject) || "ActiveXObject" in window) {
trace.push("Transforming with ActiveXObject");
wrapper.innerHTML = xml.transformNode(xsl);
trace.push("Transformed with ActiveXObject");
}
else if (document.implementation && document.implementation.createDocument) {
trace.push("Transforming with XSLTProcessor");
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
wrapper.appendChild(xsltProcessor.transformToFragment(xml, document));
trace.push("Transformed with XSLTProcessor");
}
else {
throw new Error("No XSL parser found");
}
}
function xmlString(xml) {
return (new XMLSerializer()).serializeToString(xml);
}
function showError(ex) {
var console = document.getElementById("console");
showTrace();
console.appendChild(document.createTextNode("ERROR!!! " + ex.message));
}
function showTrace() {
var console = document.getElementById("console");
for (var i = 0; i < trace.length; i++) {
console.appendChild(document.createTextNode(trace[i]));
console.appendChild(document.createElement("br"));
}
}
var trace = [];
var strXml = "<root>\n"
+ " <fc>\n"
+ " <sc>\n"
+ " <i />\n"
+ " <i />\n"
+ " <i />\n"
+ " <i />\n"
+ " </sc>\n"
+ " </fc>\n"
+ "</root>";
trace.push("XML string defined");
var strXsl = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n"
+ " <xsl:template match=\"/root\">\n"
+ " <ul>\n"
+ " <xsl:for-each select=\"fc/sc/i\">\n"
+ " <li>[<xsl:value-of select=\"position()\" />]</li>\n"
+ " </xsl:for-each>\n"
+ " </ul>\n"
+ " </xsl:template>\n"
+ "</xsl:stylesheet>";
trace.push("XSL string defined");
var strWrapperId = "wrapper";
trace.push("Parsing XML");
var xmlDoc = getXmlDom(strXml);
trace.push("XML parsed");
trace.push("Parsing XSL");
var xslDoc = getXmlDom(strXsl);
trace.push("XML parsed");
var domWrapper = document.getElementById(strWrapperId);
var xmlItemList = xmlDoc.getElementsByTagName("i");
trace.push("All variables loaded");
trace.push("Iterating item positions");
try {
for (var i = 0; i < xmlItemList.length; i++) {
xmlItemList[i].setAttribute("p", i);
}
}
catch (ex) {
showError(ex);
return;
}
trace.push("Itens positions iterared");
trace.push("Transforming XML with XSL to wrapper");
try {
xslTransformTo(xslDoc, xmlDoc, domWrapper);
}
catch (ex) {
showError(ex);
return;
}
showTrace();
}
catch (ex) {
alert(ex.message);
}
P.S.: The only difference with the code I use is the trace and the loadXML based on string content, as in fact I use load method with a accessible uri.
Edit 1 - 23/fev/16
I tried to run the JSFiddle posted by Martin Honnen on IE 11 and it shows ERROR!!! No XSL parser found. I did some refactoring using the instructions on MSDN page he suggested. That article instructs to try, not to test, because some plugins may be instantiated but not detected. And going that way my IE 11 creates and load my XML and XSL objects and content using DOMParser but fails to transform with both transformNode and XSLTProcessor. As done in: http://jsfiddle.net/mfedatto/6nsc5bf1/38
Edit 2 - 25/fev/16
For some reason the solution doesn't work on JSFiddle, I'll do some digging about it. But with Martin Honnen answer I could load my external XML and XSL files crossbrowser, including IE 11. Here is the final code I used:
function loadXmlFile(path) {
var xmlDoc;
if (loadXmlFile.cache === undefined) {
loadXmlFile.cache = { };
}
if (loadXmlFile.cache[path] === undefined) {
try {
xmlDoc = new ActiveXObject("MSXML2.DOMDocument.6.0");
}
catch (e) {
try {
xmlDoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
}
catch (e2) {
xmlDoc = new XMLHttpRequest();
xmlDoc.responseType = "application/xml";
}
}
try {
xmlDoc.open("GET", path, false);
xmlDoc.send();
loadXmlFile.cache[path] = xmlDoc.responseXML;
}
catch (ex) {
xmlDoc.async = false;
xmlDoc.load(path);
loadXmlFile.cache[path] = xmlDoc;
}
}
return loadXmlFile.cache[path];
}
function xslTransformTo(xsl, xml, wrapper) {
if (typeof xml.transformNode != "undefined") {
wrapper.innerHTML = xml.transformNode(xsl);
}
else if (typeof XSLTProcessor != "undefined") {
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
wrapper.appendChild(xsltProcessor.transformToFragment(xml, document));
}
}
See https://msdn.microsoft.com/en-us/library/dn423948(v=vs.85).aspx, in IE 11 you need to use new ActiveXObject('program.id') inside of a try/catch, the check for the window property does not work.
Furthermore, the native IE DOM documents you create with DOMParser in IE do not support transformNode, so if you know you need an XML DOM document in IE to do XSLT transformation then you need to make sure you create an MSXML DOM document with new ActiveXObject and you need to do try to do that first in your code with try/catch, before you try to instantiate DOMParser.
So for the XML parsing from a string I would use
function getXmlDom(content) {
var xmlDom;
try {
xmlDom = new ActiveXObject('Msxml2.DOMDocument.6.0');
xmlDom.loadXML(content);
}
catch (e) {
try {
xmlDom = new ActiveXObject('Msxml2.DOMDocument.3.0');
xmlDom.loadXML(content);
}
catch (e2) {
xmlDom = (new DOMParser()).parseFromString(content, 'application/xml');
}
}
return xmlDom;
}
as done in http://home.arcor.de/martin.honnen/javascript/2016/test2016022301.html.
I built a chrome extension and everything worked well.
Now i need to put it on firefox, and it's a f*** mess.
The problem is with dom parsing.
Her's the code that doesn't work on FF :
var parser = new DOMParser();
SOURCE_DOM = parser.parseFromString(data.url, "text/html");
SOURCE_DOM always return an object empty :
Object : {location : null}
On chrome there's no problem with that, it gives me the document object and i can properly work with it. But Firefox is a pain in the ass compared to chrome when it comes to extension building.
Someone would know how to get the document ?
Use the code below
if (window.DOMParser) {
var parser=new window.DOMParser();
var parsererrorNS = null;
// IE9+ now is here
if(!isIEParser) {
try {
parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
}
catch(err) {
parsererrorNS = null;
}
}
try {
xmlDoc = parser.parseFromString( xmlDocStr, "text/xml" );
if( parsererrorNS!= null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
//throw new Error('Error parsing XML: '+xmlDocStr);
xmlDoc = null;
}
}
catch(err) {
xmlDoc = null;
}
} else {
// IE :(
if(xmlDocStr.indexOf("<?")==0) {
xmlDocStr = xmlDocStr.substr( xmlDocStr.indexOf("?>") + 2 );
}
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xmlDocStr);
}
The below code does not run in Chrome.
function parseXML(xmlstring) {
var dom;
if (window.ActiveXObject && window.GetObject) {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.loadXML(xmlstring);
return dom;
}
if (window.DOMParser) {
var xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", xmlstring, false);
xmlDoc.overrideMimeType('text/xml');
xmlDoc.onreadystatechange = function () {
if (xmlDoc.readyState == 4 && xmlDoc.status == 200) {
dom = xmlDoc.responseXML;
return dom;
}
};
xmlDoc.send("");
//return new DOMParser().parseFromString((xmlstring), 'text/xml');
}
}
I tried all posibility even used $.parseXML but did not work in Chrome
Your valuable input will be highly appreciated.
i got the dom properly but i was doing $(dom).find('') instead of $(dom.find(" ") dont know why this strange behavior in Chrome...Now it works in all browser...[:)]
I am having some JavaScript issues that seem to only occur in Internet Explorer 10 on Windows 8 (IE 7, 8, and 9 all work fine). The basic jist of what I am doing is getting XML and XSL from a web service and then transforming them in JavaScript to render on the page using the Sys.Net.XMLDOM object.
XMLDOM = Sys.Net.XMLDOM;
var xsl = // XSL gotten from somewhere else
var xmlString = // XML gotten from somewhere else as a string...
var xml = new XMLDOM(xmlString);
var content = xml.transformNode(xsl);
When I use the above code in IE 10, I get:
Object doesn't support property or method 'transformNode'
Any ideas on why Internet Explorer 10 is doing this?
EDIT
I have also tried this:
xmldoc = new ActiveXObject("Msxml2.DOMDocument");
xmldoc.async = false;
xmldoc.load(xml);
xsldoc = new ActiveXObject("Msxml2.DOMDocument");
xsldoc.async = false;
xsldoc.load(xsl);
var content = xmldoc.transformNode(xsldoc);
Which works in all previous versions of IE, but in IE 10 I get:
Reference to undeclared namespace prefix: 'atom'.
IE 9 and grater doesn't support it, try this function (found online)
function TransformToHtmlText(xmlDoc, xsltDoc) {
if (typeof (XSLTProcessor) != "undefined") { // FF, Safari, Chrome etc
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsltDoc);
var xmlFragment = xsltProcessor.transformToFragment(xmlDoc, document);
return GetXmlStringFromXmlDoc(xmlFragment);
}
if (typeof (xmlDoc.transformNode) != "undefined") { // IE6, IE7, IE8
return xmlDoc.transformNode(xsltDoc);
}
else {
try { // IE9 and grater
if (window.ActiveXObject) {
var xslt = new ActiveXObject("Msxml2.XSLTemplate");
var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
xslDoc.loadXML(xsltDoc.xml);
xslt.stylesheet = xslDoc;
var xslProc = xslt.createProcessor();
xslProc.input = xmlDoc;
xslProc.transform();
return xslProc.output;
}
}
catch (e) {
alert("The type [XSLTProcessor] and the function [XmlDocument.transformNode] are not supported by this browser, can't transform XML document to HTML string!");
return null;
}
}
}
var content = TransformToHtmlText(xml, xsl);
Found the answer: http://blogs.msdn.com/b/ie/archive/2012/07/19/xmlhttprequest-responsexml-in-ie10-release-preview.aspx
IE 10 requires using an XMLHttpRequest with the responseType set as "msxml-document". Once I switched the code over to that, everything works perfectly in all browsers:
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP"); // For IE 6
}
xhr.open("GET", url, false);
try { xhr.responseType = "msxml-document"; } catch (e) { };
xhr.send();
I had the same problem with IE 9 and none of the answers helped until I stopped trying to load the xslt file using jQuery. I loaded the file with a script as documented in: https://msdn.microsoft.com/en-us/library/ms762796%28v=vs.85%29.aspx.
I was then able to use the transformNode() function. Here is the script that they gave:
<HTML>
<HEAD>
<TITLE>sample</TITLE>
<SCRIPT language = "javascript">
function init()
{
var srcTree =
new ActiveXObject("Msxml2.DOMDocument.6.0");
srcTree.async=false;
// You can substitute other XML file names here.
srcTree.load("hello.xml");
var xsltTree =
new ActiveXObject("Msxml2.DOMDocument.6.0");
xsltTree.async = false;
// You can substitute other XSLT file names here.
xsltTree.load("hello.xsl");
resTree.innerHTML = srcTree.transformNode(xsltTree);
}
</SCRIPT>
</HEAD>
<BODY onload = "init()" >
<div id="resTree"></div>
</BODY>
</HTML>
Firstly credit to Roel van Lisdonk who published the function Sheik Heera shared.
I found this function as it was didn't work in Chrome, because of GetXmlStringFromXmlDoc() so I used the XMLSerializer:
So for example:
if (typeof(GetXmlStringFromXmlDoc)!= "undefined")
{
return GetXmlStringFromXmlDoc(xmlFragment);
}
else
{
// chrome friendly
// get a xml serializer object
var xmls = new XMLSerializer();
// convert dom into string
var sResult = xmls.serializeToString(xmlFragment);
//extract contents of transform iix node if it is present
if (sResult.indexOf("<transformiix:result") > -1)
{
sResult = sResult.substring(sResult.indexOf(">") + 1, sResult.lastIndexOf("<"));
}
return sResult;
}
The revised function is now:
function TransformToHtmlText(xmlDoc, xsltDoc)
{
// 1.
if (typeof (XSLTProcessor) != "undefined")
{
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsltDoc);
var xmlFragment = xsltProcessor.transformToFragment(xmlDoc, document);
if (typeof(GetXmlStringFromXmlDoc)!= "undefined")
{
return GetXmlStringFromXmlDoc(xmlFragment);
}
else
{
// chrome friendly
// get a xml serializer object
var xmls = new XMLSerializer();
// convert dom into string
var sResult = xmls.serializeToString(xmlFragment);
//extract contents of transform iix node if it is present
if (sResult.indexOf("<transformiix:result") > -1)
{
sResult = sResult.substring(sResult.indexOf(">") + 1, sResult.lastIndexOf("<"));
}
return sResult;
}
}
// 2.
if (typeof (xmlDoc.transformNode) != "undefined")
{
return xmlDoc.transformNode(xsltDoc);
}
else {
var activeXOb = null;
try { activeXOb = new ActiveXObject("Msxml2.XSLTemplate"); } catch (ex) {}
try {
// 3
if (activeXOb)
{
var xslt = activeXOb;
var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
xslDoc.loadXML(xsltDoc.xml);
xslt.stylesheet = xslDoc;
var xslProc = xslt.createProcessor();
xslProc.input = xmlDoc;
xslProc.transform();
return xslProc.output;
}
}
catch (e)
{
// 4
alert("The type [XSLTProcessor] and the function [XmlDocument.transformNode] are not supported by this browser, can't transform XML document to HTML string!");
return null;
}
}
}
I'm designing a client side script that will read an XML file and display it, like this:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
function loadXML(xmlFile) {
xmlDoc.async = "false";
xmlDoc.onreadystatechange = verify;
xmlDoc.load(xmlFile);
}
function verify() {
if(xmlDoc.readyState != 4) {
return false;
}
}
function traverse(tree) {
if(tree.hasChildNodes()) {
document.write('<ul><li>');
document.write('<b>' + tree.tagName + ': </b>');
var nodes = tree.childNodes.length;
for(var i = 0; i < tree.childNodes.length; i++) {
traverse(tree.childNodes(i));
}
document.write('</il></ul>');
} else {
document.write(tree.text);
}
}
function initTraverse(file) {
loadXML(file);
var doc = xmlDoc.documentElement;
traverse(doc);
}
When I fired Safari I saw that nothing was displayed, then I've opened the Error Console and what I got was this:
ReferenceError: Can't find variable: ActiveXObject
What should I do to make this work?
PS: I would prefer if this page could be capable of running at Mobile Safari
ActiveXObject do not work outside of internet explorer.
There are a few alternative xml parser's and handlers like E4X. Although E4X is currently only done in firefox (https://developer.mozilla.org/En/E4X/Processing_XML_with_E4X).
If using jQuery is an option then you can look into marcgrabanski.com/articles/jquery-makes-parsing-xml-easy
Some interesting stuff going on there. Most interesting is the async = false line. You probably want to re-consider that bit. In order to change to an asynchronous request, you would have to re-write some other code and remove the document.write calls.
Regardless, here is a (untested but hopefully) drop in replacement for what you have using XMLHttpRequest instead of an xml document.
var xmlDoc = null;
function loadXML(xmlFile) {
var request = new XMLHttpRequest();
request.open('GET', xmlFile, false); // false is synchronous
request.send();
xmlDoc = request.responseXML;
}
You may have to do some debugging...
You should have something cross-browser compatible with either DOMParser or DOMDocument. Of course, I'm not sure if you're wanting to parse a XML URL or a XML string. For a XML URL, I recommend:
if (window.XMLHttpRequest) return new window.XMLHttpRequest();
else if (window.ActiveXObject) {
// the many versions of IE's XML fetchers
var AXOs = [
'MSXML2.XMLHTTP.6.0',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP',
'MSXML.XMLHTTP'
];
for (var i = 0; i < AXOs.length; i++) {
try { return new ActiveXObject(AXOs[i]); }
catch() { continue; }
}
return null;
}
For a XML string, this code block would work better:
if (window.DOMParser) return (new DOMParser()).parseFromString(str, 'text/xml');
else if (window.ActiveXObject) {
var doc;
// the many versions of IE's DOM parsers
var AXOs = [
'MSXML2.DOMDocument.6.0',
'MSXML2.DOMDocument.5.0',
'MSXML2.DOMDocument.4.0',
'MSXML2.DOMDocument.3.0',
'MSXML2.DOMDocument',
'Microsoft.XMLDOM',
'MSXML.DOMDocument'
];
for (var i = 0; i < AXOs.length; i++) {
try { doc = new ActiveXObject(AXOs[i]); break; }
catch() { continue; }
}
if (!doc) return createElement('div', null);
if (doc.async) doc.async = false;
doc.loadXML(str);
return doc;
}
return createElement('div', null);
The DOMDocument objects do support a load() method for loading XML from a URL, but it's a different syntax than the XMLHttpRequest and XMLHTTP methods.
The DOMDocument appears (at least from the MSDN docs) to also contain the XMLHTTP methods, so you could interlace DOMDocument in the AXOs array, but I'm not certain about that. Plus, I can't imagine DOMDocument being in place without XMLHTTP.