Reputation: 35
I'm creating an XML file using a foreach to add the data.
Problem:
I need to create an ELEMENT < Listings > and inside it I need to put the children that will be Listing given .... < /Listing > and after that FOR I need to close the < /Listings >
What is happening is that it is creating the xml file with the Listings element already closed example: < Listings/ >
Code:
var xml = builder.create('ListingDataFeed', { version: '1.0', encoding: "UTF-8"});
xml.ele('Listings');
// var listings = xml.ele('Listings');
for(var i=0; i< result.length; i++){
xml.ele('Listing')
.ele('ListingID', `${result[i].sku}`).up()
.ele('Title').dat(`${result[i].name}`).up()
.ele('TransactionType', `${transaction}`).up()
.ele('PublicationType', `${type_offer}`).up()
.ele('DetailViewUrl', 'https://sortinvestimentos.com.br/imovel/' + `${result[i].url}`).up()
.ele('Media')
.ele('Item', {'medium': 'image'}, `${result[i].media_1}`).up()
.up() // Media finish
.ele('ContactInfo')
.ele('Name', 'Sort Investimentos').up()
.ele('Email', '[email protected]').up()
.up()
.up() // Listing finish
}
.up(); // Listings finish
var root = xml.end({ pretty: true});
This result
Upvotes: 1
Views: 1580
Reputation: 538
Here is a working example:
var {create} = require("xmlbuilder2");
const R = [{name: 'foo1', sku: 'bar1'}, {name:'foo2', sku: 'bar2'}];
let xml = create({ version: '1.0', encoding: "UTF-8"})
.ele('ListingDataFeed')
.ele('Listings');
for(let i = 0; i<R.length;i++){
xml.ele("Listing")
.ele("listingId: ", `${R[i].sku}`).up()
.ele('Title').dat(`${R[i].name}`).up().up();
//rest of your code
}
The point being that the ele()
function creates a new node and returns that node. Therefore, when you call your loop, you have to make sure that the xml
variable is pointing to the Listings
node, so the child elements are attached to it.
In the code above, at the beginning of the loop, the xml
var is pointing the newly created Listings
element.
Upvotes: 2