【问题标题】:Is there any way to save an XmlDocument *without* indentation and line returns?有没有办法保存 XmlDocument * without * 缩进和换行?
【发布时间】:2011-01-18 14:01:14
【问题描述】:

我所有的搜索都提出了相反的问题,但我有一个文件,如果它与换行符和缩进一起保存,它会增长近 50%。

有没有办法解决这个问题?

编辑我说的不是打开一个文件,而是保存一个文件。此代码为我重现了“错误”:

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);

中间的断点表明 doc.InnerXml 实际上是 &lt;root&gt;&lt;line&gt;&lt;/line&gt;&lt;line&gt;&lt;/line&gt;&lt;/root&gt;,正如预期的那样。但是最后test.xml的内容是:

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

【问题讨论】:

标签: c# .net xmldocument


【解决方案1】:

试试这个代码:

XmlDocument doc = new XmlDocument();

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

【讨论】:

  • 哇,它保留了&lt;![CDATA[...]]&gt; 块中的新行!谢谢
  • 谢谢!我目前正在 Trados 2014 (*.sdlxliff) 文件中提取和导入数据,如果我在不删除 xml 格式的情况下保存它们,它们就会中断。
【解决方案2】:

使用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);

【讨论】:

  • 请注意,这也会从 &lt;![CDATA[..]]&gt; 块中删除新行(但不是多余的空格)。
猜你喜欢
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多