你如何转换成XML字符串使用UTF-8编码UTF-16? [英] How do you convert an xml string with UTF-8 encoding UTF-16?

查看:1437
本文介绍了你如何转换成XML字符串使用UTF-8编码UTF-16?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举例来说,假设我有一个字符串,下面的XML:

For example, say I have the following xml in a string:

<?xml version="1.0" encoding="UTF-8"?>
<Stuff />

如果我尝试插入该到SQL Server 2005数据库表中的XML列,我会得到下面的错误(我使用的是EF 4.1,但我不认为事情):

If I try to insert this into a SQL Server 2005 database table with an Xml column, I'll get the following error (I'm using EF 4.1, but I don't think that matters):

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

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

做了一些研究之后,我才知道,SQL Server期望的XML为UTF-16。如何转换呢?

After doing some research, I learned that SQL Server expects the xml to be UTF-16. How do I convert it?

推荐答案

我的第几次尝试参与流,字节数组和许多编码问题。原来,在.NET中字符串已经UTF-16,所以才有了XML声明需要改变。

My first few attempts involved streams, byte arrays and many encoding issues. Turns out that strings in .NET are already UTF-16, so only the xml declaration needs to be changed.

其实答案很简单。下面是加载字符串转换为的XmlDocument 扩展方法,改变了声明,并抓住了 OuterXml

The answer is actually quite simple. Here's an extension method that loads the string into an XmlDocument, changes the declaration, and grabs the 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);

这篇关于你如何转换成XML字符串使用UTF-8编码UTF-16?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆