Upon testing code that creates a XML document, I saw that after a string that ends with a linebreak is being written, the WriteEndElement
on the next line is not indented at all. The WriteStartElement
after that is correctly indented.
I tried all three settings for NewLineHandling
without a change. The element can not contain the CDATA
annotation as the target system wouldn't know what to do with that.
My code:
using System;
using System.Xml;
using System.Text;
using System.IO;
public class Program
{
public static void Main()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Async = false;
settings.CloseOutput = false;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Encoding = Encoding.UTF8; // Encoding.GetEncoding(28605);
settings.Indent = true;
settings.IndentChars = " ";
settings.NamespaceHandling = NamespaceHandling.Default;
settings.NewLineChars = Environment.NewLine;
settings.NewLineHandling = NewLineHandling.Entitize;
settings.NewLineOnAttributes = false;
settings.OmitXmlDeclaration = false;
settings.WriteEndDocumentOnClose = false;
using (MemoryStream ms = new MemoryStream())
{
using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("RootNode");
xmlWriter.WriteStartElement("subnode");
xmlWriter.WriteString("12\r\n354\r\n");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("guid");
xmlWriter.WriteString(Guid.NewGuid().ToString("D"));
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
}
ms.Flush();
ms.Position = 0;
using (StreamReader reader = new StreamReader(ms))
{
Console.Write(reader.ReadToEnd());
}
}
}
}
Expected output:
<?xml version="1.0" encoding="utf-8"?>
<RootNode>
<subnode>12
354
</subnode>
<guid>5c712399-c7b3-45e1-be3d-d5f6718e07b9</guid>
</RootNode>
Output I get:
<?xml version="1.0" encoding="utf-8"?>
<RootNode>
<subnode>12
354
</subnode>
<guid>6ffbd53c-6b9d-482c-b006-ca5f6d40293d</guid>
</RootNode>
As you can see, the </subnode>
tag is not properly aligned and no matter what I try, it keeps looking like that. To repeat: Even if I set NewLineHandling to Entitize
the </subnode>
tag is not indented correctly - which I don't understand.
This happens for .NET 4.5.2 and .NET 4.7.2.