The following code produces this output:
This is not a bug in .NET. This is due to you using StringWriter
as the target for your XDocument. Since StringWriter internally uses UTF-16, the document must also use UTF-16 as encoding. If you save the XDoc to a stream or a file, it will use UTF-8 as instructed.
For more information, see MSDN information about StringWriter.Encoding:
This property is necessary for some XML scenarios where a header must be written containing the encoding used by the StringWriter. This allows the XML code to consume an arbitrary StringWriter and generate the correct XML header.
Allow me answer my own question, this seems to work:
private static string BuildXmlWithLINQ()
{
XDocument xdoc = new XDocument
(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("customers",
new XElement("customer",
new XElement("firstName", "Jim"),
new XElement("lastName", "Smith")
)
)
);
return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();
}
You can use the following code as an example
XDocument doc = GetXmlDoc();
using (var stream = new MemoryStream())
{
doc.Save(stream, SaveOptions.DisableFormatting);
var docBytes = stream.ToArray();
File.WriteAllBytes("fileName.xml", docBytes);
}