2016-10-20 43 views
0

我必须包含以下格式的XML行的表:SQL Server 2012的解析XML名称空间

<msit:message xmlns:wsa="http://URL1" xmlns:msit="http://URL2" xmlns:env="http://URL3"> 
    <env:Body> 
    <ns0:parent xmlns:ns0="http://URL4"> 
     <ns0:child>123456789</ns0:child> 
... 
    </ns0:parent> 
    </env:Body> 
</msit:message>` 
在表名MYTABLE

,列名的数据。

我写了下面的查询:

;with xmlnamespaces('http://URL2' as msit, 
        'http://URL3' as env, 
        'http://URL1' as wsa, 
        'http://URL4' as ns0) 
select 
t2.field.value('child[1]','varchar(20)') as ban 
from mytable 
cross apply data.nodes('/message/Body/parent') t2(field) 

返回空集,当我需要返回123456789

我在做什么错?

谢谢

回答

3

您可能需要包括在XPath表达式的前缀:

declare @mytable table (data xml) 
insert into @mytable values 
('<msit:message xmlns:wsa="http://URL1" xmlns:msit="http://URL2" xmlns:env="http://URL3"> 
    <env:Body> 
    <ns0:parent xmlns:ns0="http://URL4"> 
     <ns0:child>123456789</ns0:child> 
    </ns0:parent> 
    </env:Body> 
</msit:message>') 

;with xmlnamespaces('http://URL2' as msit, 
        'http://URL3' as env, 
        'http://URL1' as wsa, 
        'http://URL4' as ns0) 
select 
t2.field.value('ns0:child[1]','varchar(20)') as ban 
from @mytable 
cross apply data.nodes('/msit:message/env:Body/ns0:parent') t2(field) 
+0

工作!谢谢。 – Ben

1

命名空间的整点是从多个文档汇集元素之间进行区分。 它类似于我们使用表名或别名限定列的方式,例如, t1.x Vs. t2.x。 所以,当你引用一个元素时,你应该使用正确的命名空间来限定它。

您可能还想使用outer apply而不是交叉应用以防万一缺少元素。

create table mytable (x xml); 
insert into mytable (x) values 
(
'  
<msit:message xmlns:wsa="http://URL1" xmlns:msit="http://URL2" xmlns:env="http://URL3"> 
    <env:Body> 
    <ns0:parent xmlns:ns0="http://URL4"> 
     <ns0:child>123456789</ns0:child> 
    </ns0:parent> 
    </env:Body> 
</msit:message> 
' 
) 
; 

; 
with  xmlnamespaces 
      (
       'http://URL2' as msit 
       ,'http://URL3' as env 
       ,'http://URL1' as wsa 
       ,'http://URL4' as ns0 
      ) 

select  t2.field.value('ns0:child[1]','varchar(20)') as ban 

from     mytable 

      outer apply x.nodes('/msit:message/env:Body/ns0:parent') t2(field) 
;