SQL Server XQuery and Namespaces
I just had a frustrating little SQL Server problem earlier today and would like to share the handy solution I found via Experts Exchange.
SELECT ResponseXml.value('(//Reference)[1]', 'varchar(50)')
FROM Transaction
A fairly simple XQuery request of an XML column but annoyingly it didn’t work, and it turned out to to be because the ResponseXml had an unnamed XML namespace, which SQL Server doesn’t handle too nicely.
<Message xmlns="http://www.example.com/">
<Reference>123</Reference>
</Message>
It’s the xmlns attribute (XML namespace) that causes the problem apparently, and the simplest solution I found was this snippet:
SELECT ResponseXml.value('declare default element namespace "http://www.example.com/"; (//Reference)[1]', 'varchar(50)')
FROM Transaction
I just had to tell XQuery to use a different default namespace – a lot simpler than other suggested solutions such as removing the namespace from the XML.