Writing XML and preserve comments
Dear all,
Now that I have manged to read all sorts of information from an XML file I want to go one step further and save created or modified data back to the XML file. While a function WriteXmlData (xData, sXmlFile) is quite simple and works for most situations (see hereafter), I encounter these problems:
- An XML file is per defintion a human readeable file - why else would there be XML comments. When reading (parsing) the xml file comments ar stripped by default. How can I preserve the comments? I do not understand how to use the XML class properties (BTW the term class is very misleading for simple minds like me). In particular how do I use the property ignoreComments?
The following does not work at all:
function main () {
var oXmlSettings, xmlData;
oXmlSettings = xmlData.defaultSettings(); // xml reader settings ?
oXmlSettings.ignoreComments = false; // are they keypt ?
xmlData.setSettings(oXmlSettings); // are these the new settings?
- Also in chapter XML Object Reference of the JavaScript Tools Guide CC there is described how to use JS variables in XML data. While this works perfectly within the script, trying to write the data out to the file clears the file!
function main () {
var nItems;
var oXmlSettings, xmlData, xmlData2, sXmlFile = "WriteXml.xml"; // in same dir as this script;
var bWord = 1, bCase = 0, bBack = 0, bClone = 0, sSearchMode = "RegeX",
sFindType = "Conditional Tag →", sName = "Experiment with JS varaibles";
var xmlData2 =
<item>
<name>{sName}</name>
<info>Elements and attributes set via JS variables.</info>
<options searchMode={sSearchMode} word={bWord} case={bCase} back={bBack} />
<findtype>{sFindType}</findtype>
<findstring>*something</findstring>
<replmode>To Text:</replmode>
<replstring>$1\t</replstring>
</item>
xmlData = GetXMLdata (sXmlFile); // already contains the root and two items
// This works perfectly, because xmlData1 does not use JS variables
nItems = xmlData.item.length();
xmlData.item[nItems] = xmlData1;
WriteXML (xmlData, sXmlFile);
// This, however clears the file!
$.bp(true);
nItems = xmlData.item.length(); // n
xmlData.item[nItems] = xmlData2; // xmlData correctly appended
nItems = xmlData.item.length(); // n+1
WriteXML (xmlData, sXmlFile); // file is cleared!!!!
}
Please find the complete script and xml data file attached. AAAArgh, ZIP can not be attached. So find it here: https://daube.ch/zz_tests/WriteXML.zip

