简体   繁体   English

XDocument如何在不使用字节顺序标记和预设格式/空白的情况下进行保存

[英]XDocument how to save without Byte Order Mark AND preseve formatting/whitespace

I am able to remove the Byte Order Mark using this code: 我可以使用以下代码删除字节顺序标记:

using (var writer = new XmlTextWriter(file, new UTF8Encoding(false)))
{
    writer.Formatting = Formatting.None;
    xdoc.Save(writer);
}

The problem with this though is that my formatting becomes messed up and all the whitespace is removed. 但是,问题是我的格式变得混乱,所有空白都被删除了。 For example: 例如:

<root>
  <data name="A" xml:space="preserve">
    <value>A</value>
  </data>
</root>

Now becomes: 现在变成:

<root><data name="A" xml:space="preserve">
    <value>A</value>
</data></root>

Is there any way to remove this byte order mark and keep the original formatting of the file? 有什么方法可以删除此字节顺序标记并保持文件的原始格式?

Problem solved (Updated due to issue with creating unnecessary whitespace): 已解决的问题(由于创建不必要的空格的问题而更新):

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = new UTF8Encoding(false);
using (var writer = XmlWriter.Create(file, settings))
{
     xdoc.Save(writer);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM