node.js transform xml into json with xml2js

502 views Asked by At

I am using the node.js package xml2js to transform xml into json. Documentation is here: https://www.npmjs.com/package/xml2js

My problem is that attributes for those xml are not correctly transformed.

example XML with multiple events

<events><event id="E0-001-098932239-8"></event><event id="E0-001-105389601-2"></event><event id="E0-001-104342965-3"></event><event id="E0-001-104830349-3"></event><event id="E0-001-105374979-6"></event><event id="E0-001-105389620-7"></event><event id="E0-001-104247759-2"></event><event id="E0-001-104342949-5">

Result from JSON.stringify(result.search.events)

The event tag is only once in the generated JSON - My expectation is that it should have multiple tags event. So I assume the transformation process went wrong. I tried multiple options for the parser like ignoreAttrs, explicitArray or explicitChildren but without success.

[{
    "event": [{
            "$": {
                "id": "E0-001-098932239-8"
            },
            ]
        }, {
            "$": {
                "id": "E0-001-105389601-2"
            },
        }, {
            "$": {
                "id": "E0-001-104342965-3"
            },
        }, {
            "$": {
                "id": "E0-001-104830349-3"
            },

access JSON elements

After correct transformation I expect to simply access the JSON elements via event[1].$.id

but all tries are unsuccessful:

  • events.event --> undefined
  • events.event.$ --> undefined
  • events.$ --> undefined

My Question is now: how can i correctly transform the xml into JSON and access the elements correctly?

1

There are 1 answers

1
Anh Thang Bui On BEST ANSWER

Javascript is starting from 0, you should get events[0].event[0].$.id

Also, you can try with another package (camaro) with simply and easily change the desired result.

Example:

const xml = '<events><event id="E0-001-098932239-8"></event><event id="E0-001-105389601-2"></event><event id="E0-001-104342965-3"></event><event id="E0-001-104830349-3"></event><event id="E0-001-105374979-6"></event><event id="E0-001-105389620-7"></event><event id="E0-001-104247759-2"></event><event id="E0-001-104342949-5"></event></events>'

const temp = {
    events: ['/events/event', {
        id: '@id'
    }]
}

const transform = require('camaro')
const results = transform(xml, temp)

console.log(JSON.stringify(results, null, 2))

Results

{
    "events": [
        {
            "id": "E0-001-098932239-8"
        },
        {
            "id": "E0-001-105389601-2"
        },
        {
            "id": "E0-001-104342965-3"
        },
        {
            "id": "E0-001-104830349-3"
        },
        {
            "id": "E0-001-105374979-6"
        },
        {
            "id": "E0-001-105389620-7"
        },
        {
            "id": "E0-001-104247759-2"
        },
        {
            "id": "E0-001-104342949-5"
        }
    ]
}