我正在尝试从SOAP xml响应中提取令牌。我尝试了各种片段,并得出以下结论:
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var options = {
"method": "POST",
"hostname": "www.titlepage.com",
"port": null,
"path": "/ws/TitleQuery.php",
"headers": {
"content-type": "text/xml",
"cache-control": "no-cache",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
const xml = (body.toString());
parser.parseString(xml, function (err, result) {
if (err) {
console.error('here is the eror: ', err);
} else {
jsonLog = (JSON.stringify(result, null, 2));
console.log(result['SOAP-ENV:Envelope']['SOAP-ENV:Body'][0]['ns1:LoginResponse'][0]['Token']['0']);
}
});
});
});
req.write("<?xml version="1.0"?>n<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">n <soap:Body xmlns:m="http://www.titlepage.com/ws">n <m:Login>n <m:UserName>a105yn</m:UserName>n <m:Password>pink6PUPT1yult*kul</m:Password>n </m:Login>n </soap:Body>n</soap:Envelope>");
req.end();
结果是:
{
_: '312cb0ee6c346ee266dc95bc6c688021',
'$': { 'xsi:type': 'xsd:string' }
}
]
我如何进入最后一步并访问令牌(_ key)的值,_ key是什么?
你可以试试这个
var convert = require('xml-js');
var xml = `<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.titlepage.com/ws">
<m:Login>
<m:UserName>Username goes here</m:UserName>
<m:Password>Password goes here</m:Password>
</m:Login>
</soap:Body>
</soap:Envelope>`
var options = {compact: true, spaces: 4, elementNameFn: function(val) {return val.replace('soap:','');}};
var result = convert.xml2json(xml,options);
console.log(result);
var extract = JSON.parse(result)
console.log(extract.Envelope.Body['m:Login']['m:UserName']["_text"]) //Prints "Username goes here"
console.log(extract.Envelope.Body['m:Login']['m:Password']["_text"]) //Prints "Password goes here"