0

I have a XML as follows:

<xml>
    <grandparent>
        <parent>
            <father>A</father>
            <mother>B</mother>
            <children>
                <name>C</name>
                <name>D</name>
            </children>
        </parent>
        <parent>
            <father>E</father>
            <mother>F</mother>
            <children>
                <name>G</name>
                <name>H</name>
                <name>I</name>
            </children>
        </parent>
        <parent>
            <father>J</father>
            <mother>K</mother>
            <children>
                <name>L</name>
            </children>
        </parent>
    </grandparent>
</xml>

How do I loop in this XML and retrieves and parent names and the children names.

I must get the following result: Row 1: A, B, C, D

Row 2: E, F, G, H, I

Row 3: J, K, L

Please help. Thanks.

Yuvraj
  • 1
  • 1
  • 3
  • Possible duplicate of [Cross-Browser Javascript XML Parsing](http://stackoverflow.com/questions/7949752/cross-browser-javascript-xml-parsing) – Hamlet Hakobyan Aug 06 '16 at 10:11

1 Answers1

0

The solutions is as follows:

//get parent list
var parent_list = rsp.response.getElementsByTagName("parent");

for (i = 0; i  < parent_list.length; i++) {
    //output father and mother
    alert(parent_list[i].getElementsByTagName("father")[0].childNodes[0].nodeValue);
    alert(parent_list[i].getElementsByTagName("mother")[0].childNodes[0].nodeValue);

    //get children list
    var children_list = parent_list[i].getElementsByTagName("children");

    for (j = 0; j < children_list.length; j++) {
        //output children name
        alert(children_list[j].getElementsByTagName("name")[0].childNodes[0].nodeValue);
    }

}
Yuvraj
  • 1
  • 1
  • 3
  • Unless you need to target some obsolete IE versions you can safely shorten the use of `.childNodes[0].nodeValue` to `.textContent`. – Martin Honnen Aug 06 '16 at 15:02