In my initializing service, I'm creating a empty xml using xml-writer node package as follows
createEmptyXML(xw: any) {
xw.startDocument()
xw.startElement('Hello').writeAttribute('name', '_nameOfThePerson')
}
Which creates something like this
<?xml version="1.0"?>
<Hello name="_nameOfThePerson"/>
I want to write a function that can add child tags to the Hello tag. Something like the following
<?xml version="1.0"?>
<Hello name="_nameOfThePerson"/>
<childTag name="A"/>
<childTag name="B"/>
</Hello>
My approach was to save the initial writer in a store and pass it to a method and use it to add elements, like follows
writeXML(xw: any): void {
xw.startElement('childTag').writeAttribute('name', 'A')
}
In the first attempt is works correctly as expected. It adds the child tag inside my Hello tag.
<?xml version="1.0"?>
<Hello name="_nameOfThePerson"/>
<childTag name="A"/>
</Hello>
But when i use that method again, it gives a result like this
<?xml version="1.0"?>
<Hello name="_nameOfThePerson"/>
<childTag name="A"/>
</Hello>
<childTag name="B"/>
How do I add my second child Tag right after the first one, and not after the Hello tag.
Try assigning the parent/hello tag to the variable, which will be store/passed to methods:
and then later:
Try this code, it should produce the desired output, which you can then adapt according to your code design pattern:
So, make sure you pass/write to the parent, not the document instance. For example: