简体   繁体   中英

How can I read child node names and their values in XML without specifying the tag name?

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>

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 );
        }
    }
}

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

Hint: Search for tagName on the page

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM