Preserve xml formatting using XmlDocument

不羁的心 提交于 2019-12-04 12:40:41

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.

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> 
abhishek

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!