Preserve xml formatting using XmlDocument

2019-04-12 07:47发布

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>

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-12 08:05

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.

查看更多
倾城 Initia
3楼-- · 2019-04-12 08:17

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> 
查看更多
疯言疯语
4楼-- · 2019-04-12 08:26

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

查看更多
登录 后发表回答