开发者

Using Jquery to return elements of XML string doesn't work in Internet Explorer 9

开发者 https://www.devze.com 2023-01-25 12:25 出处:网络
Using jQuery I use the selector and the each function to itterate through named elements of an XML string.

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.


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.


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");
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号