我试图解析xml到json &我在nodejs中使用xml2js。下面是我的代码:
var chai = require('chai');
var chaiHttp = require('chai-http');
var request = chai.request;
var should = chai.should();
var expect = chai.expect;
var assert = chai.assert;
var supertest = require('supertest');
var fs = require('fs');
var xmlLocation = "./configdata/xmlDoc.xml";
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
//Plugin for HTTP, etc.
chai.use(chaiHttp);
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
//xmlFile = JSON.parse(fs.readFileSync(xmlData, 'utf8'));
describe("Test : ", function () {
it("convert xml to json", function (done) {
r = fs.readFileSync(xmlLocation, 'UTF-8');
parser.parseString(r, function (err, parsedData) {
if (err) throw err;
else {
fs.writeFile("jsonData.json", JSON.stringify(parsedData), function (err, response) {
});
}
});
done();
});
})
xml文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
<ALEXA>
<SD TITLE="A" FLAGS="" HOST="davidwalsh.name">
<TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
<LINKSIN NUM="1102"/>
<SPEED TEXT="1421" PCT="51"/>
</SD>
<SD>
<POPULARITY URL="davidwalsh.name/" TEXT="7131"/>
<REACH RANK="5952"/>
<RANK DELTA="-1648"/>
</SD>
</ALEXA>
输出如下:
{
"ALEXA": {
"SD": [
{
"$": {
"TITLE": "A",
"FLAGS": "",
"HOST": "davidwalsh.name"
},
"TITLE": [
{
"$": {
"TEXT": "David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"
}
}
],
"LINKSIN": [
{
"$": {
"NUM": "1102"
}
}
],
"SPEED": [
{
"$": {
"TEXT": "1421",
"PCT": "51"
}
}
]
},
{
"POPULARITY": [
{
"$": {
"URL": "davidwalsh.name/",
"TEXT": "7131"
}
}
],
"REACH": [
{
"$": {
"RANK": "5952"
}
}
],
"RANK": [
{
"$": {
"DELTA": "-1648"
}
}
]
}
]
}
}
'$'被添加到解析的json中。如何避免??
解决方案:
const parser = xml2js.Parser({mergeAttrs: true, attrkey: 'ANYTHINGELSE' , explicitArray:false});
我们如果需要一个包,是需要理解这个包都给提供了那些配置项的,比如这个xml2js,每个人的需求都不一致,所以它提供了很多选项。
比如,值里面涉及到了数字,xml2js转换来的json key和value都是字符串。
有一些定义很重要,一定要写清楚,这个定义应该是要贯穿整个项目,这样才能统一规范
References:
https://stackoverflow.com/questions/44106133/unable-to-parse-xml-to-json-properly
https://www.npmjs.com/package/xml2js
https://stackoverflow.com/questions/42804620/xml2js-xml-tag-values-converted-to-array-of-jsons
网友评论