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

10,061

Solution 1

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

Solution 2

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

Hint: Search for tagName on the page

Solution 3

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.

Share:
10,061
NoviceToDotNet
Author by

NoviceToDotNet

Hi friend, I am new to asp dot net realm. I am here for knowledge sharing and learning technical from seniors. Favourite Book:-&gt; THE AUTOBIOGROPHY OF A YOGI FAVOURITE QUOTHATION:-&gt; There is nothing matter in this world except your spiritual progress every day. from the Autobiography of a Yogi. Attachment is blinding; it lends an imaginary halo of attractiveness to the object of desire." Swami Sri Yukteswar, from the Autobiography of a Yogi.

Updated on June 19, 2022

Comments

  • NoviceToDotNet
    NoviceToDotNet almost 2 years

    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>