sách gpt4 ăn đã đi

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

In lại 作者:数据小太阳 更新时间:2023-10-29 02:37:03 27 4
mua khóa gpt4 giày nike

例如,假设我在字符串中有以下 xml:



如果我尝试将其插入到带有 Xml 列的 SQL Server 2005 数据库表中,我将收到以下错误(我使用的是 EF 4.1,但我认为这无关紧要):

XML parsing: line 1, character 38, unable to switch the encoding

经过一些研究,我了解到 SQL Server 要求 xml 为 UTF-16。我如何转换它?

câu trả lời hay nhất

我最初的几次尝试涉及流、字节数组和许多编码问题。事实证明,.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);

关于.net - 如何将 UTF-8 编码为 UTF-16 的 xml 字符串转换为 UTF-16?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8929342/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress