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:I've just tried that, and the whitespace was preserved.
Umm. I'm seeing whitespace being preserved when using
PreserveWhiteSpace=true
. Perhaps it wasfalse
when you loaded?Shows:
use preservewhitespace before you load. It will keep formatting same
if you will use it after loading. it will kill white spaces in between