Search code examples
c#formattingxmldocument

Preserve xml formatting using XmlDocument


I am using XmlDocument to work with xml

How do I save my "XmlDocument" with my current formatting?

Current formatting:

<?xml version="1.0" encoding="utf-8"?>
<root>

  <element></element>

</root>

Code:

                XmlDocument testDoc = new XmlDocument();
                testDoc.Load(@"C:\Test.xml");

                **(do reading/writing using only XmlDocument methods)**

                testDoc.Save(@"C:\Test.xml");

There is a similar topic: XmlDocument class is removing formatting, c#, .NET

The accepted answer is PreserveWhiteSpace = true, which in reality removes all whitespaces instead of preserving them.

Example:

Code:

    XmlDocument testDoc = new XmlDocument();
    testDoc.Load(@"C:\Test.xml");
    testDoc.PreserveWhitespace = true;
    testDoc.Save(@"C:\Test.xml");

Result:

<?xml version="1.0" encoding="utf-8"?><root><element></element></root>

Solution

  • Setting PreserveWhitespace to true works for me - but you've got to do it before loading so that the whitespace doesn't get thrown away at load time:

    using System;
    using System.Xml;
    
    class Test
    {
        static void Main() 
        {
            XmlDocument testDoc = new XmlDocument();
            testDoc.PreserveWhitespace = true;
            testDoc.Load("Test.xml");
            testDoc.Save("Output.xml");
        }
    }
    

    I've just tried that, and the whitespace was preserved.