簡體   English   中英

在Node JS中使用xpath.js解析XML

[英]Parsing XML using the xpath.js in Node JS

我的XML如下所示:

<ns2:OrderList>
  <order order_id="123" item_name="123"/>
  <order order_id="234" item_name="1233"/>
  <order order_id="2357" item_name="1234"/>
  ......
</ns2:OrderList>

我想使用npjms的XPath.js
如何獲得帶有“ order_id”值的數組?

var select = require('xpath.js')
    , dom = require('xmldom').DOMParser

var xml = `<ns2:OrderList>
            <order order_id="123" item_name="123"/>
            <order order_id="234" item_name="1233"/>
            <order order_id="2357" item_name="1234"/>
           </ns2:OrderList>`;


var doc = new dom().parseFromString(xml);    
var nodes = select(doc, "//order/@order_id");
var orderIds = [];
nodes.forEach(function(node) {
    orderIds.push(node.nodeValue);
});

console.log(orderIds);

如果您想使用xpath.js(盡管您也需要xmldom進行解析),類似這樣的方法應該可以解決問題。

const Dom = require('xmldom').DOMParser;
const select = require('xpath.js');
const xml = '<ns2:OrderList> <order order_id="123" item_name="123"/> <order order_id="234" item_name="1233"/> <order order_id="2357" item_name="1234"/> </ns2:OrderList>¬';
const doc = new Dom().parseFromString(xml);
const nodes = select(doc, '//order');

const orderIds = nodes.map((node) => node.getAttribute('order_id'));
console.log(orderIds);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM