【问题标题】:json to xml with xml2js Array elementnamejson 到 xml 与 xml2js 数组元素名
【发布时间】:2017-09-26 04:05:27
【问题描述】:

我正在使用 xml2js 节点将 json 对象转换为 xml 文件。我想在解析我的 json 时设置数组项元素名称

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

我希望它看起来像(并将“元素”标签设置为“myItem”)

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

但是xml2js就给我

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

是否有任何选项可以设置或者我需要以某种方式格式化我的 json?能够设置“元素”标签名称?我今天有xml2js的最新更新。

【问题讨论】:

  • 能够解决这个问题。我需要在代码中创建一个额外的对象(myItems 不是数组)并将数组重命名为 myItem,然后将数组元素移动到该对象。它以正确的方式解析它。然后 Json 变为 { "myValue": "1", "myItems":{ myItem:[ "13", "14", "15", "16" ]} } 但这仍然必须能够使用中的选项xml2js
  • js2xml 默认做类似的事情;它将数组项放在 之间。但我也宁愿坚持使用 xml2js

标签: json xml xml2js


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    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>
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-05
      • 2020-12-29
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多