views:

839

answers:

2

I am trying to indent after a newline when using an XmlTextWriter

So essentially i want this

<?xml version="1.0" encoding="utf-16"?>
<element>
  a
</element>

but using the code below i get this

<?xml version="1.0" encoding="utf-16"?>
<element>
a
</element>

Here is my current test harness

[Test]
public void XmlIndentingTest()
{
    var provider = new StringBuilder();
    var settings = new XmlWriterSettings
                       {
                           Indent = true,
                           IndentChars = "  ",
                       };
    using (var writer = new StringWriter(provider))
    {
        using (var xmlWriter = XmlTextWriter.Create(writer, settings))
        {
            xmlWriter.WriteStartElement("element");
            xmlWriter.WriteString("\r\na\r\n");
            xmlWriter.WriteEndElement();
        }
    }
    Debug.WriteLine(provider.ToString());
}
+5  A: 

The indentation specified in the writer is for indentation between elements where there is no significant whitespace. The whitespace you want to create is siginficant because it forms part of the text value between the opening and closing tags.

If the writer were to do that to normal xml it would be modifying the text content in unacceptable way. You need to do this yourself.

AnthonyWJones
Thanks anthony. This is waht i expected. I was hoping there was some automated way.
Simon
A: 

Your code doesexactly what you tell it to do, I'm afraid.

xmlWriter.WriteStartElement("element"); //<element>
xmlWriter.WriteString("\r\na\r\n");     //newline, directly followed by 'a'
xmlWriter.WriteEndElement();            //</element>

If you want an indentation, you will have to write this in your code, like

xmlWriter.WriteString("\r\n\ta\r\n");

The problem with that approach is that if your <element> is already indented, it will mess up the indentation - your 'a' would still be indented exactly one tab.

So you can either calculate the indentation yourself somehow, and write the appropriate number of tabs, or you go with the whole element in one line

<element>a</element>

This is definitely clearer, but it may look strange when 'a' becomes a very long text.

Treb