Skip to content

XDocument/XmlWriter: Whitespace not preserved with xml:space="preserve" when writing with settings option Indent = true #112343

@SetTrend

Description

@SetTrend

Description

When saving an XDocument, whitespace is not preserved for XElement elements declared with xml:space="preserve".

Reproduction Steps

using System;
using System.Xml.Linq;

namespace WhitespaceTest
{
  internal class Program
  {
    static void Main()
    {
      XElement root;

      XDocument xDoc = new XDocument(
        root = new XElement("outer"
          )
        );

      root.Add(
        new XElement("middle",
          new XAttribute(XNamespace.Xml + "space", "preserve"),
          new XElement("inner"
            )
          )
        );

      Console.Write(xDoc.ToString(SaveOptions.OmitDuplicateNamespaces));
      Console.ReadKey(true);
    }
  }
}

Expected behavior

There should be no whitespace output between <middle> and </middle>, because <middle> is declared with xml:space="preserve" and there is no whitespace in the in-memory object tree.

<outer>
  <middle xml:space="preserve"><inner /></middle>
</outer>

Actual behavior

Whitespace is added between <middle/> and <middle/>:

<outer>
  <middle xml:space="preserve">
    <inner />
  </middle>
</outer>

Configuration

.NET 9.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions