对于具有默认命名空间的元素,查询XML数据失败

时间:2016-01-15 10:24:17

标签: sql-server xml sql-server-2008

为什么我得到第二个SELECT查询的空白结果,第一个查询返回结果。

Declare @myxml xml;
set @myxml = '<items count="2">
  <item id="561" quantity="1" />
  <item id="167" quantity="1" />
</items>'

select @myxml.query('//items');
Go
Declare @myxml xml;
set @myxml = '<ContactLog xmlns="http://adventure-works/contact">
  <Contact Date="2008-09-02T10:12:00" Type="Email">
    <Employee>adventure-works\linda3</Employee>
    <Notes>Customer confirmed delivery of order 71935.</Notes>
  </Contact>
  <Contact Date="2008-06-02T15:07:00" Type="Phone">
    <Employee>adventure-works\david8</Employee>
    <Employee>adventure-works\linda3</Employee>
    <Notes>Customer requested status update on order 71935. Informed customer it is being prepared for delivery.</Notes>
  </Contact>
</ContactLog>';

select @myxml.query('//ContactLog');

1 个答案:

答案 0 :(得分:1)

您应该在适当的命名空间中查询。您的第二个SELECT应为:

select @myxml.query('declare namespace pd="http://adventure-works/contact"; //pd:ContactLog') ;

另一种写作方式如下:

WITH XMLNAMESPACES ('http://adventure-works/contact' AS pd)
SELECT  @myxml.query('//pd:ContactLog');

您可以阅读有关如何在SQL Server here

中处理XML命名空间的更多信息