2

Is it possible to find an xml element by searching with the value of a child element?

So for XML such as:

<route>
    <name>Lakeway</name>
    <abrv>LAKE</abrv>
    <eta>
        <time>00:30</time>
        <dest>MAIN</dest>
    </eta>
</route>

If I only have the value of the abrv, how would I parse the xml so as to get at the eta tags' child elements?

Is this doable with jQuery without looping through each element and comparing the values to the defined variable? Or is there a better way to do this?

EDIT:

I am trying to parse an XML feed from another domain. I'm not sure if I can do that with the xmlParse function, or if I'll need to use jQuery's Ajax functions?

simon
  • 25
  • 1
  • 1
  • 4

2 Answers2

2

You could use the contains filter to filter nodes based on this value.

Something like,

$(xml).find('abrv:contains(LAKE) + eta > *')

will return a jQuery object with two elements for the sample document.

<time>00:30</time>
<dest>MAIN</dest>

Here's an example.

Anurag
  • 140,337
  • 36
  • 221
  • 257
1

Maybe something like this:

var xmlString = "<route><name>Lakeway</name><abrv>LAKE</abrv><eta><time>00:30</time><dest>MAIN</dest></eta></route>",
xmlDoc = $.parseXML( xmlString ),
$xml = $( xmlDoc ),
$abrv = $xml.find( "abrv" ).text() == "LAKE" ? $xml.find( "abrv" ) : false;

var time = $abrv.next().children("time").text();
var dest = $abrv.next().children("dest").text();

alert(time + " " + dest);

http://jsfiddle.net/jensbits/UH2m5/

Hopefully, that could get you started.

jk.
  • 14,365
  • 4
  • 43
  • 58
  • How could I use this with an external XML file? That's what I was looking for actually. – simon Aug 03 '11 at 01:55
  • You will need to bring the xml in using another method. See http://stackoverflow.com/questions/1292486/why-cant-i-load-an-external-resource-from-jquery-load-method – jk. Aug 03 '11 at 12:20
  • OK, so I used a simple proxy to get the XML, but I have another question. Is there a difference between using the parseXML function and using the $.get ajax function? So if instead of declaring an xml string, if I use $.get to get xml, should I be able to use the same selectors as you outline above? – simon Aug 04 '11 at 22:36
  • Yes, you should be able to on the return xml. – jk. Aug 04 '11 at 23:21