Parsing xml in Javascript iterate through child nodes

8.6k views Asked by At

I need to parse the below xml in javascript.

<Department id='1' name='Admins'>
    <Floor Id='5' Name='WingA'>
        <Employee Id='35' Name='John Smith' SysId='120' FileId='135' />
        <Employee Id='124' Name='John Doe'  SysId='214' FileId='125' />
        <Employee Id='79' Name='Lorem Ipsum' SysId='185' FileId='194' />
    </Floor>
</Department>

What I need is to loop through all the employees until I met a given condition (for example, get FileId of the employee node where SysId=214). I am able to get the Floor node but not sure how to iterate through the children and match the condition? The childNodes[0].nodeValue doesnt seem to work

parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlstr, "text/xml");

 floor = xmlDoc.getElementsByTagName("Floor");
      for (i = 0; i < floor.length; i++) {
 floor[i].childNodes[0].nodeValue
}
2

There are 2 answers

0
fatrex On BEST ANSWER

Try something like this:

for (var i = 0; i < floor.length; i++) {
  for (var j = 0; j < floor[i].childNodes.length; j++) {
    var el = floor[i].childNodes[j];
    console.log(el.attributes[2].nodeValue);
  }
} 

Test Fiddle: https://jsfiddle.net/1r2ydxhu/

0
Henrik On

There is no nodeValue on the Employee tags.. So what did you expect to be shown?

try the more appropriate:

.hasAttribute("SysId")
.getAttribute("SysId")

and why not select by "Employee" ? is it only the first floor element you want to inspect?

also consdier that multiple childnode types exist if parsed as html.. so

 for (i = 0; i < floor.childNodes.length; i++) {
     elm = floor.childNodes[i]
     if( elm.nodeType == 1 && elm.hasAttribute("SysId"))
       console.info(elm.getAttribute("SysId"))
 }