I’m trying to read an existing XML file, modify the InnerText and Attribute values for a bunch of nodes, and then save changes back to the file.
I’m using the below code. When the XML file is saved, it messes up the formatting. For example, line breaks between some nodes disappear. How do I preserve (or re-format as well formatted & indented) the XML file?
XmlDocument xDoc = new XmlDocument();
using (XmlReader xRead = XmlReader.Create(strXMLFilename))
{
xDoc.Load(xRead);
}
//Makes changes to a few nodes
XmlWriterSettings xwrSettings = new XmlWriterSettings();
xwrSettings.IndentChars = "\t";
xwrSettings.NewLineHandling = NewLineHandling.Entitize;
xwrSettings.Indent = true;
xwrSettings.NewLineChars = "\n";
using (XmlWriter xWrite = XmlWriter.Create(strXMLFilename, xwrSettings))
{
xDoc.Save(xWrite);
}
Okay, so the
XmlDocumentobject, by default, ignores whitespace. I had to force it to preserve whitespace like this —and BAM! Problem solved!