的XDocument:保存XML无BOM到文件 [英] XDocument: saving XML to file without BOM

查看:408
本文介绍了的XDocument:保存XML无BOM到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我产生的 UTF-8 XML 的文件中使用的XDocument

I'm generating an utf-8 XML file using XDocument.

XDocument xml_document = new XDocument(
                    new XDeclaration("1.0", "utf-8", null),
                    new XElement(ROOT_NAME,                    
                    new XAttribute("note", note)
                )
            );
...
xml_document.Save(@file_path);

正确生成文件,并成功XSD文件进行验证。

The file is generated correctly and validated with an xsd file with success.

当我尝试将XML文件上传到在线服务,该服务说,我的文件是错在第1行;我们已经发现,该问题是由BOM上的文件的第一个字节而引起的。

When I try to upload the XML file to an online service, the service says that my file is wrong at line 1; I have discovered that the problem is caused by the BOM on the first bytes of the file.

你知道为什么的BOM附加到文件,我怎么能保存文件没有它?

Do you know why the BOM is appended to the file and how can I save the file without it?

字节顺序标记表示维基百科的文章:

虽然统一code标准允许在BOM
  UTF-8的不需要或
  推荐它
。字节顺序没有
  在UTF-8这样一个BOM只意
  用于识别一个文本流或
  文件为UTF-8,或者将其转化
  从具有BOM另一种格式

While Unicode standard allows BOM in UTF-8 it does not require or recommend it. Byte order has no meaning in UTF-8 so a BOM only serves to identify a text stream or file as UTF-8 or that it was converted from another format that has a BOM

它是一个的XDocument 问题,或者我应该联系在线服务提供商的家伙,要求解析器升级?

Is it an XDocument problem or should I contact the guys of the online service provider to ask for a parser upgrade?

推荐答案

使用的的XmlTextWriter 并传递到的XDocument的Save()方法,这样你可以有更多的

Use an XmlTextWriter and pass that to the XDocument's Save() method, that way you can have more control over the type of encoding used:

var doc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement("root", new XAttribute("note", "boogers"))
);
using (var writer = new XmlTextWriter(".\\boogers.xml", new UTF8Encoding(false)))
{
    doc.Save(writer);
}

UTF8Encoding 类的构造函数有指定是否与一个布尔值,用BOM(字节顺序标记),你的情况假。

The UTF8Encoding class constructor has an overload that specifies whether or not to use the BOM (Byte Order Mark) with a boolean value, in your case false.

这code的结果是用记事本+ +来检查文件的编码进行验证。

The result of this code was verified using Notepad++ to inspect the file's encoding.

这篇关于的XDocument:保存XML无BOM到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆