3

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.

1 Answer 1

3

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
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.