Inserting xml tag nodes inside existing tags as child tags

50 views Asked by At

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.

1

There are 1 answers

0
traynor On

Try assigning the parent/hello tag to the variable, which will be store/passed to methods:

const parent = xw.startElement('Hello').writeAttribute('name', '_nameOfThePerson');

and then later:

parent.startElement('childTag').writeAttribute('name', 'A').endElement();

Try this code, it should produce the desired output, which you can then adapt according to your code design pattern:

const xw = new XMLWriter();

xw.startDocument();

const parent = xw.startElement('Hello').writeAttribute('name', '_nameOfThePerson');

parent.startElement('childTag').writeAttribute('name', 'A').endElement();

parent.startElement('childTag').writeAttribute('name', 'b').endElement();

So, make sure you pass/write to the parent, not the document instance. For example:

parent!: any;

createParent(xw: any) {
    xw.startDocument();
    // now store parent somewhere
    // and pass/write it instead of the document instance
    const parent = xw.startElement('Hello').writeAttribute('name', '_nameOfThePerson')

    this.parent = parent;
}

// write to/send parent, instead of xw
writeChild(parent: any): void {
    // or this.parent...
    parent.startElement('childTag').writeAttribute('name', 'A').endElement();
}