我有以下xml。我想循环遍历每个学生的课程。如何使用nodejs的xpath js模块完成?
<students>
<student>
<name>George</name>
<courses>
<course>
<coursename>Philosophy</coursename>
</course>
<course>
<coursename>Literature</coursename>
</course>
</courses>
</student>
<student>
<name>John</name>
<courses>
<course>
<coursename>History</coursename>
</course>
<course>
<coursename>Maths</coursename>
</course>
</courses>
</student>
</students>
答案 0 :(得分:1)
试试这个:
var xpath = require('xpath'),
dom = require('xmldom').DOMParser
xml= ".. xml string .."
var doc = new dom().parseFromString(xml)
var nodes = xpath.select("//student", doc)
nodes.forEach(function(node){
var courses = node.getElementsByTagName('coursename')
for(var i=0;i< courses.length;i++){
console.log(node.firstChild.firstChild.nodeValue,courses[i].firstChild.nodeValue)
}
})