如何使用JavaScript循环遍历XML节点和子节点?

时间:2014-11-20 17:15:15

标签: javascript html xml

我目前遇到循环遍历XML节点并显示其子元素的问题。

这是XML的样子:

<?xml version="1.0" encoding="UTF-8"?>

<monday>
    <employee>
        <name>Employee 1</name>
        <startTime>12 PM</startTime>
        <endTime>3:30 PM</endTime>
        <skills>Web Development, Graphic Design</skills>
        <programs>Sublime Text</programs>
    </employee>
    <employee>
        <name>Employee 2</name>
        <startTime>10 AM</startTime>
        <endTime>2 PM</endTime>
        <skills>Graphic Design</skills>
        <programs>Illustrator, Photoshop</programs>
    </employee>
    <employee>
        <name>Employee 3</name>
        <startTime>12:30 PM</startTime>
        <endTime>3:30 PM</endTime>
        <skills>Social Media</skills>
        <programs>Facebook, Twitter, Instagram</programs>
    </employee>
</monday>

我瞄准的算法是:

  1. 在根元素(monday)中,转到firstChild元素(employee
  2. 遍历employee的每个子元素(namestartTimeendTimeskillsprograms
  3. 对于每个子元素,将文本写入HTML文档
  4. 对每个employee元素重复步骤2和3,直到迭代到达lastChild元素
  5. 到目前为止,我只能迭代并编写每个员工的只有一个元素。这是name元素的代码:

    // loads XML file
    if (window.XMLHttpRequest) {
      xhttp = new XMLHttpRequest();
    } else { // for IE 5/6
      xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET","assets/" + today + ".xml",false);
    xhttp.send();
    xmlDoc = xhttp.responseXML;
    document.write("XML document loaded into an XML DOM Object." + "<br><br>"); // confirms XML file is loaded
    
    
    // iterates through employees and displays their information
    x = xmlDoc.getElementsByTagName("name");
    for (i = 0; i < x.length; i++) {                  // line 1
        document.write(x[i].childNodes[0].nodeValue);
        document.write("<br>");
    }
    

    输出:

    Employee 1
    Employee 2
    Employee 3
    

    我已尝试在// line 1内嵌套另一个for循环,但这导致输出中没有显示任何内容。

    我正确输出的目标是:

    Employee 1
    Start Time: 12 PM
    End Time: 3:30 PM
    Skills: Web Development, Graphic Design
    Programs: Sublime Text, Dreamweaver
    
    Employee 2
    Start Time: 11 AM
    End Time: 32 PM
    Skills: Graphic Design
    Programs: Illustrator, Photoshop
    
    Employee 3
    Start Time: 12:30 PM
    End Time: 3:30 PM
    Skills: Social Media
    Programs: Facebook, Twitter, Instagram
    

    如果您有任何疑问,我会尽我所能回答!

    提前谢谢你!

1 个答案:

答案 0 :(得分:2)

employee而不是name上附加循环的根对嵌套循环更好(这是此解决方案将使用的):

var employees = xmlDoc.getElementsByTagName("employee"); //outputs array of employees

for (employeeIndex = 0; employeeIndex  < employees.length; employeeIndex++) {
    var empDetails = employees[employeeIndex].children; //outputs array of details

    for (detailIndex = 0; detailIndex < empDetails.length; detailIndex++) {
        document.write(employees[employeeIndex].childNodes[detailIndex].nodeValue);
    }

    document.write("<br>");
}

我还注意到每个employee节点集的容器是一周中的某一天。如果您想要遍历一周中的每一天,可以在employeeIndex之外创建另一个嵌套来循环遍历dayIndex种类。