I am creating the XML files in Node.js
using the XMLBuilder
package. Everything is working fine except for one thing. I am trying to add attributes to root
element but for some reason, it gets added to child
element.
I have declared my root
element like this:
//Create the header for XML
var builder = require('xmlbuilder');
var root = builder.create('test:XMLDocument')
root.att('schemaVersion', "2.0")
root.att('creationDate', '2020-10-09T09:53:00.000+02:00')
root.att('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance")
root = root.ele('MyBody')
root = root.ele('MyEvents')
After the declaration when I try to add some more attributes to my root elements:
root.att('new1','additionalAttributes1')
root.att('new2','additionalAttributes2')
It is getting appended to the MyEvents
and looks something like this:
<?xml version="1.0"?>
<test:XMLDocument schemaVersion="2.0" creationDate="2020-10-09T09:53:00.000+02:00">
<MyBody>
<MyEvents new1="additionalAttributes1" new2="additionalAttributes2">
</MyEvents>
</MyBody>
</test:XMLDocument>
But I am expecting the generated XML file to appear something like this:
<?xml version="1.0"?>
<test:XMLDocument schemaVersion="2.0" creationDate="2020-10-09T09:53:00.000+02:00" new1="additionalAttributes1" new2="additionalAttributes2">
<MyBody>
<MyEvents>
</MyEvents>
</MyBody>
</test:XMLDocument>
I am aware that if I declare my XML element like this then I am able to achieve the expected result but as I am passing it to another function I am unable to declare it like this:
//Create the header for XML
var builder = require('xmlbuilder');
var root = builder.create('test:XMLDocument')
root.att('schemaVersion', "2.0")
root.att('creationDate', '2020-10-09T09:53:00.000+02:00')
root.att('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance")
root.att('new1','additionalAttributes1')
root.att('new2','additionalAttributes2')
root = root.ele('MyBody')
root = root.ele('MyEvents')
I tried adding the .up() to see if it gets added to parent but no luck. Can someone please help me how can I add the attributes to parent when I have multiple child and achieve the required results?
you just have to go up twice
var builder = require('xmlbuilder')
var root = builder.create('test:XMLDocument')
root.att('schemaVersion', '2.0')
root.att('creationDate', '2020-10-09T09:53:00.000+02:00')
root.att('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
root = root.ele('MyBody')
root = root.ele('MyEvents')
root = root.up().up()
root.att('new1','additionalAttributes1')
root.att('new2','additionalAttributes2')
console.log(root.end({pretty: true}));
output
<?xml version="1.0"?>
<test:XMLDocument schemaVersion="2.0" creationDate="2020-10-09T09:53:00.000+02:00" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" new1="additionalAttributes1" new2="additionalAttributes2">
<MyBody>
<MyEvents/>
</MyBody>
</test:XMLDocument>