在Javascript中解析xml遍历子节点 [英] Parsing xml in Javascript iterate through child nodes

查看:47
本文介绍了在Javascript中解析xml遍历子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 javascript 中解析以下 xml.

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>

我需要的是遍历所有员工,直到满足给定条件(例如,获取 SysId=214 的员工节点的 FileId).我能够获得 Floor 节点,但不确定如何遍历子节点并匹配条件?childNodes[0].nodeValue 似乎不起作用

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
}

推荐答案

试试这个:

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

测试小提琴:https://jsfiddle.net/1r2ydxhu/

这篇关于在Javascript中解析xml遍历子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆