Reputation: 159
I'm using xml2json library in nodeJs. I have got 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>
I'm trying to parse this xml:
const parser = new xml2js.Parser();
parser.parseString(plannerXML , (err, result) => {
console.log(result["SchedulingModel"]["Jobs"]);
});
But after parsing in result I have just one object in Jobs array
console.log(result);
{ SchedulingModel:
Jobs: [ [Object] ]
}
Who can say what's wrong? I need all object from this xml.
Upvotes: 0
Views: 1478
Reputation: 196
I usually use camaro for transform from xml to json with easily change the desired result.
You can try with below sample (added some text to operations for example):
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))
Response:
{
"SchedulingModel": [
{
"Id": "1",
"Operations": "a"
},
{
"Id": "2",
"Operations": "b"
},
{
"Id": "3",
"Operations": "c"
},
{
"Id": "4",
"Operations": "d"
},
{
"Id": "5",
"Operations": "e"
}
]
}
Upvotes: 2
Reputation: 26
first I noticed that you arent using xml2json package, the package you are using is xml2js. I tried your build and xml2js doesnt work as you imagine, it creates a single object called "Job" as an array of jobs. For a more visual test just place a stringify like this:
parser.parseString(plannerXML , (err, result) => {
console.log(JSON.stringify(result["SchedulingModel"]["Jobs"]));
});
I hope it helps.
Upvotes: 1