I came across the same question. In the end, I went out with the usual author:
public class IndentTextXmlWriter : XmlTextWriter { private int indentLevel; private bool isInsideAttribute; public IndentTextXmlWriter(TextWriter textWriter): base(textWriter) { } public bool IndentText { get; set; } public override void WriteStartAttribute(string prefix, string localName, string ns) { isInsideAttribute = true; base.WriteStartAttribute(prefix, localName, ns); } public override void WriteEndAttribute() { isInsideAttribute = false; base.WriteEndAttribute(); } public override void WriteStartElement(string prefix, string localName, string ns) { indentLevel++; base.WriteStartElement(prefix, localName, ns); } public override void WriteEndElement() { indentLevel--; base.WriteEndElement(); } public override void WriteString(string text) { if (String.IsNullOrEmpty(text) || isInsideAttribute || Formatting != Formatting.Indented || !IndentText || XmlSpace == XmlSpace.Preserve) { base.WriteString(text); return; } string[] lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); string indent = new string(IndentChar, indentLevel * Indentation); foreach (string line in lines) { WriteRaw(Environment.NewLine); WriteRaw(indent); WriteRaw(line.Trim()); } WriteRaw(Environment.NewLine); WriteRaw(new string(IndentChar, (indentLevel - 1) * Indentation)); } }
You can use it as follows:
[TestMethod] public void WriteIndentedText() { var result = new StringBuilder(); using (var writer = new IndentTextXmlWriter(new StringWriter(result)){Formatting = Formatting.Indented, IndentText = true}) { string text = @" Line 1 Line 2 Line 3 ";
And the conclusion:
<?xml version="1.0" encoding="utf-16"?> <root> <child> <elementIndented> Line 1 Line 2 Line 3 </elementIndented> <elementPreserved xml:space="preserve"> Line 1 Line 2 Line 3 </elementPreserved> </child> </root>
source share