Reputation: 2550
I have a xml file having following data
<SearchProgramsResponse xmlns="http://api.abc.com/2011-03-01/">
<page>1</page>
<items>50</items>
<total>3129</total>
<programItems>
<programItem id="7779">
<name>Coolblue NL</name>
<adrank>5.4</adrank>
<categories>
<category id="40">Cell, Phone & Fax</category>
<category id="11">Internet services</category>
</categories>
</programItem>
<programItem id="7780">
<name>ABC NL</name>
<adrank>2.4</adrank>
<categories>
<category id="42">Cell</category>
<category id="12">services</category>
</categories>
</programItem>
</programItems>
</SearchProgramsResponse>
I want to Transfer this XML data to SQL server tables. But as there are multiple categories for one ITEM.. So how do i process this XML.
I mean I want to transfer DATA to two tables
In tableA one row per record eg :
TableA(ITEM) : programItem , Name , adrank
TABLEB(Category) : ITEMID, categoryID ,CategoryName
I have gone through XML reference but all are with Single value xml attribute , HOW can I process this type of XML ?
I have tried both queries below but no success
DECLARE @xmldata XML
SET @xmldata =
N'<SearchProgramsResponse xmlns="http://api.abc.com/2011-03-01/">
<page>1</page>
<items>50</items>
<total>3129</total>
<programItems>
<programItem id="7779">
<name>Coolblue NL</name>
<adrank>5.4</adrank>
<categories>
<category id="40">Cell, Phone & Fax</category>
<category id="11">Internet services</category>
</categories>
</programItem>
<programItem id="7780">
<name>ABC NL</name>
<adrank>2.4</adrank>
<categories>
<category id="42">Cell</category>
<category id="12">services</category>
</categories>
</programItem>
</programItems>
</SearchProgramsResponse>';
SELECT
Tbl.Col.value('name[1]', 'varchar(70)')
FROM @xmldata.nodes('/SearchProgramsResponse/programItems/programItem') Tbl(Col)
SELECT
XReservering.value('@programItem', 'int'),
XOpties.value('(.)', 'varchar(50)')
FROM
@xmldata.nodes('/SearchProgramsResponse/programItems/programItem') AS XTbl1(XReservering)
CROSS APPLY
XReservering.nodes('categories/category') AS XTbl2(XOpties)
Upvotes: 1
Views: 3089
Reputation: 117636
Well you can apply nodes()
function twice to get all the categories with item_id
:
;with xmlnamespaces(default 'http://api.abc.com/2011-03-01/')
select
t.c.value('@id', 'int') as id,
t.c.value('(name/text())[1]', 'nvarchar(max)') as name,
t.c.value('(adrank/text())[1]', 'decimal(29,10)') as adrank
from @data.nodes('SearchProgramsResponse/programItems/programItem') as t(c)
;with xmlnamespaces(default 'http://api.abc.com/2011-03-01/')
select
t.c.value('@id', 'int') as item_id,
c.c.value('@id', 'int') as category_id,
c.c.value('text()[1]', 'nvarchar(max)') as category_name
from @data.nodes('SearchProgramsResponse/programItems/programItem') as t(c)
outer apply t.c.nodes('categories/category') as c(c)
Upvotes: 1