5

I'm having issues querying XML data stored in a SQL Server 2012 database. The node tree I wish to query is in the following format -

<eForm>
   <page id="equalities" visited="true" complete="true">
      <Belief>
         <item selected="True" value="Christian">Christian</item>
         <item selected="False" value="Jewish">Jewish</item>
         ...
      </Belief>
   </page>
</eForm>

What I would like to do is return the value attribute of the item node where the selected attribute is equal to true. I've read several tutorials on querying XML in SQL but can't seem to get the code right.

Thanks Stu

3 Answers 3

4

DEMO

SELECT [value].query('data(eForm/page/Belief/item[@selected="True"]/@value)')
FROM test
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I wasn't wrapping the XPath in data()
one small note, this would be type xml and not varchar
What if the XML tag appears multiple times and I would like to select as many times as it appears? stackoverflow.com/questions/26426412/…
1
select
    Value.value('(eForm/page/Belief/item[@selected="True"])[1]/@value', 'nvarchar(max)')    
from test

sql fiddle demo

Comments

0
DECLARE @T TABLE (X XML);
INSERT @T VALUES ('<eForm>
                       <page id="equalities" visited="true" complete="true">
                          <Belief>
                             <item selected="True" value="Christian">Christian</item>
                             <item selected="False" value="Jewish">Jewish</item>
                          </Belief>
                       </page>
                    </eForm>')

SELECT  item.value('item[1]', 'NVARCHAR(50)')       
FROM    @T
        CROSS APPLY X.nodes('eForm/page/Belief') i (item)
WHERE   item.value('(item[1]/@selected)[1]', 'VARCHAR(5)') = 'true';

N.B.

I actually prefer the other approach posted by MarcinJuraszek, however there could be advantages to the below if you require further data to extract. I originally deleted the answer but there could be situations where this approach is useful so in the interest of showing all options I have undeleted.

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.