3

I can query XML, which has defined xmlns tag with common table expression

DECLARE @XML XML
SET @XML = 
'<NodeA xmlns="https://XYZ.xsd">
<NodeB verzePis="">
 <NodeC1 attrA="Hello" />
 <NodeC2 attrA="World" />
 </NodeB>
</NodeA>
'
;WITH XMLNAMESPACES(DEFAULT 'https://XYZ.xsd')
 SELECT
 r.value('fn:local-name(.)', 'nvarchar(50)') as SectionName,
 r.value('@attrA','NVARCHAR(250)') attrA
 FROM @XML.nodes('/NodeA/NodeB/*') AS t(r);

But what if source XML does not contain any xmlns tag ? How can i workaround missing namespace ?

Tom V
15.8k7 gold badges66 silver badges87 bronze badges
asked Feb 12, 2016 at 11:32

1 Answer 1

6

You can just remove the WITH XMLNAMESPACES(DEFAULT 'https://XYZ.xsd') part:

DECLARE @XML XML
SET @XML = 
'<NodeA>
<NodeB verzePis="">
 <NodeC1 attrA="Hello" />
 <NodeC2 attrA="World" />
 </NodeB>
</NodeA>
'
;--WITH XMLNAMESPACES(DEFAULT 'https://XYZ.xsd')
 SELECT
 r.value('fn:local-name(.)', 'nvarchar(50)') as SectionName,
 r.value('@attrA','NVARCHAR(250)') attrA
 FROM @XML.nodes('/NodeA/NodeB/*') AS t(r);

produces

+-------------+-------+
| SectionName | attrA |
+-------------+-------+
| NodeC1 | Hello |
| NodeC2 | World |
+-------------+-------+

Please note, WITH XMLNAMESPACES does not create a common table expression, it just declares an optional namespace

answered Feb 12, 2016 at 11:45
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.