我是 node.js
的新手并且需要解析 XML
.在 js 中,我只使用 DOMParser
并使用 getElementsByTagName
获得我想要的值(value)。我刚刚切换到 Node 并正在使用 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] ]
}
}
我正在尝试访问 <fName>
的值在 <cust>
内但没有运气。任何帮助,将不胜感激。谢谢!
最佳答案
如果您将 xplicitArray 选项设置为 false,当它解析时,它不会在您没有预料到的地方创建那些数组。像这样:
function parseBody(body) {
var parseString = require('xml2js').parseString;
const options = {
explicitArray: false
};
var xml = body
parseString(xml, options, function (err, result) {
console.log("cust fname: " + result['soapenv:Envelope']['soapenv:Body']['int:readResponse']['response']['cust']['fName']);
})
}
var input = '<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>';
parseBody(input);
此外,如果您删除前缀,它会变得更干净:
function parseBody(body) {
var parseString = require('xml2js').parseString;
var stripNS = require('xml2js').processors.stripPrefix;
const options = {
tagNameProcessors: [stripNS],
explicitArray: false
};
var xml = body
parseString(xml, options, function (err, result) {
console.log("cust fname: " + result.Envelope.Body.readResponse.response.cust.fName);
})
}
var input = '<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>';
parseBody(input);```
关于node.js - 使用 xml2js 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45594547/