title: How do I control the <?xml ?> part of xml serialization with .NET?
body: <p>I am using this method to serialize my object:</p>
  
  <pre><code>public static string XmlSerialize(object o)
  {
      var stringWriter = new StringWriter();
      var xmlSerializer = new XmlSerializer(o.GetType());
      xmlSerializer.Serialize(stringWriter, o);
      string xml = stringWriter.ToString();
      stringWriter.Close();
      return xml;
  }
  </code></pre>
  
  <p>It makes XML that starts like this:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-16"?&gt;
  &lt;MyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  </code></pre>
  
  <p>But I want it to look like this:</p>
  
  <pre><code>&lt;?xml version = "1.0" encoding="Windows-1252" standalone="yes"?&gt;
  &lt;MyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
  </code></pre>
  
  <p>So, how do I change the encoding to Windows-1252 and set standalone = yes?
  Additionally, how to I get the object to exclude the xmlns value?</p>
  
  <p>I've seen a couple similar questions, like <a href="https://stackoverflow.com/questions/933664/net-xml-serialization-without-xml-root-node">this one</a>, but I was hoping it might be simpler for me, maybe by setting some attributes somewhere?</p>
  
  <p>Update 2: After looking at John's answer and comments, and thinking about this more, I decided to just make a second method. I don't think that creating this wacky custom xml just for a 3rd party on one occasion should be called something as generic as "XmlSerialize" in the first place.</p>
  
  <p>So, I created a second method that takes an XML document and first, removes the one namespace element like this:</p>
  
  <pre><code>xElement.Attributes().Where(a =&gt; a.IsNamespaceDeclaration &amp;&amp; a.Value == "http://www.w3.org/2001/XMLSchema").Remove();
  </code></pre>
  
  <p>then, it it writes it to XML with John's code. Finally it returns that xml, following the output from this:</p>
  
  <pre><code>new XDeclaration("1.0", "Windows-1252", "yes").ToString()
  </code></pre>
  
  <p>And that's ugly, but it gets me exactly what I need for this 3rd party to understand my XML.</p>