subsoft subsoft - 2 months ago 17
Node.js Question

How to use js2xmlparser to output xml

Hi currently i am using js2xmlparser module to generate XML using node.

I have managed to structure most of the xml as required but not sure how to iterate through Json object as below and format xml as required:

Here is the sample Json object:

Json data format as (data):
{
Group-type-1:"Value1",
Group-type-2:"Value2",
Group-type-3:"Value3",
Group-type-4:"Value4"
}


Expected XML data format:

<main-group>
<group>
<name>Group type 1</name>
<value>Some value</value>
</group>
<group>
<name>Group type 2</name>
<value>Some value</value>
</group>
<group>
<name>Group type 3</name>
<value>Some value</value>
</group>
<group>
<name>Group type 4</name>
<value>Some value</value>
</group>
</main-group>


Here is what I have done so far:

parsedBody = JSON.parse(data);

"main-group":{
"group":{
"name":"Group type 1",
"vale":parsedBody["Group-type-1"]
},
...
...
...
}

Answer

You need to use an array.

The following example uses the latest version of js2xmlparser (2.0.2, at the time of writing):

var js2xmlparser = require("js2xmlparser");
js2xmlparser.parse("main-group", {
    "group": [
        {
            "name": "Group type 1",
            "value": "Some value 1"
        },
        {
            "name": "Group type 2",
            "value": "Some value 2"
        },
        ...
    ]
});
Comments