使用XmlDocument保留xml格式

And*_*rey 3 c# formatting xmldocument

我正在使用XmlDocument来处理xml

如何使用当前格式保存"XmlDocument"?

当前格式:

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

  <element></element>

</root>
Run Code Online (Sandbox Code Playgroud)

码:

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

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

                testDoc.Save(@"C:\Test.xml");
Run Code Online (Sandbox Code Playgroud)

有一个类似的主题: XmlDocument类正在删除格式,c#,.NET

接受的答案是PreserveWhiteSpace = true,实际上删除了所有空格而不是保留它们.

例:

码:

    XmlDocument testDoc = new XmlDocument();
    testDoc.Load(@"C:\Test.xml");
    testDoc.PreserveWhitespace = true;
    testDoc.Save(@"C:\Test.xml");
Run Code Online (Sandbox Code Playgroud)

结果:

<?xml version="1.0" encoding="utf-8"?><root><element></element></root>
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 13

设置PreserveWhitespace为true对我有用 - 但是你必须在加载之前这样做,以便在加载时不会抛弃空格:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我刚刚尝试过,并保留了空白.

  • 请注意,"PreserveWhitespace"仅保留元素缩进.如果您有新行或多行值的属性,则会重新格式化它们. (7认同)
  • 非常感谢,我在加载后保存它们 (2认同)