3

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 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.