How do you run an xPath query in IE11?

2020-02-09 04:20发布

问题:

At one point in our system we use javascript to read in a chunk of XML and then query that XML document using xPath.

Prior to IE 11, IE supported using xmldoc.selectSingleNode(“//xpath/string”) and the non IE browsers supported using a xmldoc.evaluate(“//xpath/string”). These both returned a similar object that we could then carry on interpreting to extract the data required.

In IE11 neither of these methods seem to be available.

It seems that IE11 has some support for XML documents in that when I read in the xml using the DOMParser object using the parseFromString method, it returns an object that the IE11 debugger calls an XMLDocument.

回答1:

Thanks to @Martin Honnen for pointing out that some ActivXObjects are still supported in IE11!

var doc;
try { 
    doc = new ActiveXObject('Microsoft.XMLDOM'); 
    doc.loadXML(stringVarWithXml); 
    var node = doc.selectSingleNode('//foo'); 
} catch (e) { // deal with case that ActiveXObject is not supported }

I've used "Microsoft.XMLDOM" as it is sugested here that it is a more generic call to what ever xml parser is present on the system, where as it sounds like "Msxml2.DOMDocument.6.0" will fail if that exact version is not present. (We do have to support all IE vers back to 6.0 at my place!)

This just works as it always has done. The only problem I had was that the old switch I used to detect IE vs other browsers was if (typeof ActiveXObject !== "undefined") failed as I guess they are trying to discourage it's use!

Thanks all for your help.



回答2:

To expand on pixelmatt's answer, some results of my tests (Win 7 64bit with IE11) I did in order to get DOMParser to work as it did in IE9 and IE10 (in IE11 it now returns an XMLDocument object which appears to not support xpath queries?).

Turns out I could make it behave like in IE10 with the following meta tag:

<meta http-equiv="X-UA-Compatible" content="IE=10" />

Results without and with above meta:

And here are the XMLDocument's memebers (for reference):