Preserve xml formatting using XmlDocument

2019-04-12 08:01发布

问题:

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>

回答1:

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.



回答2:

Umm. I'm seeing whitespace being preserved when using PreserveWhiteSpace=true. Perhaps it was false when you loaded?

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

  <element></element>

</root>";

var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(xmlStr);
xmlDoc.Save(Console.Out);

Shows:

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

  <element></element>

</root> 


回答3:

use preservewhitespace before you load. It will keep formatting same

like above
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(xmlStr);

if you will use it after loading. it will kill white spaces in between