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.
- Perform a raw string insert, which is unlikely to work
- Use an XmlReader and SqlDbType.Xml
- 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, 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.