我有一个XML字符串(utf-8)。我需要将字符串存储在数据库中(MS SQL)。编码字符串必须是UTF-16。
此代码不起作用,utf16Xml为空
XDocument xDoc = XDocument.Parse(utf8Xml);
xDoc.Declaration.Encoding = "utf-16";
StringWriter writer = new StringWriter();
XmlWriter xml = XmlWriter.Create(writer, new XmlWriterSettings()
{ Encoding = writer.Encoding, Indent = true });
xDoc.WriteTo(xml);
string utf16Xml = writer.ToString();
utf8Xml - string包含一个序列化对象(编码UTF8)。
如何将xml字符串UTF8转换为UTF16?
答案 0 :(得分:1)
这可能对您有所帮助
MemoryStream ms = new MemoryStream();
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Indent = true;
XDocument xDoc = XDocument.Parse(utf8Xml);
xDoc.Declaration.Encoding = "utf-16";
using (XmlWriter xw = XmlWriter.Create(ms, xws))
{
xDoc.WriteTo(xw);
}
Encoding ut8 = Encoding.UTF8;
Encoding ut116 = Encoding.Unicode;
byte[] utf16XmlArray = Encoding.Convert(ut8, ut116, ms.ToArray());
var utf16Xml = Encoding.Unicode.GetString(utf16XmlArray);
答案 1 :(得分:0)
鉴于XDocument.Parse仅接受string
,并且.NET中的string
始终是UTF-16 Little Endian,看来您正在采取许多步骤来有效地没做什么。要么:
字符串utf8Xml
已经是UTF-16 LE,可以按SqlDbType.Xml
或SqlDbType.NVarChar
的形式原样插入SQL Server(即不执行任何操作),>
或
utf8Xml
以某种方式包含UTF-8字节序列,这将是无效的UTF-16 LE(即Microsoft-land中的“ Unicode”)字节序列。如果是这种情况,那么您也许可以简单地:
xDoc.Declaration.Encoding = "utf-8";
OmitXmlDeclaration = false;
utf8Xml
的身份将DbType.VarChar
传递到SQL Server 有关进一步的解释,请参阅我对相关问题的解答(在此处为S.O。):
How to solve “unable to switch the encoding” error when inserting XML into SQL Server