Top

Tags


Roadkill .NET Wiki

Google ads

Recommended reading


Search

Wednesday
Dec292010

Avoiding Unicode issues when inserting XML into a SQL Database

If you have to insert XML into a SQL Server (2005+) XML column, there's three ways of doing it.

  1. Perform a raw string insert, which is unlikely to work
  2. Use an XmlReader and SqlDbType.Xml
  3. Use SqlDbType.Text and a Stream.

Below is my preferred way of doing it and gets around the problem you might come up with:

XML parsing: line 1, character (xx), unable to switch the encoding

This occurs when you're trying to shove a UTF8 string into the database XML column, either using

<?xml version="1.0" encoding="utf-8"?>

It might also happen with a file with no BOM, which can be fixed by opening + saving the file in notepad. Anyway the solution below gets around this issue.

using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;

...
using (SqlConnection connection = new SqlConnection("conn string"))
{
    connection.Open();
    string sql = "INSERT INTO mytable (xmlColumn) VALUES (@xmlData)";
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
        // Swap round if the source file is unicode         
        string xml = File.ReadAllText(@"C:\myxml.xml");
        //string xml = File.ReadAllText(@"C:\myxml.xml", Encoding.Unicode);

        using (MemoryStream stream = new MemoryStream())
        {
            using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
            {
                writer.Write(xml);
                writer.Flush();
                stream.Position = 0;

                SqlParameter parameter = new SqlParameter("@xmlData", SqlDbType.Text);
                parameter.Value = new SqlXml(stream);
                command.Parameters.Add(parameter);
                command.ExecuteNonQuery();
            }
        }
    }
}

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« Spruce features from 0.1 to 0.9 | Main | C# Bit manipulation by example (part 1) »