Haydn Welch
Haydn Welch

Reputation: 3

Insert new XML element to existing XML document in JS

I am parsing XML via libxmljs2 and then trying to add an extra element, see example below.

var x = require('libxmljs2');

var xmlDoc = x.parseXmlString(`<?xml version="1.0" encoding="UTF-8"?>
<ns:FOO xmlns:ns=“example ns" xmlns:ns2="example ns 2”>
   <ns:A>
      <ns2:X>TEXT</ns2:X>
   </ns:A>
   <ns:B>
      <ns2:Y>TEXT</ns2:Y>
      <ns2:Z>TEXT</ns2:Z>
      <ns2:P>TEXT</ns2:P>
   </ns:B>
</ns:FOO>`)

What i want is to make it like:

    <?xml version="1.0" encoding="UTF-8"?>
    <ns:FOO xmlns:ns=“example ns" xmlns:ns2="example ns 2">
       <NEW-ELEMENT>
          <NEW-SUB-ELEMENT>
            <ANOTHER-NEW-SUB-ELEMENT>TEXT</ANOTHER-NEW-SUB-ELEMENT>
          <NEW-SUB-ELEMENT>
       </NEW-ELEMENT>
       <ns:A>
          <ns2:X>TEXT</ns2:X>
       </ns:A>
       <ns:B>
          <ns2:Y>TEXT</ns2:Y>
          <ns2:Z>TEXT</ns2:Z>
          <ns2:P>TEXT</ns2:P>
       </ns:B>
    </ns:FOO>

This is what I am trying to do:

const reqNode = xmlDoc.get('//ns:FOO', { FOO: 'example'})

const doc = new x.Document();
      doc
          .node('NEW-ELEMENT')
          .node('Service', "TI")
          .parent()
          .node('NEW-SUB-ELEMENT')
            .node('ANOTHER-NEW-SUB-ELEMENT', 'TEXT')
          .parent()
        .parent().toString()
    reqNode.addChild(doc)

However it seems to make it like:

<?xml version="1.0" encoding="UTF-8"?>
    <ns:FOO xmlns:ns=“example ns" xmlns:ns2="example ns 2">
       <ns:A>
          <ns2:X>TEXT</ns2:X>
       </ns:A>
       <ns:B>
          <ns2:Y>TEXT</ns2:Y>
          <ns2:Z>TEXT</ns2:Z>
          <ns2:P>TEXT</ns2:P>
       </ns:B>
       <NEW-ELEMENT>
           <NEW-SUB-ELEMENT>
               <ANOTHER-NEW-SUB-ELEMENT>TEXT</ANOTHER-NEW-SUB-ELEMENT>
           <NEW-SUB-ELEMENT>
       </NEW-ELEMENT>
    </ns:FOO>

Any ideas, where I'm doing wrong?

Much appreciated

Upvotes: 0

Views: 739

Answers (1)

brunnerh
brunnerh

Reputation: 184516

node(...) always adds the node at the end. If you want to insert an element elsewhere you can use addPrevSibling(siblingNode) to insert a node before the Element that was called on. So here you would first find the ns:A Element and then call that function on it (you probably have to construct the child element explicitly so it can be passed as an argument).

Upvotes: 1

Related Questions