2

Here, I want to loop through the <detail> elements. Although I can specify the <detail> tag name in my code, I can't use the tag names of the children. I want to know the tag names of those elements and their values.

How can I loop through them and do this?

<?xml version="1.0" encoding="utf-8" ?>
<body>
  <detail>
    <FirstName>t1 </FirstName>
    <LastName>t2</LastName>
    <Company>t3</Company>
    <Country>t4</Country>
    <Proviance>MP</Proviance>
    <city>indore</city>
  </detail>

  <detail>
    <FirstName>t5 </FirstName>
    <LastName>t6</LastName>
    <Company>t7</Company>
    <Country>t8</Country>
    <Proviance>t9</Proviance>
  </detail>

  <detail>
    <FirstName>t10 </FirstName>
    <LastName>t11</LastName>
    <Company>t12</Company>
    <Country>t13</Country>
    <Proviance>t14</Proviance>
  </detail>

</body>
Andy E
  • 338,112
  • 86
  • 474
  • 445
NoviceToDotNet
  • 10,387
  • 36
  • 112
  • 166

3 Answers3

11

How about;

var details = xml.getElementsByTagName("detail");

for (var i = 0; i < details.length; i++) {
    if (details[i].childNodes) {
        for (var j = 0; j < details[i].childNodes.length; j++) {
            var detail = details[i].childNodes[j];
            if (detail.nodeType === 1)
                alert( "details node " + (i + 1) + ": " + detail.nodeName + "=" + detail.firstChild.nodeValue );
        }
    }
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288
1

Here is a tutorial for parsing XML with JavaScript. Maybe it helps.

Hint: Search for tagName on the page

yunzen
  • 32,854
  • 11
  • 73
  • 106
1

Another great article of reading xml in javascript.

this tutorial only cover the IE support script, a little reading may help you make it compatible with other browsers.

you can search this text on google "XML Parser in Firefox Browsers" will give more results with example code.

Muhammad Saifuddin
  • 1,284
  • 11
  • 29