Search code examples
c#.netxmlxelement

Add blank lines to XElement preserving other formatting


I have an XElement that I constructed in code. It has (conceptually) 2 groups of nodes. If I just print it out, I get a nicely formatted Xml file, but with all the nodes together. If I add a couple of newlines between the 2 groups for easier human comprehension, I lose all the formatting following it. How can I add a small break between the 2 groups, and still keep the rest of the formatting?

Example:
This is the default:

<root>
  <node>1.1</node>
  <node>1.2</node>
  <node>2.1</node>
  <node>2.2</node>
</root>

This is if I add the break:

<root>
  <node>1.1</node>
  <node>1.2</node>

<node>2.1</node><node>2.2</node></root>

This is what I want:

<root>
  <node>1.1</node>
  <node>1.2</node>

  <node>2.1</node>
  <node>2.2</node>
</root>

Solution

  • Check out the solution posted here. I have the impression it's not possible with a clean solution. I tried several ways, to no avail. I also looked into the System.Linq.Xml source code, but can't really find why it does this.

    Another option is to do the ToString first, and then to add the newlines after that (with a replace, if you know which nodes need the newline):

    result = result.Replace("<parentNode>", Environment.NewLine + "<parentNode>");
    

    But that will probably muck up your indenting again.