0

I am trying to convert an xml file to csv file using node.js diretly.

My xml file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<testResults version="1.2">
<httpSample ts="1501597136964" lb="req_10">
  <responseData class="java.lang.String">1501597138973</responseData>
</httpSample>
<httpSample ts="1501597136964" lb="req_10">
  <responseData class="java.lang.String">1501597139525</responseData>
</httpSample>
<httpSample ts="1501597136964" lb="req_10">
  <responseData class="java.lang.String">1501597139716</responseData>
</httpSample>
</testResults>

I am able to get the value of <responseData class="java.lang.String">1501597138973</responseData>. But I also want to parse the value of ts="1501597136964" and lb="req_10" from <httpSample> tag

I am using xml2rec package

var xml2rec=require('xml2rec');
xml2rec('xmlFile.xml', 'httpSample', 'csvFile.csv');

Should I be checking any other packages that can help me do this or I have to go the long way to convert from xml to json first and then json to csv?? Also, in doing so, will I be able to get the value of ts and lb attributes of httpSample tag??

P.S. The output xml file is JMeter response file

1 Answer 1

1

Not sure what's the best way to do this but since xml structure is not flat anyway, you will have to flatten it before converting to csv.

const transform = require('camaro')
const json2csv = require('json2csv').parse

const xml = `
<?xml version="1.0" encoding="UTF-8"?>
<testResults version="1.2">
<httpSample ts="1501597136964" lb="req_10">
  <responseData class="java.lang.String">1501597138973</responseData>
</httpSample>
<httpSample ts="1501597136964" lb="req_10">
  <responseData class="java.lang.String">1501597139525</responseData>
</httpSample>
<httpSample ts="1501597136964" lb="req_10">
  <responseData class="java.lang.String">1501597139716</responseData>
</httpSample>
</testResults>
`
const template = {
    data: ['//httpSample', {
        ts: '@ts',
        lb: '@lb',
        resp: 'responseData'
    }]
}

const result = transform(xml, template)
const csv = json2csv(result.data)
console.log(csv)

Output:

"lb","resp","ts"
"req_10","1501597138973","1501597136964"
"req_10","1501597139525","1501597136964"
"req_10","1501597139716","1501597136964"
Sign up to request clarification or add additional context in comments.

1 Comment

So we do usually go from xml to json and then json to csv... Let me try if this is helpful in my case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.