使用XmlDocument保留xml格式 [英] Preserve xml formatting using XmlDocument

查看:175
本文介绍了使用XmlDocument保留xml格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XmlDocument来处理XML



如何保存XmlDocument与我目前的格式?



当前格式:

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

< element>< / element>

< / root>

代码:

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

**(仅使用XmlDocument方法进行读/写)**

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

有一个相似的主题:



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



示例:

代码:

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

结果:

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


解决方案

设置 PreserveWhitespace 真正适用于我 - 但是你必须在加载之前这样做,以便在加载时空白不会被扔掉:

 使用System; 
使用System.Xml;
$ b class Test b $ b {
static void Main()
{
XmlDocument testDoc = new XmlDocument();
testDoc.PreserveWhitespace = true;
testDoc.Load(Test.xml);
testDoc.Save(Output.xml);




$ b我已经试过了,保存。


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>

解决方案

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.

这篇关于使用XmlDocument保留xml格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆