Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XmlDocument incorrectly serializes elements with an empty-string child text node when pretty-printing #41574

Open
mklement0 opened this issue Oct 5, 2019 · 0 comments

Comments

@mklement0
Copy link
Collaborator

commented Oct 5, 2019

System.Xml.XmlDocument - unlike System.Xml.Linq.XDocument - incorrectly serializes an element that has an empty-string child text node when producing pretty-printed output.

(The idea behind creating an empty-string child text node - as opposed to using a truly empty (childless) element - is to force serialization of such an element in the <tag></tag> form, as opposed to in the self-closing empty-tag form (<tag />).
For a real-world scenario and manifestation of this bug, see this StackOverflow question.)

Steps to reproduce:

using System;
using System.Xml;
using System.IO;

public static class Program
{
  public static void Main()
  {

    var xd = new XmlDocument();
    xd.LoadXml("<root><Elem/></root>");

    // Add an empty-string child text node to <Elem>
    xd.DocumentElement.FirstChild.InnerText = "";
    
    xd.Save("t.xml");

    Console.WriteLine(File.ReadAllText("t.xml"));
 }

}

Expected output:

<root>
  <Elem></Elem>
</root>

That is, the element should serialize in the <tag>...</tag> form, with the empty string as the (implied) inner text.

Actual output:

<root>
  <Elem>
  </Elem>
</root>

That is, the element unexpectedly serialized across two lines, which introduced extraneous whitespace as the value of the <Elem> element (the value of its child text node).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants
You can’t perform that action at this time.