How to print <?xml version="1.0"?> using XDocument

This is by far the best way and most managable:

var xdoc = new XDocument(new XElement("Root", new XElement("Child", "台北 Táiběi.")));

string mystring;

using(var sw = new MemoryStream())
{
    using(var strw = new StreamWriter(sw, System.Text.UTF8Encoding.UTF8))
    {
         xdoc.Save(strw);
         mystring = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray());
    }
}

and i say that just because you can change encoding to anything by changing .UTF8 to .Unicode or .UTF32


By using XDeclaration. This will add the declaration.

But with ToString() you will not get the desired output.

You need to use XDocument.Save() with one of his methods.

Full sample:

var doc = new XDocument(
        new XDeclaration("1.0", "utf-16", "yes"), 
        new XElement("blah", "blih"));

var wr = new StringWriter();
doc.Save(wr);
Console.Write(wr.ToString());