XDocument: saving XML to file without BOM

后端 未结 3 1266
眼角桃花
眼角桃花 2020-11-27 19:43

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

XDocument xml_document = new XDocument(
                    new XDeclaration(\"1.0\"         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 19:58

    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);
    }
    

    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.

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

提交回复
热议问题