【问题标题】:Parsing XML using the xpath.js in Node JS在 Node JS 中使用 xpath.js 解析 XML
【发布时间】:2017-03-29 19:05:35
【问题描述】:

我的 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>

我想使用XPath.js from npjms
如何获取具有“order_id”值的数组???

【问题讨论】:

标签: javascript node.js xml xpath


【解决方案1】:

如果您想使用 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);

【讨论】:

    【解决方案2】:
    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多