jQuery won't parse xml with nodes called option

后端 未结 3 1999
既然无缘
既然无缘 2020-11-27 22:22

I\'m using jQuery to parse some XML, like so:

function enumOptions(xml) {
   $(xml).find(\"animal\").each(function(){  
       alert($(this).text());
   });
         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 23:14

    Update

    jQuery has this method built-in now. You can use

    $.parseXML("..")
    

    to construct the XML DOM from a string.


    jQuery relies on the HTML DOM using innerHTML to parse the document which can have unreliable results when tag names collide with those in HTML.

    Instead, you can use a proper XML parser to first parse the document, and then use jQuery for querying. The method below will parse a valid XML document in a cross-browser fashion:

    // http://www.w3schools.com/dom/dom_parser.asp
    function parseXML(text) {
        var doc;
    
        if(window.DOMParser) {
            var parser = new DOMParser();
            doc = parser.parseFromString(text, "text/xml");
        }
        else if(window.ActiveXObject) {
            doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = "false";
            doc.loadXML(text);
        }
        else {
            throw new Error("Cannot parse XML");
        }
    
        return doc;
    }
    

    Once the XML DOM is constructed, jQuery can be used as normal - http://jsfiddle.net/Rz7Uv/

    var text = "";
    var xml = parseXML(text);
    $(xml).find("option"); // selects , 
    

提交回复
热议问题