使用xpath.js NPM模块解析XML

时间:2014-03-19 21:09:39

标签: javascript xml node.js xpath

我的XML看起来像这样:

<jobs>
  <job>
    <title>Engineer - System Planning</title>
    <url>http://my.jobs/0629cdc680d04cf3bcd711a1c0b69836321</url>
    <company>Iberdrola USA</company>
    <location>Augusta, ME</location>
    <dateacquired>2013-3-22 6:24 PM</dateacquired>
    <jvid>0629cdc680d04cf3bcd711a1c0b69836321</jvid>
  </job>
  <job>
    <title>Engineer - Hydro</title>
    <url>http://my.jobs/61cccbfba50c4f93a5169aafc13c82b2321</url>
    <company>Iberdrola USA</company>
    <location>Rochester, NY</location>
    <dateacquired>2013-7-5 8:33 PM</dateacquired>
    <jvid>61cccbfba50c4f93a5169aafc13c82b2321</jvid>
  </job>
</jobs>

我想使用XPath.js NPM模块(https://www.npmjs.org/package/xpath.js)。但我不知道如何使用该模块遍历XML文档中的每个job

1 个答案:

答案 0 :(得分:3)

xpath.js documentation的第一个示例中,使用类似//job的XPath表达式,您将得到一个节点集:

var nodes = select(doc, "//job");

你可以使用常规JavaScript循环,因为它是一个数组。然后,您可以将每个节点作为另一个XPath表达式中的参数传递,并获取其他节点内的数据:

for (i = 0; i < nodes.length; i++) {
    var title   = select(nodes[i], "title/text()")[0].data;
    var url     = select(nodes[i], "url/text()")[0].data;
    var company = select(nodes[i], "company/text()")[0].data;
    ...
}