在javascript中获取XML节点子节点

时间:2013-04-11 09:00:26

标签: javascript html xml

我正在寻找解析像这样的XML文件

<class>
    <subject>
        <knowledgeLevel> 1 </knowledgeLevel>
        <subjectName> Try1 </subjectName>
        <theory>
            <tutorial> Quickly Explain Try1 </tutorial>
            <full> Largely Explain Try1 </full>
        </theory>
        <example>
            <id> 1 </id>
            <code> some code </code>
            <level> easy </level>
        </example>
        <example>
            <id> 2 </id>
            <code> some code </code>
            <level> hard </level>
        </example>
    </subject>
</class>

考虑到文件中最后会出现多个主题,如何让理论和示例的subChilds用Javascript编写HTML表?

1 个答案:

答案 0 :(得分:0)

这个简单的脚本应该适用于您的目的;它将XML包装在一个临时的<div>元素中,以便您可以遍历它。

var div = document.createElement('div');

div.innerHTML = xml;

function getChildElements(node, fn)
{
  [].forEach.call(node.childNodes, function(node) {
    if (node.nodeType == 1) {
      fn(node);
    }
  });
}

getChildElements(div.firstChild, function(subject) {
  getChildElements(subject, function(info) {
      console.log(info.tagName);
      console.log(info.textContent);
  });
});

Demo