如何转换UTF-8编码UTF-16的xml字符串?

问题描述:

例如,说我有一个字符串以下XML:如何转换UTF-8编码UTF-16的xml字符串?

如果我尝试使用XML列插入到SQL Server 2005数据库表这一点,我会得到以下错误(I”使用EF 4.1,但我米不认为事项):

XML解析:1号线,38字符,无法切换编码

做了一些研究之后,我才知道,SQL服务器期望xml是UTF-16 。我如何转换它?

我的第一次尝试涉及流,字节数组和许多编码问题。发现.NET中的字符串已经是UTF-16,所以只需要更改xml声明。

答案其实很简单。这里有一个扩展方法,将字符串加载到XmlDocument中,更改声明并抓取OuterXml

public static class XmlDocumentExtensions 
{ 
    public static string ToEncoding(this XmlDocument document, Encoding encoding) 
    { 
     if (document.FirstChild.NodeType == XmlNodeType.XmlDeclaration) 
     { 
      XmlDeclaration xmlDeclaration = (XmlDeclaration)document.FirstChild; 
      if (String.Compare(xmlDeclaration.Encoding, encoding.WebName, StringComparison.OrdinalIgnoreCase) != 0) 
      { 
       xmlDeclaration.Encoding = encoding.WebName; 
       return document.OuterXml; 
      } 
     } 

     return document.OuterXml; 
    } 
} 

您可以使用它像这样:

XmlDocument document = new XmlDocument(); 
document.LoadXml(xml); 
xml = document.ToEncoding(Encoding.Unicode);