Reputation: 31
I need to parse XML into a SQL Server 2012 database. However, I cannot find any good guide to parse this kind XML (here is SELECT TOP 2 FROM table):
<ns2:SoftWare xmlns:ns2="http://www.example.com" xmlns:ns3="http://www.example2.com"><keyc>123-ABC</keyc><statusc>Y</statusc></ns2:SoftWare>
<ns2:custom-data xmlns:ns2="http://www.example.com/2"><timec>2016.01.02</timec><customer>8R</customer><keyc>8R</keyc><statusc>N</statusc></ns2:custom-data>
Any help, how I can parse "keyc" value from XML?
So, I can use it select clause / or insert it to database.
Upvotes: 3
Views: 115
Reputation: 13209
You can use the nodes
and value
to get that entity:
DECLARE @Data TABLE (XmlText XML)
INSERT @Data VALUES
('<ns2:SoftWare xmlns:ns2="http://www.example.com" xmlns:ns3="http://www.example2.com"><keyc>123-ABC</keyc><statusc>Y</statusc></ns2:SoftWare>'),
('<ns2:custom-data xmlns:ns2="http://www.example.com/2"><timec>2016.01.02</timec><customer>8R</customer><keyc>8R</keyc><statusc>N</statusc></ns2:custom-data>')
SELECT
Nodes.KeyC.value('.', 'VARCHAR(50)') AS KeyC
FROM @Data D
CROSS APPLY XmlText.nodes('//keyc') AS Nodes(KeyC)
This outputs the following:
KeyC
-----------
123-ABC
8R
Upvotes: 3