title: How to solve "unable to switch the encoding" error when inserting XML into SQL Server
body: <p>I'm trying to insert into XML column (SQL SERVER 2008 R2), but the server's complaining:</p>
  
  <blockquote>
    <p>System.Data.SqlClient.SqlException (0x80131904):<br>
    XML parsing: line 1, character 39, unable to switch the encoding</p>
  </blockquote>
  
  <p>I found out that the XML column has to be UTF-16 in order for the insert to succeed.</p>
  
  <p>The code I'm using is:</p>
  
  <pre><code> XmlSerializer serializer = new XmlSerializer(typeof(MyMessage));
   StringWriter str = new StringWriter();
   serializer.Serialize(str, message);
   string messageToLog = str.ToString();
  </code></pre>
  
  <p>How can I serialize object to be in UTF-8 string?</p>
  
  <p><em>EDIT</em>: Ok, sorry for the mixup - the string needs to be in UTF-8. You were right - it's UTF-16 by default, and if I try to insert in UTF-8 it passes. So the question is how to serialize into UTF-8.</p>
  
  <p><strong>Example</strong></p>
  
  <p>This causes errors while trying to insert into SQL Server:</p>
  
  <pre><code>    &lt;?xml version="1.0" encoding="utf-16"?&gt;
      &lt;MyMessage&gt;Teno&lt;/MyMessage&gt;
  </code></pre>
  
  <p>This doesn't:</p>
  
  <pre><code>    &lt;?xml version="1.0" encoding="utf-8"?&gt;
      &lt;MyMessage&gt;Teno&lt;/MyMessage&gt;
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>I figured out when the SQL Server 2008 for its <code>Xml</code> column type needs utf-8, and when utf-16 in <code>encoding</code> property of the xml specification you're trying to insert:</p>
  
  <p>When you want to add <code>utf-8</code>, then add parameters to SQL command like this:</p>
  
  <pre><code> sqlcmd.Parameters.Add("ParamName", SqlDbType.VarChar).Value = xmlValueToAdd;
  </code></pre>
  
  <p>If you try to add the xmlValueToAdd with <code>encoding=utf-16</code> in the previous row it would produce errors in insert. Also, the <code>VarChar</code> means that national characters aren't recognized (they turn out as question marks).</p>
  
  <p>To add utf-16 to db, either use <code>SqlDbType.NVarChar</code> or <code>SqlDbType.Xml</code> in previous example, or just don't specify type at all:</p>
  
  <pre><code> sqlcmd.Parameters.Add(new SqlParameter("ParamName", xmlValueToAdd));
  </code></pre>