有什么方法可以保存 XmlDocument *没有*缩进和换行吗?

发布于 2024-10-12 17:43:15 字数 758 浏览 4 评论 0原文

我所有的搜索都带来了相反的问题,但我有一个文件,如果使用换行符和缩进保存,它会增长近 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 实际上是 ,如预期。但最后的test.xml内容是:

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

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

几度春秋 2024-10-19 17:43:15

试试这个代码:

XmlDocument doc = new XmlDocument();

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

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);
}
聽兲甴掵 2024-10-19 17:43:15

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文