简体   繁体   English

将XML插入SQL Server 2008数据库

[英]INSERT XML into SQL Server 2008 database

Hello I'm trying to insert some XML data into a table on SQL Server 2008. However I keep getting thrown this error; 您好我正在尝试将一些XML数据插入到SQL Server 2008上的表中。但是我不断抛出此错误;

XML parsing: line 1, character 39, unable to switch the encoding XML解析:第1行,第39个字符,无法切换编码

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. 数据库列filemeta使用XML数据类型,我将编码切换为UTF-16,我认为这是添加XML数据所必需的。

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. 注意:我使用XMLTextWriter创建了XML。

Yes, there are issues when you try to insert XML into SQL Server 2008 and the XML contains an encoding instruction line. 是的,当您尝试将XML插入SQL Server 2008并且XML包含编码指令行时,会出现问题。

I typically get around using the CONVERT function which allows me to instruct SQL Server to skip those instructions - use something like this: 我通常使用CONVERT函数,它允许我指示SQL Server跳过这些指令 - 使用类似这样的东西:

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. 它确实帮助我将各种编码的XML内容输入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. 请参阅有关CAST和CONVERTMSDN文档 - 在页面下方有一些样式可用于CONVERT with XML及其中的一些解释。

You just need to include N in front of your XML string to make it unicode. 您只需要在XML字符串前面包含N即可使其成为unicode。

INSERT INTO testfiles
  (filename, filemeta) 
VALUES 
  ('test.mp3', N'<?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>');

This worked for me without any errors: 这对我没有任何错误:

DECLARE @input XML 
SET @input = N'<?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>'

INSERT INTO testfiles (filename, filemeta)
VALUES ('test.mp3', @input);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM