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.