How to make xml nodes open and closed on the same line if they have no children?

I am working with a large XML file and want to cut it down a bit. I currently have many examples of something like this:

<column name="Name">


Since the column has no child nodes, I would like it to be

<column name="Name"/>


xml is generated using FluentNHibernate config



The column node is created for



in my ClassMap.

Is there any way I can use the System.Xml classes to rewrite it to write one line for each childless node)?


source to share

1 answer

As you probably cannot change the way the XML is generated, you can load it in XDocument

and make the necessary changes. By default it will load with no spaces - this will overwrite this:

<column name="Name">


like this:

<column name="Name"></column>


This is because he sees that he matters ""

. To get rid of this, you need to clear the contents of those that have an empty string as their value.

string xml = "..."

var document = XDocument.Parse(xml);

var emptyElements = document.Descendants()
    .Where(e => !e.Nodes().Any());

foreach (var element in emptyElements)

xml = document.ToString();


The code looks odd (what nodes are we removing from an element without nodes ?!), but it makes an internal margin content


where it was in this case ""

. The end result is this:

<column name="Name" />




All Articles