Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery won't parse xml with nodes called option

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

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

enumOptions("<root><animal>cow</animal><animal>squirrel</animal></root>");

This works great. However if I try and look for nodes called "option" then it doesn't work:

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

enumOptions("<root><option>cow</option><option>squirrel</option></root>");

There's no error, just nothing gets alerted, as if the find isn't finding anything. It only does it for nodes called option everything else I tested works ok!

I'm using the current version of jQuery - 1.4.2.

Anyone any idea?

TIA.

bg

like image 533
push 22 Avatar asked May 25 '10 22:05

push 22


2 Answers

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 = "<root><option>cow</option><option>squirrel</option></root>";
var xml = parseXML(text);
$(xml).find("option"); // selects <option>cow</option>, <option>squirrel</option>
like image 122
Anurag Avatar answered Sep 29 '22 21:09

Anurag


This is probably some special handling for the HTML <option> element, but I can't find that in the source.

like image 21
SLaks Avatar answered Sep 29 '22 21:09

SLaks