【问题标题】:add JSON object into an object and export to XML将 JSON 对象添加到对象中并导出到 XML
【发布时间】:2017-07-28 18:20:30
【问题描述】:

我想生成一个类似于以下内容的 XML 文档:

<?xml version="1.0" encoding="UTF-8"?>
<Documents>
   <Document>
     <ih_account><![CDATA[WEB100]]></ih_account>       
     <DocLine>
       <quan><![CDATA[1]]></quan>
       <sellprice><![CDATA[7.4916666666667]]></sellprice>
    </DocLine>
    <DocLine>
       <quan><![CDATA[1]]></quan>
       <sellprice><![CDATA[8.325]]></sellprice>
    </DocLine>
    <DocLine>
       <it_desc><![CDATA[Shipping]]></it_desc>
       <quan><![CDATA[1]]></quan>
       <sellprice><![CDATA[3.99]]></sellprice>
    </DocLine>
   </Document>
</Documents>

我正在使用node-xmlhttps://www.npmjs.com/package/xml,这是我目前拥有的代码

var xml = require('xml');
var order = {_id: 'WEB100', items: [{price: 2450, quantity: 10},{price: 2480, quantity: 10, },{ price: 100, quantity: 10 }]};

var createXML;
createXML = function(order) {
  var items, options, orderObject, ordered, toXML;
  options = {
    declaration: {
      version: "1.0",
      encoding: "UTF-8"
    }
  };
  items = order.items.ordered;
  ordered = items.map(function(it) {
    return {
      DocLine: [
        {
          quan: {
            _cdata: it.quantity
          }
        }, {
          sellprice: {
            _cdata: it.price
          }
        }
      ]
    };
  });
  orderObject = {
    OperaDocuments: [
      {
        Document: [
          {
            ih_account: {
              _cdata: order._id
            }
          }
        ]
      }
    ]
  };
  orderObject.OperaDocuments.Document = ordered;
  toXML = XML([orderObject], options);
  return console.log(toXML);
};

但这就是我要返回的:

<?xml version="1.0" encoding="UTF-8"?>
 <OperaDocuments>
   <Document>
    <ih_account><![CDATA[WEB100]]></ih_account>
   </Document>
 </OperaDocuments>

我如何包含Docline 项目?非常感谢任何建议。

【问题讨论】:

  • &lt;![CDATA[8.325]]&gt; wat
  • 这是一个问题吗?

标签: javascript json xml


【解决方案1】:

好的,我必须创建初始对象,例如 document,然后将每个项目推入其中,例如:

var document, ordered;

document = [
  {
    ih_doc: {
      _cdata: order_id
    }
  }
];

ordered = items.map(function(it) {
  return document.push({
    DocLine: [
      {
        it_sku: {
          _cdata: it.sku
        }
      }, {
        it_desc: {
          _cdata: it.name
        }
      }, {
        quan: {
          _cdata: it.quantity
        }
      }, {
        sellprice: {
          _cdata: it.price
        }
      }
    ]
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-12
    • 2015-09-21
    • 2017-10-27
    • 2019-12-22
    • 2021-04-12
    • 2021-12-24
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多