How to parse multiple xml objects present at same level in the response

My question:
I’m getting the below XML response from my API call

<data name="xyz" isRequired="Yes" departmentNumber="123"> </data>
<data name="abc" isRequired="No" departmentNumber="125"> </data>
<data name="mnq" isRequired="Yes" departmentNumber="123"> </data>

when I’m doing let jsonObject = xml2Json(pm.response.text()); its only returning me first data object. How I can get all the data objects and parse them to JSON as array?

Hello @vaibhavbarmkar :wave:

Can you please have a look at this post?

Try using


let xml2js = require('xml2js');

let xml = pm.response.text();

Hi @vaibhavbarmkar,

Is this the entire response of your API call? If so, I can replicate the problem, and I understand why it is happening; XML documents are supposed to only have a single root node, and this is why xml2json only parses the first object that it encounters. (I see the same problem when I try to use xml2js as well.)

I think the best way to resolve would be to pad your response to include a parent tag, for instance:

jsonObject = xml2Json("<myData>" + pm.response.text() + "</myData>");
console.log(jsonObject); 

Now I see all three nested items are correctly parsed:

You can then access individual items, e.g.

console.log(jsonObject.myData.data[0].$.name)
1 Like

Thanks, @neilstudd for the above solution. As of now, I used cheerio lib for parsing

const $ = cheerio.load(jsonData1, {
xml: {
normalizeWhitespace: true,
},
});

its bit complex but worked for me. But I think your solution should be cleaner approach.