将JSON对象添加到对象中并导出到XML

时间:2017-07-28 18:20:31

标签: javascript json xml

我想生成一个类似于:

的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-xml https://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项?任何建议都非常感谢。

1 个答案:

答案 0 :(得分:0)

好吧,我必须创建初始对象,例如def loopit(words, aggregator): for word in words: aggregator.do_unknown_caulculation(word) return aggregator.get_result() def comprehendit(words, aggregator): [aggregator.do_unknown_caulculation(word) for word in words] return aggregator.get_result() words = ['I', 'need', 'to', 'aggregate', 'this'] print (loopit(words, BlackBox()), comprehendit(words, BlackBox())) ,然后按下每个项目,例如:

document