My goal is to output a modified XML file and preserve a special indentation that was present in the original file. The objective is so that the resulting file still looks like the original, making them easier to compare and merge through source control.
My program will read a XML file and add or change one specific attribute.
Here is the formatting I'm trying to achieve / preserve:
<Base Import="..\commom\style.xml">
<Item Width="480"
Height="500"
VAlign="Center"
Style="level1header">
(...)
In this case, I simply wish to align all attributes past the first one with the first one.
XmlWriterSettings provides formatting options, but they won't achieve the result I'm looking for.
settings.Indent = true;
settings.NewLineOnAttributes = true;
These settings will put the first attribute on a newline, instead of keeping it on the same line as the node, and will line up attributes with the node.
Here is the Load call, which asks to preserve whitespace:
MyXml = XDocument.Load(filepath, LoadOptions.PreserveWhitespace);
But it seems like it won't do what I expected.
I tried to provide a custom class, which derives from XmlWriter to the XDocument.Save call, but I haven't managed to insert whitespace correctly without running into InvalidOperationException. Plus that solution seems overkill for the small addition I'm looking for.
For reference, this is my save call, not using my custom xml writer (which doesn't work anyway)
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;
settings.OmitXmlDeclaration = true;
using (XmlWriter writer = XmlWriter.Create(filepath + "_auto", settings))
{
MyXml.Save(writer);
}