0

I have an xml data where there are multiple nodes with same name, however I just want to extract the value of one tag.

Sample XML:

<update>
    <family>
        <name>Rajesh</name>
        <age>35</age>
        <kids>
            <kid>
                <name>Manu</name>
                <age>2</age>
            </kid>
        </kids>
    </family>
</update>

I'm trying to extract the value of name tag from the family node but "name" value under kids sub-node is also getting selected.

$name = $(data).find("name");

This gives me "RajeshManu"

How do I select just value of "name" under family but not under "kids".

1 Answer 1

1

Remember, you need to parse the XML before you can use jQuery.

$xml = $.parseXML(data);

Then you can use jQuery, to match elements inside the $xml object.


You could use children() instead of find().

This is because find() will get all children and ancestors of the currently selected element. You want just the immediate child.

Using children() in the same way will give you just the immediate children which match the chosen selector.

For example:

$name = $xml.find('family').children('name');

Or you could match it using the > selector:

$name = $xml.find('family > name');
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.