Search code examples
xmlinternet-explorer-10msxml

How to manually create msxml document in IE10


I looked at this question and I understand that when dealing with an ajax response, it is possible to instruct IE10 to create an msxml document instead of a native XML document. This is in order to use legacy xpath methods such as selectSingleNode.

However, in my case I am not reading the XML from an ajax response, I am reading it from raw text in javascript. E.g., this is a code snippet that works in most browsers:

var xmlString = "<a><b>some data</b></a>";
vor xmlDocument = new DOMParser().parseFromString(xmlString, "text/xml");

In IE10, DOMParser returns a native XML document. What can I do differently here in order to get an MSXML document, similarly to the way it's done with ajax?


Solution

  • You'll have to explicitly create an instance of the parser using ActiveXObject:

    var xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
    xmlDocument.async = 'false';
    xmlDocument.loadXML(xmlString);
    
    alert(xmlDocument.selectSingleNode('//a/b').text);
    

    See also

    ps. if you need to test for ActiveXObject being available, then check out window.ActiveXObject difference in IE11, testing for window.ActiveXObject !== undefined seems to work fine.