We help IT Professionals succeed at work.
Get Started

Problem with XML format after insert a new XMLNode

Ingo Förster
Last Modified: 2019-11-21
In my node app I have to insert a new XMLnode for identify it later. I developed some code where I expected the right result.
It is really simple:

var xmlDoc = new DOMParser().parseFromString(dataRegelWerk);  //Incomming data
if(allok == false){
                var root = xmlDoc.documentElement;

                var varselem = xmlDoc.getElementsByTagName('vars')[0];
                var newEle = xmlDoc.createElement('TCafe');
                var att1 = xmlDoc.createAttribute("initvalue");
                att1.value = "1";
                var att2 = xmlDoc.createAttribute("type");
                att2.value = "int";

                root.insertBefore(newEle, varselem);

var myFile = serializer.serializeToString(xmlDoc); //Put back to string to store in db

Open in new window

This is the original formatted XML

<xml xmlns:xi="http://www.w3.org/2001/XInclude">


Open in new window

I tried to insert before "vars" and the result is

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/><vars>

Open in new window

But I expected

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/>


Open in new window

Is there anything wrong with my code or do I expect a wrong thing? Maybe I have to close the new XMLNode? (I expected the last / will do it.
Any help will be great.
Watch Question
Senior Developer
This problem has been solved!
Unlock 1 Answer and 1 Comment.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE