3

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 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.