SQL Server XML parsing issue

I need to parse XML on a SQL Server 2012 database. However, I cannot find a good guide for parsing this kind of XML (here is the 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 can I parse the "keyc" value from XML?

So, I can use this select / clause or insert it into the database.

+3


source to share


1 answer


You can use nodes

and value

to get this object:

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)

      



Outputs the following:

KeyC
-----------
123-ABC
8R

      

+3


source







All Articles