Using Jquery to return elements of XML string does

2019-08-23 06:40发布

问题:

Using jQuery I use the selector and the each function to itterate through named elements of an XML string.

e.g.

$("<xml><elem></elem><elem></elem></xml>").each(function() 
{ 
   alert("processing elem tag");
});

This works fine in FF/Chrome/IE<8 but in 9 fails. Presumably something in the IE doc no longer allows this.

回答1:

It's not intended to take a string of XML directly, only from an AJAX response, e.g. .responseXML, in any case don't worry about it at this point.

IE9 has bugs, it's not RTM quality, they are mostly their bugs...I personally wouldn't waste time changing (or even debugging) your code until their's is more complete/stable. (Opinion) don't worry about the client with IE9 either...they signed on for a buggy experience when they installed pre-release software.



回答2:

jQuery doesn't parse XML. What $("<xml><elem></elem><elem></elem></xml>") does is to create an element and set its innerHTML property to "<xml><elem></elem><elem></elem></xml>", which will have variable and unpredictable results.

You need to parse the XML using the browser's built-in XML parser. Here's a function that does this. I haven't tested it in IE 9 but I'd be surprised if it didn't work: they've implemented DOMParser, so unlike IE < 9 it will fall into the first branch and should work unless they've made a mess of it.

var parseXml;

if (window.DOMParser) {
    parseXml = function(xmlStr) {
       return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    parseXml = function() { return null; }
}

var xmlStr = "<xml><elem></elem><elem></elem></xml>";
var xmlDoc = parseXml(xmlStr);

$(xmlDoc).each(function() { 
   alert("processing elem tag");
});