Is there any way to save an XmlDocument *without* indentation and line returns?

柔情痞子 提交于 2021-02-07 05:16:04

问题


All my searches have brought up people asking the opposite, but I have a file which grows by nearly 50% if it is saved with line returns and indentation.

Is there any way round this?

EDIT I'm not talking about opening a file, but saving one. This code reproduces the 'bug' for me:

var path = @"C:\test.xml";
System.IO.File.WriteAllText(path, "<root>\r\n\t<line></line>\r\n\t<line></line>\r\n</root>");
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.PreserveWhitespace = false;
doc.Load(path);
doc.PreserveWhitespace = false; //just in case!
doc.Save(path);

A breakpoint in the middle shows that doc.InnerXml is effectively <root><line></line><line></line></root>, as expected. But the contents of test.xml at the end is:

<root>
  <line>
  </line>
  <line>
  </line>
</root>

回答1:


Try this code:

XmlDocument doc = new XmlDocument();

using(XmlTextWriter wr = new XmlTextWriter(fileName, Encoding.UTF8))
{
    wr.Formatting = Formatting.None; // here's the trick !
    doc.Save(wr);
}



回答2:


Use XmlWriterSettings:

XmlDocument xmlDoc = new XmlDocument();
[...]
XmlWriterSettings xwsSettings = new XmlWriterSettings();
xwsSettings.Indent = false;
xwsSettings.NewLineChars = String.Empty;
using (XmlWriter xwWriter = XmlWriter.Create(@"c:\test.xml", xwsSettings))
 xmlDoc.Save(xwWriter);


来源:https://stackoverflow.com/questions/4724940/is-there-any-way-to-save-an-xmldocument-without-indentation-and-line-returns

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