你如何转换成XML字符串使用UTF-8编码UTF-16?转换成、字符串、XML、UTF

由网友(此籹子狠乖)分享简介:举例来说,假设我有一个字符串,下面的XML:For example, say I have the following xml in a string:如果我尝试插入该到SQL Server 2005数据库表中的XML列...

举例来说,假设我有一个字符串,下面的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);
阅读全文

相关推荐

最新文章