0

I have XML variable defined below and its value.

I want to fetch the text defined between tag <TextNodeChild> in single query.

Kindly help.

Declare @XMLVariable = 
'<?xml version="1.0"?>
 <root>  
     <TextNodeParent>
         <TextNodeChild>12345</TextNodeChild>
         <TextNodeChild>67890</TextNodeChild>
         <TextNodeChild>12389</TextNodeChild>
     </TextNodeParent>
 </root>'

I need output like this:

12345
67890
12389
1
  • 1
    Show us what you've tried so far Commented Dec 5, 2017 at 7:57

2 Answers 2

1

You could use the XQuery (i.e. XML query) .nodes() method

SELECT 
    TextNodeParent = n.value('.[1]', 'NVARCHAR(max)') 
FROM
    @XMLVariable.nodes('root/TextNodeParent/*') as p(n)

EDIT : If you want to just the select the TextNodeChild node data then little change in xml path as follow

 @XMLVariable.nodes('root/TextNodeParent/TextNodeChild') as p(n)

Result

TextNodeParent
12345
67890
12389
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution.
That will list all elements below <TextNodeParent> - not jsut the <TextNodeChild> nodes. In the sample, there are no other nodes - so this works - but as a general solution, it could fail if there were other elements stored under the <TextNodeParent> node
0

@YogeshSharma's solution works - here - because you have nothing but <TextNodeChild> elements under your <TextNodeParent> node.

However, if you had various node, and you wanted to extract only the <TextNodeChild> ones and get their values (and ignore all others), you'd have to use something like this instead:

SELECT 
    TextNodeParent = XC.value('.', 'INT')
FROM
    @XMLVariable.nodes('root/TextNodeParent/TextNodeChild') as XT(XC)

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.