Problem with XML format after insert a new XMLNode

Ingo Förster
Ingo Förster used Ask the Experts™
on
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";
                newEle.setAttributeNode(att1);
                newEle.setAttributeNode(att2);

                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">

   <vars>
....

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"/>

       <vars>

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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior Developer
Commented:
Both, I guess.

You're inserting the new node before the vars node. Thus what you'll get.
And the formatting is no releveant, thus what you get and expect is sematically the same.

When you expect a certain formatting (line brakes, indenting) then you need to look into your serialzer, whether it supports control over those properties.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial