【问题标题】:How do I read XML in TSQL using sp_xml_preparedocument that includes a namespace without prefix?如何使用包含不带前缀的命名空间的 sp_xml_preparedocument 在 SQL 中读取 XML?
【发布时间】:2022-06-16 19:16:55
【问题描述】:

我正在运行 SQL Server 2019 15.0.2095.3,我想读取 XML 文件的内容,然后将其存储到表中。问题是我没有收到任何错误,但是当 XML 包含不带前缀的命名空间时结果集为空,但是一旦我删除无前缀命名空间,它就会再次返回数据(它确实可以使用前缀)。

这里是复制问题的代码:

DECLARE @idoc INT, @doc VARCHAR(1000);   
SET @doc =' 
<ROOT xmlns="http://test.com">  
<Customers>  
   <Orders>  
      <nr>5</nr>
      <line>
        <test>55</test>
        <test2>444</test2>
      </line>
   </Orders>  
</Customers>  
<Customers>  
   <Orders>    
      <nr>4</nr>
      <line>
        <test>44</test>
        <test2>444</test2>
      </line>
   </Orders>  
</Customers>  
</ROOT>';   
  
--Create an internal representation of the XML document.  
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc, '<ROOT xmlns="http://test.com"/>  '
  
-- SELECT statement that uses the OPENXML rowset provider.  
    SELECT *
    FROM       OPENXML (@idoc, '/ROOT/Customers/Orders/nr' ) 

EXEC sp_xml_removedocument @idoc;  

当您删除命名空间 &lt;ROOT xmlns="http://test.com"&gt; 并只使用没有它的元素时:&lt;ROOT&gt; 它将返回一个正常的结果集。

但是我希望查询返回内容而不更改 XML

【问题讨论】:

  • 如果您使用的是 SQL Server 2019,为什么不使用 XQuery? SQL Server 至少从 2005 年开始支持它。然后你可以在你的命名空间中使用 WITH XMLNAMESPACES 子句。

标签: sql xml tsql


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
相关资源
最近更新 更多