XmlWriterSettings, XmlTextWriter, XmlWriter not formatting output?! No new lines, no indentation
Using .Net 3.5 SP1 in VS2008 I have a XmlDocument and have tried writing it to file:
using (XmlTextWriter tw = new XmlTextWriter(outXmlFileName, System.Text.Encoding.UTF8))
{
tw.Formatting = Formatting.Indented;
tw.Indentation = 3;
tw.IndentChar = ' ';
tw.QuoteChar = '\'';
doc.Save(tw);
}
And
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Cre开发者_如何转开发ate(outXmlFileName, settings))
{
doc.Save(writer);
}
What is unclear from the documentation, http://msdn.microsoft.com/en-us/library/kkz7cs0d.aspx, is if I should be using XmlWriter.Create() above .Net 2, anyway either way neither methods format the output! I just get what is in the XmlDocument instance:
<?xml version='1.0' encoding='utf-8'?>
<root>
<node1 />
<node2 value='Data' />
<node3 value='ID' /><node4><item>
<from value='1 Jan 1870' />
<id value='PF' />
<to value='1 Jan 1940' /></item></node4>
</root>
How can I tidy my XML before writing it file from .Net?!
I got it to work by loading the XML into an 2nd intermediary XmlDocument instance so it forgot the original white space:
XmlWriterSettings settings = new XmlWriterSettings(); // http://msdn.microsoft.com/en-us/library/kkz7cs0d(VS.85).aspx
settings.Indent = true;
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(doc.OuterXml);
using (XmlWriter writer = XmlWriter.Create(outXmlFileName, settings))
{
doc2.Save(writer);
}
精彩评论