tags:

views:

44

answers:

2

I have some xml like

<entry>
    <a>a</a>
    ...
    <subelement>
        <b>b</b>
         .... 
    </subelement>
</entry>

if I do $(entry).find('whatIAmLookingFor')

it works for some elements, but not for other elements, when those elements are nested in the subelement.

I can get it to work by doing

$(entry).find('subelement').children()[indexofwhatiamlookingfor].textContent;

in Firebug, but obviously this is a hack...

Why would 'find' find some elements in a subelement but not others? I had another developer look at this to make sure I had the element names correct (no fat finger issues).

A: 

I haven't tried it personally, but it might be worth looking at the jParse XML parsing plugin.

Ken Redler
+2  A: 

jQuery doesn't parse XML. You can use the following simple function to do it and use jQuery to do its usual querying stuff on the document:

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 xml = parseXml("<foo>Stuff</foo>");
if (xml) {
    var $xmlDoc = $(xml);
    window.alert($xmlDoc.find("foo")[0].nodeName);
}
Tim Down