Querying XML data types which have xmlns node attributes

夙愿已清 提交于 2019-12-05 03:10:31

If your XML document has XML namespaces, then you need to consider those in your queries!

So if your XML looks like your sample, then you need:

-- define the default XML namespace to use
;WITH XMLNAMESPACES(DEFAULT 'bar')
SELECT   
    x.u.value('Name[1]', 'varchar(100)') as Name
from 
    @XMLDOC.nodes('/Feed/Product') x(u)

Or if you prefer to have explicit control over which XML namespace to use (e.g. if you have multiple), use XML namespace prefixes:

-- define the XML namespace 
;WITH XMLNAMESPACES('bar' as b)
SELECT   
    x.u.value('b:Name[1]', 'varchar(100)') as Name
from 
    @XMLDOC.nodes('/b:Feed/b:Product') x(u)

As well as the XMLNAMESPACES solution, you can also use the hideously bulky local-name syntax...

DECLARE @XMLDOC XML
SET @XMLDOC = '<Feed xmlns="bar"><Product><Name>Foo</Name></Product></Feed>'

SELECT  x.u.value('*[local-name() = "Name"][1]', 'varchar(100)') as Name
from @XMLDOC.nodes('/*[local-name() = "Feed"]/*[local-name() = "Product"]') x(u)

You can define namespaces like:

WITH    XMLNAMESPACES ('bar' as b)
SELECT  x.u.value('b:Name[1]', 'varchar(100)') as Name
FROM    @XMLDOC.nodes('/b:Feed/b:Product') x(u)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!