.net 如何解决在SQL Server中插入XML时出现“无法切换编码”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3760788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to solve "unable to switch the encoding" error when inserting XML into SQL Server
提问by veljkoz
I'm trying to insert into XML column (SQL SERVER 2008 R2), but the server's complaining:
我正在尝试插入 XML 列(SQL SERVER 2008 R2),但服务器抱怨:
System.Data.SqlClient.SqlException (0x80131904):
XML parsing: line 1, character 39, unable to switch the encoding
System.Data.SqlClient.SqlException (0x80131904):
XML 解析:第 1 行,字符 39,无法切换编码
I found out that the XML column has to be UTF-16 in order for the insert to succeed.
我发现 XML 列必须是 UTF-16 才能成功插入。
The code I'm using is:
我正在使用的代码是:
XmlSerializer serializer = new XmlSerializer(typeof(MyMessage));
StringWriter str = new StringWriter();
serializer.Serialize(str, message);
string messageToLog = str.ToString();
How can I serialize object to be in UTF-8 string?
如何将对象序列化为 UTF-8 字符串?
EDIT: 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.
编辑:好的,抱歉混淆 - 字符串需要使用 UTF-8。你是对的 - 默认情况下它是 UTF-16,如果我尝试插入 UTF-8,它就会通过。所以问题是如何序列化成UTF-8。
Example
例子
This causes errors while trying to insert into SQL Server:
这会在尝试插入 SQL Server 时导致错误:
<?xml version="1.0" encoding="utf-16"?>
<MyMessage>Teno</MyMessage>
This doesn't:
这不会:
<?xml version="1.0" encoding="utf-8"?>
<MyMessage>Teno</MyMessage>
Update
更新
I figured out when the SQL Server 2008 for its Xmlcolumn type needs utf-8, and when utf-16 in encodingproperty of the xml specification you're trying to insert:
我想出什么时候 SQL Server 2008 的Xml列类型需要 utf-8,当 utf-16 在encoding您尝试插入的 xml 规范的属性中时:
When you want to add utf-8, then add parameters to SQL command like this:
如果要添加utf-8,则将参数添加到 SQL 命令中,如下所示:
sqlcmd.Parameters.Add("ParamName", SqlDbType.VarChar).Value = xmlValueToAdd;
If you try to add the xmlValueToAdd with encoding=utf-16in the previous row it would produce errors in insert. Also, the VarCharmeans that national characters aren't recognized (they turn out as question marks).
如果您尝试encoding=utf-16在前一行中添加 xmlValueToAdd,则会在插入中产生错误。此外,这VarChar意味着无法识别国家字符(它们变成问号)。
To add utf-16 to db, either use SqlDbType.NVarCharor SqlDbType.Xmlin previous example, or just don't specify type at all:
要将 utf-16 添加到 db,请在前面的示例中使用SqlDbType.NVarChar或SqlDbType.Xml,或者根本不指定类型:
sqlcmd.Parameters.Add(new SqlParameter("ParamName", xmlValueToAdd));
采纳答案by Pedro
Although a .net string is always UTF-16you need to serialize the object using UTF-16encoding.
That sould be something like this:
尽管 .net 字符串总是UTF-16需要使用UTF-16编码来序列化对象。那应该是这样的:
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-16but you should also get the xml string as UTF-16.
通过将编码设置为 Encoding.Unicode,不仅字符串将是,UTF-16而且您还应该将 xml 字符串作为UTF-16.
<?xml version="1.0" encoding="utf-16"?>
回答by ziesemer
This question is a near-duplicate of 2 others, and surprisingly - while this one is the most recent - I believe it is missing the best answer.
这个问题几乎与其他 2 个问题重复,而且令人惊讶的是 - 虽然这是最近的一个 - 我相信它缺少最佳答案。
The duplicates, and what I believe to be their best answers, are:
重复的,以及我认为是他们最好的答案,是:
- Using StringWriter for XML Serialization(2009-10-14)
- Trying to store XML content into SQL Server 2005 fails (encoding problem)(2008-12-21)
- 使用 StringWriter 进行 XML 序列化(2009-10-14)
- 尝试将 XML 内容存储到 SQL Server 2005 失败(编码问题)(2008-12-21)
In the end, it doesn't matter what encoding is declared or used, as long as the XmlReadercan parse it locally within the application server.
最后,声明或使用什么编码并不重要,只要XmlReader可以在应用程序服务器中本地解析它即可。
As was confirmed in Most efficient way to read XML in ADO.net from XML type column in SQL server?, SQL Server stores XML in an efficient binary format. By using the SqlXmlclass, ADO.net can communicate with SQL Server in this binary format, and not require the database server to do any serialization or de-serialization of XML. This should also be more efficient for transport across the network.
正如在从 SQL 服务器中的 XML 类型列读取 ADO.net 中的 XML 的最有效方法中所确认的那样?,SQL Server 以高效的二进制格式存储 XML。通过使用SqlXml该类,ADO.net 可以以这种二进制格式与 SQL Server 进行通信,并且不需要数据库服务器对 XML 进行任何序列化或反序列化。这对于跨网络传输也应该更有效。
By using SqlXml, XML will be sent pre-parsed to the database, and then the DB doesn't need to know anything about character encodings - UTF-16 or otherwise. In particular, note that the XML declarations aren't even persisted with the data in the database, regardless of which method is used to insert it.
通过使用SqlXml,XML 将被发送到数据库,然后数据库不需要知道任何关于字符编码的信息 - UTF-16 或其他。特别要注意的是,XML 声明甚至不会与数据库中的数据一起保存,无论使用哪种方法插入它。
Please refer to the above-linked answers for methods that look very similar to this, but this example is mine:
请参阅上面链接的答案,了解与此非常相似的方法,但此示例是我的:
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Xml;
static class XmlDemo {
static void Main(string[] args) {
using(SqlConnection conn = new SqlConnection()) {
conn.ConnectionString = "...";
conn.Open();
using(SqlCommand cmd = new SqlCommand("Insert Into TestData(Xml) Values (@Xml)", conn)) {
cmd.Parameters.Add(new SqlParameter("@Xml", SqlDbType.Xml) {
// Works.
// Value = "<Test/>"
// Works. XML Declaration is not persisted!
// Value = "<?xml version=\"1.0\"?><Test/>"
// Works. XML Declaration is not persisted!
// Value = "<?xml version=\"1.0\" encoding=\"UTF-16\"?><Test/>"
// Error ("unable to switch the encoding" SqlException).
// Value = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Test/>"
// Works. XML Declaration is not persisted!
Value = new SqlXml(XmlReader.Create(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Test/>")))
});
cmd.ExecuteNonQuery();
}
}
}
}
Note that I would not consider the last (non-commented) example to be "production-ready", but left it as-is to be concise and readable. If done properly, both the StringReaderand the created XmlReadershould be initialized within usingstatements to ensure that their Close()methods are called when complete.
请注意,我不会将最后一个(未注释的)示例视为“生产就绪”,而是将其保持原样以简洁易读。如果处理得当,theStringReader和 createdXmlReader都应该在using语句中初始化,以确保它们的Close()方法在完成时被调用。
From what I've seen, the XML declarations are never persisted when using an XML column. Even without using .NET and just using this direct SQL insert statement, for example, the XML declaration is not saved into the database with the XML:
从我所见,使用 XML 列时,XML 声明永远不会持久化。例如,即使不使用 .NET 仅使用此直接 SQL 插入语句,XML 声明也不会与 XML 一起保存到数据库中:
Insert Into TestData(Xml) Values ('<?xml version="1.0" encoding="UTF-8"?><Test/>');
Now in terms of the OP's question, the object to be serialized still needs to be converted into an XML structure from the MyMessageobject, and XmlSerializeris still needed for this. However, at worst, instead of serializing to a String, the message could instead be serialized to an XmlDocument- which can then be passed to SqlXmlthrough a new XmlNodeReader- avoiding a de-serialization/serialization trip to a string. (See http://blogs.msdn.com/b/jongallant/archive/2007/01/30/how-to-convert-xmldocument-to-xmlreader-for-sqlxml-data-type.aspxfor details and an example.)
现在就OP的问题而言,要序列化的对象仍然需要从MyMessage对象转换为XML结构,并且XmlSerializer仍然需要这样做。然而,在最坏的情况下,不是序列化为字符串,而是可以将消息序列化为XmlDocument- 然后可以通过SqlXmlnew传递给XmlNodeReader- 避免对字符串进行反序列化/序列化之旅。(有关详细信息和示例,请参阅http://blogs.msdn.com/b/jongallant/archive/2007/01/30/how-to-convert-xmldocument-to-xmlreader-for-sqlxml-data-type.aspx.)
Everything here was developed against and tested with .NET 4.0 and SQL Server 2008 R2.
这里的一切都是针对 .NET 4.0 和 SQL Server 2008 R2 开发和测试的。
Please don't make wasteby running XML through extra conversions (de-deserializations and serializations - to DOM, strings, or otherwise), as shown in other answers here and elsewhere.
请不要通过额外的转换(反序列化和序列化 - 到 DOM、字符串或其他方式)运行 XML 来浪费,如此处和其他地方的其他答案所示。
回答by batwad
Isn't the easiest solution to tell the serializer not to ouput the XML declaration? .NET and SQL should sort the rest out between them.
告诉序列化程序不要输出 XML 声明不是最简单的解决方案吗?.NET 和 SQL 应该对它们之间的其余部分进行排序。
XmlSerializer serializer = new XmlSerializer(typeof(MyMessage));
StringWriter str = new StringWriter();
using (XmlWriter writer = XmlWriter.Create(str, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
serializer.Serialize(writer, message);
}
string messageToLog = str.ToString();
回答by Ian Boyd
It took me forever to re-solve this problem.
我花了很长时间才重新解决这个问题。
I was doing an INSERTstatement into SQL Server as something like:
我在INSERTSQL Server 中执行如下语句:
UPDATE Customers
SET data = '<?xml version="1.0" encoding="utf-16"?><MyMessage>Teno</MyMessage>';
and this gives the error:
这给出了错误:
Msg 9402, Level 16, State 1, Line 2
XML parsing: line 1, character 39, unable to switch the encoding
消息 9402,级别 16,状态 1,第 2 行
XML 解析:第 1 行,字符 39,无法切换编码
And the really, very simple fix is to:
真正非常简单的解决方法是:
UPDATE Customers
SET data = N'<?xml version="1.0" encoding="utf-16"?><MyMessage>Teno</MyMessage>';
The difference is prefixing the Unicode string with N:
不同之处在于在 Unicode 字符串前加上N:
N'<?xml version="1.0" encoding="utf-16"?>Teno</MyMessage>'
N'<?xml version="1.0" encoding="utf-16"?>Teno</MyMessage>'
In the former case, an unprefixed string is assumed to be varchar (e.g. Windows-1252 code-page). When it encounters the encoding="utf-16"inside the string, there is a conflict (and rightly so, since the string isn'tutf-16).
在前一种情况下,无前缀字符串被假定为 varchar(例如 Windows-1252 代码页)。当它遇到encoding="utf-16"字符串内部时,就会发生冲突(这是正确的,因为字符串不是utf-16)。
The fix is to pass the string to SQL server as an nvarchar(i.e. UTF-16):
解决方法是将字符串作为nvarchar(即 UTF-16)传递给 SQL 服务器:
N'<?xml version="1.0" encoding="utf-16"?>'
N'<?xml version="1.0" encoding="utf-16"?>'
That way the string isUTF-16, which matches the utf-16 encoding that the XML says it is. The carpet matches the curtains, so to speak.
这样,字符串就是UTF-16,它与 XML 所说的 utf-16 编码相匹配。地毯与窗帘相配,可以这么说。
回答by Solomon Rutzky
@ziesemer's answer(above) is the only fully correct answer to this question and the linked duplicates of this question. However, it could still use a little more explanation and some clarification. Consider this as an extension of @ziesemer's answer.
@ziesemer 的答案(以上)是该问题的唯一完全正确答案以及该问题的链接副本。但是,它仍然可以使用更多的解释和一些澄清。将此视为@ziesemer 答案的扩展。
Even if they produce the desired result, most answers to this question (including the duplicate question) are convoluted and go through many unnecessary steps. The main issue here is the overall lack of understanding regarding how the XMLdatatype actually works in SQL Server (not surprising given that it isn't well documented). The XMLtype:
即使他们产生了预期的结果,这个问题的大多数答案(包括重复问题)都是错综复杂的,并且要经过许多不必要的步骤。这里的主要问题是对XML数据类型在 SQL Server 中的实际工作方式总体缺乏了解(鉴于它没有得到很好的记录,这并不奇怪)。该XML类型:
- Is a highly optimized (for storage) type that converts the incoming XML into a binary format (which is documented somewhere in the
msdnsite). The optimizations include:- Converting numbers and dates from string (as they are in the XML) into binary representations IFthe element or attribute is tagged with the type info (this might require specifying an XML Schema Collection). Meaning, the number "1234567" is stored as a 4-byte "int" instead of a 14-byte UTF-16 string of 7 digits.
- Element and Attribute names are stored in a dictionary and given a numeric ID. That numeric ID is used in the XML tree structure. Meaning, "
<ElementName>...</ElementName>" takes up 27 character (i.e. 54 bytes) in string form, but only 11 characters (i.e. 22 bytes) when stored in theXMLtype. And that is for a single instance of it. Multiple instances take up additional multiples of the 54 bytes. But in the XML type, each instance only takes up the space of that numeric ID, most likely a 4-byte int.
- Stores strings as UTF-16 Little Endian, always. This is most likely why the XML declaration is not stored: it is entirely unnecessary as it is always the same since the "Encoding" attribute cannot ever change.
- No XML declaration assumes the encoding to be UTF-16, notUTF-8.
Can have 8-bit / non-UTF-16 data passed in. In this case, you need to make sure that the string is notan
NVARCHARstring (i.e. not prefixed with an upper-case "N" for literals, not declared asNVARCHARwhen dealing with T-SQL variables, and not declared asSqlDbType.NVarCharin .NET). AND, you need to make sure that you dohave theXMLdeclaration, and that it specifies the correct encoding.PRINT 'VARCHAR / UTF-8:'; DECLARE @XML_VC_8 XML; SET @XML_VC_8 = '<?xml version="1.0" encoding="utf-8"?><test/>'; PRINT 'Success!' -- Success! GO PRINT ''; PRINT 'NVARCHAR / UTF-8:'; DECLARE @XML_NVC_8 XML; SET @XML_NVC_8 = N'<?xml version="1.0" encoding="utf-8"?><test/>'; PRINT 'Success!' /* Msg 9402, Level 16, State 1, Line XXXXX XML parsing: line 1, character 38, unable to switch the encoding */ GO PRINT ''; PRINT 'VARCHAR / UTF-16:'; DECLARE @XML_VC_16 XML; SET @XML_VC_16 = '<?xml version="1.0" encoding="utf-16"?><test/>'; PRINT 'Success!' /* Msg 9402, Level 16, State 1, Line XXXXX XML parsing: line 1, character 38, unable to switch the encoding */ GO PRINT ''; PRINT 'NVARCHAR / UTF-16:'; DECLARE @XML_NVC_16 XML; SET @XML_NVC_16 = N'<?xml version="1.0" encoding="utf-16"?><test/>'; PRINT 'Success!' -- Success!As you can see, when the input string is
NVARCHAR, then the XML declaration canbe included, but it needs to be "UTF-16".When the input string is
VARCHARthen the XML declaration canbe included, but it cannotbe "UTF-16". It can, however, be any valid 8-bit encoding, in which case the bytes for that encoding will be converted into UTF-16, as shown below:DECLARE @XML XML; SET @XML = '<?xml version="1.0" encoding="utf-8"?><test attr="' + CHAR(0xF0) + CHAR(0x9F) + CHAR(0x98) + CHAR(0x8E) + '"/>'; SELECT @XML; -- <test attr="" /> SET @XML = '<?xml version="1.0" encoding="Windows-1255"?><test attr="' + CONVERT(VARCHAR(10), 0xF9ECE5ED) + '"/>'; SELECT @XML AS [XML from Windows-1255], CONVERT(VARCHAR(10), 0xF9ECE5ED) AS [Latin1_General / Windows-1252]; /* XML from Windows-1255 Latin1_General / Windows-1252 <test attr="????" /> ùì?í */The first example specifies the 4-byte UTF-8 sequence for Smiling Face with Sunglassesand it get converted correctly.
The second example uses 4 bytes to represent 4 Hebrew letters making up the word "Shalom", which is converted correctly, and displayed correctly given that the "F9" byte, which is first, is the?character, which is on the right-side of the word (since Hebrew is a right-to-left language). Yet those same 4 bytes display asùì?íwhen selected directly since the default Collation for the current DB isLatin1_General_100_CS_AS_SC.
- 是一种高度优化的(用于存储)类型,它将传入的 XML 转换为二进制格式(在
msdn站点的某处记录)。优化包括:- 如果元素或属性用类型信息标记(这可能需要指定 XML 模式集合),则将数字和日期从字符串(如它们在 XML 中)转换为二进制表示。意思是,数字“1234567”存储为 4 字节的“int”,而不是 7 位的 14 字节 UTF-16 字符串。
- 元素和属性名称存储在字典中并被赋予一个数字 ID。该数字 ID 用于 XML 树结构。意思是,"
<ElementName>...</ElementName>" 以字符串形式占用 27 个字符(即 54 个字节),但在XML类型中存储时仅占用 11 个字符(即 22 个字节)。这是针对它的单个实例。多个实例占用 54 字节的额外倍数。但是在 XML 类型中,每个实例只占用那个数字 ID 的空间,很可能是一个 4 字节的 int。
- 将字符串存储为 UTF-16 Little Endian,始终为。这很可能是不存储 XML 声明的原因:它完全没有必要,因为它总是相同的,因为“编码”属性永远不会改变。
- 没有 XML 声明假定编码是 UTF-16,而不是UTF-8。
可以传入 8 位/非 UTF-16 数据。在这种情况下,您需要确保该字符串不是一个
NVARCHAR字符串(即不以大写字母“N”为前缀,而不是声明为NVARCHARwhen处理 T-SQL 变量,而不是SqlDbType.NVarChar在 .NET 中声明)。并且,您需要确保您确实有XML声明,并且它指定了正确的编码。PRINT 'VARCHAR / UTF-8:'; DECLARE @XML_VC_8 XML; SET @XML_VC_8 = '<?xml version="1.0" encoding="utf-8"?><test/>'; PRINT 'Success!' -- Success! GO PRINT ''; PRINT 'NVARCHAR / UTF-8:'; DECLARE @XML_NVC_8 XML; SET @XML_NVC_8 = N'<?xml version="1.0" encoding="utf-8"?><test/>'; PRINT 'Success!' /* Msg 9402, Level 16, State 1, Line XXXXX XML parsing: line 1, character 38, unable to switch the encoding */ GO PRINT ''; PRINT 'VARCHAR / UTF-16:'; DECLARE @XML_VC_16 XML; SET @XML_VC_16 = '<?xml version="1.0" encoding="utf-16"?><test/>'; PRINT 'Success!' /* Msg 9402, Level 16, State 1, Line XXXXX XML parsing: line 1, character 38, unable to switch the encoding */ GO PRINT ''; PRINT 'NVARCHAR / UTF-16:'; DECLARE @XML_NVC_16 XML; SET @XML_NVC_16 = N'<?xml version="1.0" encoding="utf-16"?><test/>'; PRINT 'Success!' -- Success!如您所见,当输入字符串为 时
NVARCHAR,则可以包含XML 声明,但必须为“UTF-16”。当输入字符串
VARCHAR为时,可以包含XML 声明,但不能是“UTF-16”。但是,它可以是任何有效的 8 位编码,在这种情况下,该编码的字节将转换为 UTF-16,如下所示:DECLARE @XML XML; SET @XML = '<?xml version="1.0" encoding="utf-8"?><test attr="' + CHAR(0xF0) + CHAR(0x9F) + CHAR(0x98) + CHAR(0x8E) + '"/>'; SELECT @XML; -- <test attr="" /> SET @XML = '<?xml version="1.0" encoding="Windows-1255"?><test attr="' + CONVERT(VARCHAR(10), 0xF9ECE5ED) + '"/>'; SELECT @XML AS [XML from Windows-1255], CONVERT(VARCHAR(10), 0xF9ECE5ED) AS [Latin1_General / Windows-1252]; /* XML from Windows-1255 Latin1_General / Windows-1252 <test attr="????" /> ùì?í */第一个示例为Smiling Face with Sunglasses指定了 4 字节的 UTF-8 序列,并且它被正确转换。
第二个示例使用 4 个字节来表示组成单词“Shalom”的 4 个希伯来字母,它被正确转换,并正确显示,因为第一个字节是?字符,它位于右侧(因为希伯来语是从右到左的语言)。然而ùì?í,由于当前 DB 的默认排序规则是Latin1_General_100_CS_AS_SC.
回答by Isak Savo
A string is always UTF-16 in .NET, so as long as you stay inside your managed app you don't have to care about which encoding it is.
.NET 中的字符串始终是 UTF-16,因此只要您留在托管应用程序中,您就不必关心它是哪种编码。
The problem is more likely where you talk to the SQL server. Your question doesn't show that code so it's hard to pin point the exact error. My suggestion is you check if there's a property or attribute you can set on that code that specifies the encoding of the data sent to the server.
问题更可能发生在您与 SQL 服务器交谈的地方。您的问题没有显示该代码,因此很难指出确切的错误。我的建议是您检查是否有可以在该代码上设置的属性或属性,用于指定发送到服务器的数据的编码。
回答by arx
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?
“messageToLog”的开头是什么样的?XML 是否指定了随后证明是错误的编码(例如 utf-8)?
Edit
编辑
Based on your further info it sounds like the string is automaticallyconverted to utf-8 when it is passed to the database, but the database chokes because the XML declaration says it is utf-16.
根据您的进一步信息,听起来该字符串在传递给数据库时会自动转换为 utf-8,但数据库阻塞,因为 XML 声明说它是 utf-16。
In which case, you don'tneed 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.
在这种情况下,你并不需要序列为UTF-8。您需要使用 XML 中省略的“encoding=”进行序列化。XmlFragmentWriter(不是 .Net 的标准部分,谷歌它)可以让你做到这一点。
回答by Vinay B R
Default encoding for a xml serializer should be UTF-16. Just to make sure you can try -
xml 序列化程序的默认编码应该是 UTF-16。只是为了确保您可以尝试-
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();

