我在nodeJs中使用xml2json库。我有xml:
<SchedulingModel >
<Jobs>
<Job Id="1">
<Operations>
</Operations>
</Job>
<Job Id="2">
<Operations>
</Operations>
</Job>
<Job Id="3">
<Operations>
</Operations>
</Job>
<Job Id="4">
<Operations>
</Operations>
</Job>
<Job Id="5">
<Operations>
</Operations>
</Job>
</Jobs>
</SchedulingModel>
我试图解析这个xml:
const parser = new xml2js.Parser();
parser.parseString(plannerXML , (err, result) => {
console.log(result["SchedulingModel"]["Jobs"]);
});
但是在解析结果后,我在作业数组中只有一个对象
console.log(result);
{ SchedulingModel:
Jobs: [ [Object] ]
}
谁能说出错是什么? 我需要这个xml中的所有对象。
答案 0 :(得分:2)
我通常使用FocusedFrame
从xml转换为json,并轻松更改所需的结果。
您可以尝试使用以下示例(例如,在操作中添加一些文本):
const xml = '<SchedulingModel><Jobs><Job Id="1"><Operations>a</Operations></Job><Job Id="2"><Operations>b</Operations></Job><Job Id="3"><Operations>c</Operations></Job><Job Id="4"><Operations>d</Operations></Job><Job Id="5"><Operations>e</Operations></Job></Jobs></SchedulingModel>'
const temp = {
SchedulingModel: ['/SchedulingModel/Jobs/Job', {
Id: '@Id',
Operations: 'Operations'
}]
}
const transform = require('camaro')
const results = transform(xml, temp)
console.log(JSON.stringify(results, null, 2))
响应:
{
"SchedulingModel": [
{
"Id": "1",
"Operations": "a"
},
{
"Id": "2",
"Operations": "b"
},
{
"Id": "3",
"Operations": "c"
},
{
"Id": "4",
"Operations": "d"
},
{
"Id": "5",
"Operations": "e"
}
]
}
答案 1 :(得分:1)