jindw / xmldom

A PURE JS W3C Standard based(XML DOM Level2 CORE) DOMParser and XMLSerializer.
Other
819 stars 265 forks source link

Wrong format after InsertBefore #258

Open ognif opened 4 years ago

ognif commented 4 years ago

If I add an element to my document, the final output is wrong formatted. The result is not valid I think.

Original XML

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

   <vars>
....

Changed XML

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

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

Expected XML

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

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

       <vars>

Code

var DOMParser = require('xmldom').DOMParser;
var serializer = new (require('xmldom')).XMLSerializer;

var xmlDoc = new DOMParser().parseFromString(dataRegelWerk);

            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);

            fs.writeFileSync(filePath,myFile,{encoding:'utf8',flag:'w+'});