ni8mr ni8mr - 1 month ago 9
Javascript Question

Targeting an element and other elements under it with the value of that element in a xml

I have an xml document like this -

<?xml version="1.0" encoding="UTF-8" ?>
<Awmds>
<title>It is a xml</title>
<segment>
<reference>HASL11</reference>
<code>MSB</code>
</segment>
<segment>
<reference>HASL12</reference>
<code>MSB</code>
</segment>
</Awmds>


I can parse and extract the value of the title element, using jquery, like this -

var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$title = $xml.find("title");


Here, xml data is passed by the variable xml.
What i want to do is to target the corresponding segment or code element, with the value HASL11, which is a value of the element reference. How can i achieve this ?

Here is a live jsFiddle demonstrating my code.

Answer

It's a bit unclear what you want specifically but something like the following should help

var $seg = $xml.find('segment').has('reference:contains(HASL11)');
var code = $seg.find('code').text() 

DEMO