15

I'm loading a XML Document that has some tags that have no innertext.

If I populate the innertext with some data then it works as needed (you get opening tag, innertext and closing tag all on one line) like the following...

<root>
  <element>value</element>
</root>

The problem arises with tags with no values. These SHOULD be displayed in the same way as above with the exception of no value of coarse, like the following...

<root>
  <element></element>
</root>

However, when the innertext has an empty string it adds a carriage return & line feed which is not what is expected! It ends up looking like the following...

<root>
  <element>
  </element>
</root>

This is my current code that yields the above results...

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\test.xml");

//Save the xml and then cleanup
xmlDoc.Save(@"C:\test.xml");
Arvo Bowen
  • 4,524
  • 6
  • 51
  • 109

3 Answers3

25

This fixed it for me...

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\test.xml");

//Save the xml and then cleanup
XmlWriterSettings settings = new XmlWriterSettings { Indent = true };
XmlWriter writer = XmlWriter.Create(@"C:\test.xml", settings);
xmlDoc.Save(writer);
Arvo Bowen
  • 4,524
  • 6
  • 51
  • 109
  • 1
    I don't understand why this works and the XmlDocument PreserveWhiteSpace keeps failing me, but it solved my problem. – Brian J Feb 12 '14 at 16:29
  • This helped us with an issue we were having causing a database not to build correctly from a modified xml output. The issue was the new lines generated from the 'XmlDocument.Save()' method on empty elements. Thanks! – Tim Sexton Nov 22 '16 at 19:50
2

You control that through the XMLWriter within the Settings Property.

Check out this example along with the following references. http://msdn.microsoft.com/en-us/library/ms162618.aspx

Refernces http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.newlinehandling.aspx

jcwrequests
  • 1,132
  • 1
  • 7
  • 13
  • Thanks, yea I found my answer as soon as I posted this question. I submitted the exact code to help others out if they run into the same situation. Thanks for the answer! – Arvo Bowen Oct 08 '13 at 21:55
1

Probably too late, but I referred to the solution given by Arvo Bowen. Arvo's solution is in C#, I wrote the same in Powershell Syntax

# $dest_file is the path to the destination file
$xml_dest = [XML] (Get-Content $dest_file)

#
#   Operations done on $xml_dest
#

$settings = new-object System.Xml.XmlWriterSettings
$settings.CloseOutput = $true
$settings.Indent = $true
$writer = [System.Xml.XmlWriter]::Create($dest_file, $settings)

$xml_dest.Save($writer)
$writer.Close()

It solved my two problems:

Community
  • 1
  • 1
Suveer Jacob
  • 893
  • 7
  • 11