How to solve “unable to switch the encoding” error when inserting XML into SQL Server

后端 未结 8 1984
醉梦人生
醉梦人生 2020-11-28 07:29

I\'m trying to insert into XML column (SQL SERVER 2008 R2), but the server\'s complaining:

System.Data.SqlClient.SqlException (0x80131904):
XML

8条回答
  •  时光取名叫无心
    2020-11-28 07:48

    You are serializing to a string rather than a byte array so, at this point, any encoding hasn't happened yet.

    What does the start of "messageToLog" look like? Is the XML specifying an encoding (e.g. utf-8) which subsequently turns out to be wrong?

    Edit

    Based on your further info it sounds like the string is automatically converted to utf-8 when it is passed to the database, but the database chokes because the XML declaration says it is utf-16.

    In which case, you don't need to serialize to utf-8. You need to serialize with the "encoding=" omitted from the XML. The XmlFragmentWriter (not a standard part of .Net, Google it) lets you do this.

提交回复
热议问题