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

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

    Default encoding for a xml serializer should be UTF-16. Just to make sure you can try -

    XmlSerializer serializer = new XmlSerializer(typeof(YourObject));
    
    // create a MemoryStream here, we are just working
    // exclusively in memory
    System.IO.Stream stream = new System.IO.MemoryStream();
    
    // The XmlTextWriter takes a stream and encoding
    // as one of its constructors
    System.Xml.XmlTextWriter xtWriter = new System.Xml.XmlTextWriter(stream, Encoding.UTF16);
    
    serializer.Serialize(xtWriter, yourObjectInstance);
    
    xtWriter.Flush();
    

提交回复
热议问题