I need to create a readable XML file. XmlWriter seems almost perfect for this, but I would like to insert line breaks or, in general, custom spaces where I want them. Neither WriteRaw nor WriteWhitespace seem to work between attributes in an element. The latter looks like it should work (this method is used to manually format your document), but throws InvalidOperationException(Token StartAttribute in the Element Content state will result in an invalid XML document) if it is used instead of the comments below.
Is there a workaround for XmlWriter or a third-party XML library that supports this?
Sample code (LINQPad ready-made instructions):
var sb = new StringBuilder();
var settings = new XmlWriterSettings {
OmitXmlDeclaration = true,
Indent = true,
IndentChars = " ",
};
using (var writer = XmlWriter.Create(sb, settings)) {
writer.WriteStartElement("X");
writer.WriteAttributeString("A", "1");
writer.WriteAttributeString("B", "2");
writer.WriteAttributeString("C", "3");
writer.WriteEndElement();
}
Console.WriteLine(sb.ToString());
Actual result:
<X A="1" B="2" C="3" />
(B C A - , /" > C):
<X A="1"
B="2"
C="3"
/>