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+'});
If I add an element to my document, the final output is wrong formatted. The result is not valid I think.
Original XML
Changed XML
Expected XML
Code