简体   繁体   English

使用 xml2js 构建具有相等子键的 xml?

[英]Using xml2js to build xml with equal child key?

I'm using xml2js to build a .xml from my registers.我正在使用xml2js从我的寄存器构建一个 .xml。 For each element, i need to set the key with same name, example: key: product with an attribute id对于每个元素,我需要设置具有相同名称的键,例如:key: product with an attribute id

The expected result:预期结果:

<products>
  <product id="H12896">
    <name>Grand Hotel New York</name>
    <price>120.80</price>
  </product>
  <product id="...">
    ...
  </product>
</products>

My code:我的代码:

var products = [];

_.each(list, function(element) {

    var obj = {
      name: element.title,
      price: element.price,
    };

    products.push(obj);


});


var builder = new xml2js.Builder({rootName: 'products'});
var xml = builder.buildObject(products);
fs.writeFile('pacotes.xml', xml, (err) => {
  if (err) throw (err);
});

Output result:输出结果:

<products>
  <0>
    <name>Mountain Do</name>
    <price>0</price>
  </0>
</products>

I checked the documentation, but nothing yet.我检查了文档,但还没有。 Thanks谢谢

Is there a reason you're not using XMLBuilder?您是否有不使用 XMLBuilder 的原因? https://github.com/oozcitak/xmlbuilder-js/ https://github.com/oozcitak/xmlbuilder-js/

XMLBuilder seems much better suited for what you're wanting to do, and is much, much more popular (ex: 4 million downloads in the last month). XMLBuilder 似乎更适合您想要做的事情,而且更受欢迎(例如:上个月的下载量为 400 万次)。 xml2js is better suited for reading in JavaScript, but XMLBuilder is definitely what you'd want to use. xml2js 更适合在 JavaScript 中阅读,但 XMLBuilder 绝对是您想要使用的。

And if I'm reading correctly... xml2js is just building on XMLBuilder anyway.如果我没看错的话... xml2js 只是建立在 XMLBuilder 上。

var builder = require('xmlbuilder'),
    xml = builder.create('root'),
    products = xml.ele('products'),
    product;

_.each(list, function(element) {
    product = products.ele('product');
    product.att('id', element.id);
    product.ele('name', null, element.name);
    product.ele('price', null, element.price);
});

xml = xml.end();
fs.writeFile('pacotes.xml', xml, (err) => {
    if (err) throw (err);
});

You can just create a list of objects and use the name that you want to use as the key:您可以创建一个对象列表并使用您想要用作键的名称:

const productList = [
  { name: 'foo', price: 30 },
  { name: 'bar', price: 5 },
  { name: 'baz', price: 87 },
];

const obj = { product: [] }

productList.forEach(element => obj.product.push({
  name: element.title,
  price: element.price,
}));

const builder = new xml2js.Builder({rootName: 'products'});
const xml = builder.buildObject(obj);
console.log(xml);

Output:输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<products>
  <product>
    <name/>
    <price>30</price>
  </product>
  <product>
    <name/>
    <price>5</price>
  </product>
  <product>
    <name/>
    <price>87</price>
  </product>
</products>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM