title: How can I force XDocument to output "UTF-8" in the declaration line?
body: <p>The following code produces this output:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-16" standalone="yes"?&gt;
  &lt;customers&gt;
    &lt;customer&gt;
      &lt;firstName&gt;Jim&lt;/firstName&gt;
      &lt;lastName&gt;Smith&lt;/lastName&gt;
    &lt;/customer&gt;
  &lt;/customers&gt;
  </code></pre>
  
  <p><strong>How can I get it to produce <code>encoding="utf-8"</code> instead of <code>encoding="utf-16"</code>?</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Xml.Linq;
  
  namespace test_xml2
  {
      class Program
      {
          static void Main(string[] args)
          {
              List&lt;Customer&gt; customers = new List&lt;Customer&gt; {
                  new Customer {FirstName="Jim", LastName="Smith", Age=27},
                  new Customer {FirstName="Hank", LastName="Moore", Age=28},
                  new Customer {FirstName="Jay", LastName="Smythe", Age=44},
                  new Customer {FirstName="Angie", LastName="Thompson", Age=25},
                  new Customer {FirstName="Sarah", LastName="Conners", Age=66}
              };
  
              Console.WriteLine(BuildXmlWithLINQ(customers));
  
              Console.ReadLine();
  
          }
          private static string BuildXmlWithLINQ(List&lt;Customer&gt; customers)
          {
              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")
                          )
                      )
                  );
  
              var wr = new StringWriter();
              xdoc.Save(wr);
  
              return wr.GetStringBuilder().ToString();
          }
      }
  
      public class Customer
      {
          public string FirstName { get; set; }
          public string LastName { get; set; }
          public int Age { get; set; }
  
          public string Display()
          {
              return String.Format("{0}, {1} ({2})", LastName, FirstName, Age);
          }
      }
  }
  </code></pre>