I've found a much more elegant way of doing this: simply call WriteStartDocument(true)
on your XmlWriter
instance - this code serializes data
and outputs the resulting XML to console.
First, if you're using a StringWriter
you need to tweak it a bit to force UTF-8, but keep this in mind:
When serialising an XML document to a .NET string, the encoding must be set to UTF-16. Strings are stored as UTF-16 internally, so this is the only encoding that makes sense. If you want to store data in a different encoding, you use a byte array instead.
public sealed class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
using (var sw = new Utf8StringWriter())
using (var xw= XmlWriter.Create(sw, new XmlWriterSettings{Indent = true}))
{
xw.WriteStartDocument(true); // that bool parameter is called "standalone"
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
var xmlSerializer = new XmlSerializer(typeof(data));
xmlSerializer.Serialize(xw, data);
Console.WriteLine(sw.ToString());
}
WriteStartDocument(true)
really feels like the idiomatic way of specifying standalone=true
. The output heading looks like this:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>