Hello I'm trying to insert some XML data into a table on SQL Server 2008. However I keep getting thrown this error;
XML parsing: line 1, character 39, unable to switch the encoding
The database column filemeta uses the XML datatype, and I've switch the encoding to UTF-16 which I believe is necessary for adding XML data.
INSERT INTO testfiles (filename, filemeta) VALUES ('test.mp3', '<?xml version="1.0" encoding="utf-16" standalone="yes"?><!--This is a test XML file--><filemeta filetype="Audio"><Comments /><AlbumTitle /><TrackNumber /><ArtistName /><Year /><Genre /><TrackTitle /></filemeta>');
Help, I'm stuck.
NB: I created the XML with XMLTextWriter.
When you bulk import XML data from a file that contains an encoding declaration that you want to apply, specify the SINGLE_BLOB option in the OPENROWSET(BULK...) clause. The SINGLE_BLOB option ensures that the XML parser in SQL Server imports the data according to the encoding scheme specified in the XML declaration.
In SQL Server, you usually store XML data in a column configured with the xml data type. The data type supports several methods that let you query and modify individual elements, attributes, and their values directly within the XML instance, rather than having to work with that instance as a whole.
Now as I said before, XML data stored in a column of data type XML can be processed either by using XML functions available in SQL Server or by using the sp_xml_preparedocument stored procedure along with the OPENXML function.
Yes, there are issues when you try to insert XML into SQL Server 2008 and the XML contains an encoding instruction line.
I typically get around using the CONVERT
function which allows me to instruct SQL Server to skip those instructions - use something like this:
INSERT INTO testfiles (filename, filemeta) VALUES ('test.mp3', CONVERT(XML, N'<?xml version="1.0" encoding="utf-16" standalone="yes"?>......', 2));
It has definitely helped me get various encoded XML stuff into SQL Server.
See the MSDN docs on CAST and CONVERT - a bit down the page there's a number of styles you can use for CONVERT
with XML
and some explanations about them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With