我正在使用XDocument生成utf-8 XML文件。

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文件进行了验证。

当我尝试将XML文件上传到在线服务时,该服务说我的文件是wrong at line 1;我发现问题是由文件的第一个字节上的BOM引起的。

您知道为什么将BOM附加到文件中,并且如何在没有文件的情况下保存文件?

Byte order mark维基百科文章所述:



XDocument问题,还是应该联系在线服务提供商的人员要求解析器升级?

最佳答案

使用XmlTextWriter并将其传递给XDocument的Save()方法,这样您就可以更好地控制所使用的编码类型:

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类的构造函数具有一个重载,该重载指定是否使用带 bool 值的BOM(字节顺序标记)(在您的情况下为false)。

使用Notepad++验证了此代码的结果,以检查文件的编码。

关于c# - XDocument : saving XML to file without BOM,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4942825/

10-12 03:02