I am writing a tool that takes in an XML file, edits it by adding in elements and then saves it. The tricky bit is that the XML files need to be maintained human readable, and in this case that doesn't mean perfect formatting.
The input XElement contains many parameters such as this:
<Parameter key="lorem"> <Vector> <Value>2</Value><Value>3</Value> </Vector> </Parameter>
<Parameter key="lorem"> <Vector> <Value>2</Value><Value>3</Value> </Vector> </Parameter>
<Parameter key="lorem"> <Vector> <Value>2</Value><Value>3</Value> </Vector> </Parameter>
<Parameter key="lorem"> <Vector> <Value>2</Value><Value>3</Value> </Vector> </Parameter>
<Parameter key="lorem">
<Parameter key="ipsum">
<Parameter key="dolor">
<Vector> <Value>3</Value> <Value>4</Value> </Vector>
</Parameter>
</Parameter>
</Parameter
I want all XElements with name "Vector" and "Value" to disable indenting, but all XElements with name "Parameter" to maintain indenting.
Since my code isn't allowed to mess up any of the existing formatting, I am forced to use LoadOptions.PreserveWhitespace on the source document. This, however, forces all XElements that I add to the document to loose any formatting. Is there a way I can force a particular XElement to apply formatting, even though the whole document doesn't do it?
This looks like the answer you are after.
The key to solving this problem is to write a recursive function that iterates through the XML tree, writing the various elements and attributes to specially created XmlWriter objects. There is an 'outer' XmlWriter object that writes indented XML, and an 'inner' XmlWriter object that writes non-indented XML.
The recursive function initially uses the 'outer' XmlWriter, writing indented XML, until it sees the TextBlock element. When it encounters the TextBlock element, it creates the 'inner' XmlWriter object, writing the child elements of the TextBlock element to it. It also writes white space to the 'inner' XmlWriter.
When the 'inner' XmlWriter object is finished with writing the TextBlock element, the text that the writer wrote is written to the 'outer' XmlWriter using the WriteRaw method.