sql server 2008 xml file to table

守給你的承諾、 提交于 2019-12-12 19:17:11

问题


I have an xml file that I'm trying to import into a table. My xml file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<xml_objects xmlns="http://www.blank.info/ns/2002/ewobjects">
<item_id item_id="41-FE-001">
<class display="true">
<class_name>FEEDER</class_name>
</class>
<name display="true">
<name_value>41-FE-001</name_value>
</name>
<attributes>
<attribute>
<attributename>Type</attributename>
<value>EQUIP</value>
</attribute>
<attribute>
<attributename>Tag No</attributename>
<value>41-FE-001</value>
</attribute>
</attributes>
</item_id>
</xml_object>

This is the SQL I'm using. I can't get the SQL to return any values:

CREATE TABLE [dbo].[item_data](
[item_id] [nchar](15) NULL,
[class] [nchar](10) NULL,
) ON [PRIMARY]
GO

--INSERT INTO item_data (item_id) 
SELECT xmldata.value('(@item_id)', 'NCHAR') AS item_id       
FROM ( 
SELECT CAST(x AS XML)
FROM OPENROWSET(BULK 'C:\xmlfile.xml',
SINGLE_BLOB) AS T(x)) AS T(x)
CROSS APPLY x.nodes('//xml_objects/item_id') AS X(xmldata);

I've tried various xpath's and SQL syntax. I can't get the SQL to return any values. Any help would be greatly appreciated.


回答1:


You're ignoring the XML namespace that's defined on the root element:

<xml_objects xmlns="http://www.blank.info/ns/2002/ewobjects">
             ***********************************************

You need to add this to your query:

;WITH XMLNAMESPACES(DEFAULT 'http://www.blank.info/ns/2002/ewobjects')
SELECT 
     xmldata.value('(@item_id)', 'NCHAR') AS item_id       
FROM 
    (SELECT CAST(x AS XML)
     FROM OPENROWSET(BULK 'C:\xmlfile.xml',
     SINGLE_BLOB) AS T(x)) AS T(x)
CROSS APPLY 
     x.nodes('//xml_objects/item_id') AS X(xmldata);


来源:https://stackoverflow.com/questions/11623565/sql-server-2008-xml-file-to-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!