问题
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