Reputation: 43077
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?
Upvotes: 3
Views: 3665
Reputation: 43077
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);
Upvotes: 2