How do you convert an xml string with UTF-8 encoding UTF-16?

独自空忆成欢 提交于 2019-12-23 18:10:27

问题


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

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

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 parsing: line 1, character 38, unable to switch the encoding

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


回答1:


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.

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;
    }
}

You can use it like so:

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


来源:https://stackoverflow.com/questions/8929342/how-do-you-convert-an-xml-string-with-utf-8-encoding-utf-16

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!