'Using xml2js to build xml with equal child key?
I'm using xml2js to build a .xml from my registers. For each element, i need to set the key with same name, example: 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
Solution 1:[1]
Is there a reason you're not using XMLBuilder? 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). xml2js is better suited for reading in JavaScript, but XMLBuilder is definitely what you'd want to use.
And if I'm reading correctly... xml2js is just building on XMLBuilder anyway.
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);
});
Solution 2:[2]
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.name,
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MattEnth |
Solution 2 | Community |