2

I am using xml2js node to transform an json object to xml file. I want to set the array items element name when parsing my json

{
   "myValue": "1",
   "myItems": [
      "13",
      "14",
      "15",
      "16"
   ]
}

and i want it to look like (and set "element" tag to "myItem")

<root>
   <myItems>
      <element>13</element>
      <element>14</element>
      <element>15</element>
      <element>16</element>
   </myItems>
   <myValue>1</myValue>
</root>

but xml2js just give me

<root>
      <myItems>13</myItems>
      <myItems>14</myItems>
      <myItems>15</myItems>
      <myItems>16</myItems>
      <myValue>1</myValue>
</root>

Are there any options to set or I need to format my json on a certain way? To be able to set "element" tag name? I have the lastest update of xml2js today.

joakimja
  • 2,707
  • 2
  • 17
  • 25
  • To be able to get around this. I needed to create a extra object(myItems not an array) in code and rename the array to myItem and then move the array elements to this object. The it parse it on correct way. The Json then become { "myValue": "1", "myItems":{ myItem:[ "13", "14", "15", "16" ]} } But still this must be able to to with options in xml2js – joakimja Apr 28 '17 at 07:35
  • js2xml does something similar by default; it puts array items between . But I, too, would rather stick to xml2js – Félix Paradis Jun 15 '18 at 17:08

2 Answers2

2

Try reformatting your JSON to something like this.

{
   "myValue": "1",
   "myItems": {
      "myItem": [
        "13",
        "14",
        "15",
        "16"
      ]   
   }
}
Stucco
  • 388
  • 5
  • 21
0

This issue is being discussed on GitHug: https://github.com/Leonidas-from-XIV/node-xml2js/issues/428

Building on @Stucco's answer, I made a simple function to nest arrays under a desired name:

    var item = {
        word: 'Bianca',
        vowels: [ 'i' ],
        bannedVowels: [ 'a' ],
        syllabs: [ 'Bian', 'ca' ],
        sounds: [ 'an' ]
    };

    var output = {};

    _.each(item, function(value, key) {
        // this is where the magic happens
        if(value instanceof Array)
            output[key] = {"item": value};
        else
            output[key] = value;
    })

    var builder = new xml2js.Builder({rootName: "item"});
    var xml = builder.buildObject(output);

The above example gives this XML:

<item>
    <word>Bianca</word>
    <vowels>
         <item>i</item>
    </vowels>
    <bannedVowels>
         <item>a</item>
    </bannedVowels>
    <syllabs>
         <item>Bian</item>
         <item>ca</item>
    </syllabs>
    <sounds>
         <item>an</item>
    </sounds>
</item>

But my simple function will need tweaking if your arrays are nested deeper.

Félix Paradis
  • 5,165
  • 6
  • 40
  • 49