XDocument和BOM(字节顺序标记)的问题

Joh*_*han 5 .net xml linq-to-xml

有没有办法在没有BOM的情况下输出XDocument的内容?使用Flash读取输出时,会导致错误.

Chr*_*ham 9

如果您使用XmlWriter编写XML,则可以将编码设置为已初始化的编码以省略BOM.

EG:System.Text.UTF8Encoding的构造函数采用布尔值来指定是否需要BOM,因此:

XmlWriter writer = XmlWriter.Create("foo.xml");
writer.Settings.Encoding = new System.Text.UTF8Encoding(false);
myXDocument.WriteTo(writer);
Run Code Online (Sandbox Code Playgroud)

将使用UTF-8编码创建一个XmlWriter,而不使用字节顺序标记.


小智 5

对Chris Wenham的回答略有不同.

创建XmlWriter后无法修改编码,但可以在创建XmlWriter时使用XmlWriterSettings对其进行设置

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new System.Text.UTF8Encoding(false); 

XmlWriter writer = XmlWriter.Create("foo.xml", settings); 
myXDocument.WriteTo(writer); 
Run Code Online (Sandbox Code Playgroud)