【问题标题】:Parsing xml in Javascript iterate through child nodes在Javascript中解析xml遍历子节点
【发布时间】:2015-06-10 08:29:27
【问题描述】:

我需要用javascript解析下面的xml。

<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 似乎不起作用

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
}

【问题讨论】:

    标签: javascript xml xml-parsing


    【解决方案1】:

    试试这样的:

    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/

    【讨论】:

      【解决方案2】:

      Employee标签上没有nodeValue。那么你期望显示什么?

      尝试更合适的:

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

      为什么不选择“员工”?它只是您要检查的一楼元素吗?

      如果被解析为 html.. 所以也存在多个子节点类型

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多