添加JSON对象转换成一个对象,并出口到XML

问题描述:

我想产生类似的XML文档:添加JSON对象转换成一个对象,并出口到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项目?任何建议是非常感谢。

+0

''笏 – Will

+1

是这一个题? – khinester

好,我必须创建初始对象,例如document然后在该推每个项目,是这样的:<![CDATA [8.325]]>

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