1

I want to get the value of the QuestionID node (1000000), but all I get in return is just a blank output.

Can you please point me in the right direction?

DECLARE @xml XML =
N'<QuestionaryAnswerList xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="schemas/src/system/antagelse/x20160401">
  <Answer>
    <QuestionId>1000000</QuestionId>
    <PossibleAnswerId>100000010</PossibleAnswerId>
    <AnswerValue>
      <Tekst>No</Tekst>
    </AnswerValue>
  </Answer>
  </QuestionaryAnswerList>';
 
  SELECT CAST(@xml.query('/QuestionaryAnswerList/Answer/PossibleAnswerId') AS VARCHAR(max))
1
  • 1
    You need to define your namespaces; specifically your default one (schemas/src/system/antagelse/x20160401). The fact the value is in a variable is irrelevant. Commented Feb 14, 2022 at 11:49

1 Answer 1

2

Quite simply : respect the XML namespace on your XML root node, and use the XQuery .value() function to get at the data:

-- establish the default XML namespace
WITH XMLNAMESPACES(DEFAULT 'schemas/src/system/antagelse/x20160401')
SELECT 
    @xml.value('(/QuestionaryAnswerList/Answer/QuestionId/text())[1]', 'varchar(20)')
Sign up to request clarification or add additional context in comments.

2 Comments

Hello @marc_s, that worked. Thanks a ton for your help. Can you please explain to me, why I have to reference only the third namespace and not the first two as well? Thanks for your time :)
@givnv: the first two are "standard" namespaces - plus they are defined with a prefix (xsd and xsi) which is never used in the XML document; the third is defined without a prefix, and thus is the default namespace that applies to all XML nodes (unless they're specifically marked with a prefix of another namespace).

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.