用xml2jsparsing

我是node.js新手,需要parsingXML 。 在JS中,我只是使用DOMParser并使用getElementsByTagName来获取我想要的值。 我刚刚切换到节点,并正在使用xml2js (愿意考虑替代品)。 我一直无法弄清楚如何parsing通过响应得到我所期待的。

代码如下:

 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> 

这是我的function的输出:

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

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

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

这解决了我的问题。 我的努力与这个响应有一个arrays中的一切。 如果有一个更简单的方法来做到这一点或更多的dynamic,请让我知道。 但现在,这工作。

尝试这个

 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)) 

哪打印出来

 { "fname": "hello world" } 

你可以通过使用result.fname来访问