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

后端 未结 8 2029
醉梦人生
醉梦人生 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:51

    Although a .net string is always UTF-16 you need to serialize the object using UTF-16 encoding. That sould be something like this:

    public static string ToString(object source, Type type, Encoding encoding)
    {
        // The string to hold the object content
        String content;
    
        // Create a memoryStream into which the data can be written and readed
        using (var stream = new MemoryStream())
        {
            // Create the xml serializer, the serializer needs to know the type
            // of the object that will be serialized
            var xmlSerializer = new XmlSerializer(type);
    
            // Create a XmlTextWriter to write the xml object source, we are going
            // to define the encoding in the constructor
            using (var writer = new XmlTextWriter(stream, encoding))
            {
                // Save the state of the object into the stream
                xmlSerializer.Serialize(writer, source);
    
                // Flush the stream
                writer.Flush();
    
                // Read the stream into a string
                using (var reader = new StreamReader(stream, encoding))
                {
                    // Set the stream position to the begin
                    stream.Position = 0;
    
                    // Read the stream into a string
                    content = reader.ReadToEnd();
                }
            }
        }
    
        // Return the xml string with the object content
        return content;
    }
    

    By setting the encoding to Encoding.Unicode not only the string will be UTF-16 but you should also get the xml string as UTF-16.

    
    

提交回复
热议问题