How to indent after a line in an xml element when using an XmlTextWriter?

I am trying to backtrack after a new line when using 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()); } 
+4
source share
2 answers

The indent indicated in the entry is the indent between elements where there are no significant spaces. The space you want to create is signified, because it is part of the text value between the open and close tags.

If the writer had to do this with plain xml, he would modify the text content in an unacceptable way. You need to do it yourself.

+6
source

Your code does what you tell him, I'm afraid.

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

If you need indentation, you will have to write this in your code, for example

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

The problem with this approach is that if your <element> already indented, it will ruin the indent - your 'a' will still be indented with only one tab.

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

 <element>a</element> 

This is definitely understandable, but it may seem strange when "a" becomes a very long text.

+1
source

All Articles