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.

4

2 回答 2

1

尝试将您的 JSON 重新格式化为类似的格式。

{
   "myValue": "1",
   "myItems": {
      "myItem": [
        "13",
        "14",
        "15",
        "16"
      ]   
   }
}
于 2017-07-24T22:27:26.943 回答
0

这个问题正在 GitHug 上讨论:https ://github.com/Leonidas-from-XIV/node-xml2js/issues/428

在@Stucco 的回答的基础上,我做了一个简单的函数来将数组嵌套在所需的名称下:

    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);

上面的例子给出了这个 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>

但是如果你的数组嵌套得更深,我的简单函数将需要调整。

于 2018-06-15T19:01:05.250 回答