問題描述
我有以下 SQL 查詢:
I have the following SQL query:
DECLARE @XMLDOC XML
SET @XMLDOC = '<Feed><Product><Name>Foo</Name></Product></Feed>'
SELECT x.u.value('Name[1]', 'varchar(100)') as Name
from @XMLDOC.nodes('/Feed/Product') x(u)
返回:
Name
----
Foo
但是,如果我的
節(jié)點具有 xmlns
屬性,那么這不會返回任何結果:
However, if my <Feed>
node has an xmlns
attribute, then this doesn't return any results:
DECLARE @XMLDOC XML
SET @XMLDOC = '<Feed xmlns="bar"><Product><Name>Foo</Name></Product></Feed>'
SELECT x.u.value('Name[1]', 'varchar(100)') as Name
from @XMLDOC.nodes('/Feed/Product') x(u)
返回:
Name
----
只有當我有一個 xmlns
屬性時才會發(fā)生這種情況,其他任何東西都可以正常工作.
This only happens if I have an xmlns
attribute, anything else works fine.
這是為什么?如何修改我的 SQL 查詢以返回結果而不考慮屬性?
Why is this, and how can I modify my SQL query to return results regardless of the attributes?
推薦答案
如果您的 XML 文檔具有 XML 命名空間,那么您需要在查詢中考慮這些!
If your XML document has XML namespaces, then you need to consider those in your queries!
因此,如果您的 XML 看起來像您的示例,那么您需要:
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)
或者,如果您希望明確控制要使用的 XML 命名空間(例如,如果您有多個),請使用 XML 命名空間前綴:
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)
這篇關于查詢具有 xmlns 節(jié)點屬性的 XML 數據類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!