2017-08-09 49 views
1

我是node.js的新手,需要解析XML。在js中,我只使用DOMParser并使用getElementsByTagName来获得我想要的值。我刚刚切换到节点,并正在使用xml2js(愿意考虑替代方案)。我一直无法弄清楚如何通过回应来解析我所需要的。下面用xml2js解析

代码:

function parseBody(body){ 
    var parseString = require('xml2js').parseString; 
    var xml = body 
    parseString(xml, function (err, result) { 
    console.dir(result); 
}); 

,这里是我传递给函数的XML:

<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:int=\"realURLHere"> 
    <soapenv:Header/> 
    <soapenv:Body> 
     <int:readResponse> 
     <response> 
      <request>?</request> 
      <cust> 
       <fName>?</fName> 
      </cust> 
     </response> 
     </int:readResponse> 
    </soapenv:Body> 
</soapenv:Envelope> 

这里是我的函数的输出:

{ 'soapenv:Envelope': 
    { '$': 
     { 'xmlns:soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', 
     'xmlns:int': 'realURLHere' }, 
    'soapenv:Body': [ [Object] ] 
    } 
} 

我试图在<cust>之内访问<fName>的值,但没有运气。任何帮助,将不胜感激。谢谢!

回答

0

var custFName = result['soapenv:Envelope']['soapenv:Body'][0]['int:realURLHe‌​re'][0]['response'][‌​0]['cust'][0]['fName‌​'];

这解决了我的问题。我的努力与这个响应中的每一件事都有关系。如果有更简单的方法来做到这一点或更具活力,请让我知道。但现在,这工作。

+0

打印出

{ "fname": "hello world" } 

您可以访问尝试下面的答案 –

0

试试这个

const transform = require('camaro') 

const xml = ` 
<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:int=\"realURLHere"> 
    <soapenv:Header/> 
    <soapenv:Body> 
     <int:readResponse> 
     <response> 
      <request>?</request> 
      <cust> 
       <fName>hello world</fName> 
      </cust> 
     </response> 
     </int:readResponse> 
    </soapenv:Body> 
</soapenv:Envelope> 
` 

const template = { 
    fname: '//cust/fName' 
} 

const result = transform(xml, template) 
console.log(JSON.stringify(result, null, 2)) 

通过使用result.fname