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">
</column>

      

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

<column name="Name"/>

      

xml is generated using FluentNHibernate config

Fluently.Configure(configuration)
    .Mappings(
          m=>m.FluentMappings
              .Add(...)
              .ExportTo("myXmlFile"))
    .BuildSessionFactory();

      

The column node is created for

Map(x=>x.Name);

      

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)?

+3


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">
</column>

      

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)
{
    element.RemoveNodes();
}

xml = document.ToString();

      

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

null

where it was in this case ""

. The end result is this:

<column name="Name" />

      

+1


source







All Articles