如何在 SQL Server 中读取 XML

问题描述 投票:0回答:1
<Result xmlns="uri:SomeNamespace">  
  <PD:Summary xmlns:PD="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription">  
   <p1:p xmlns:p1="http://www.w3.org/1999/xhtml">  
         Our top-of-the-line competition mountain bike. Performance-  
         enhancing options include the innovative HL Frame, super-smooth   
         front suspension, and traction for all terrain.</p1:p>  
  </PD:Summary>  
</Result>

如何在 SQL Server 中使用 XQuery 读取此 XML 的元素和属性?

sql-server xml sql-server-2012 xquery xquery-sql
1个回答
0
投票

假设您的 XML 数据位于 SQL 变量中 - 您可以尝试这样的操作

  • 尊重所有定义的 XML 命名空间
  • 深入 XML

代码:

DECLARE @XmlData XML =
    '<Result xmlns="uri:SomeNamespace">  
  <PD:Summary xmlns:PD="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription">  
   <p1:p xmlns:p1="http://www.w3.org/1999/xhtml">  
         Our top-of-the-line competition mountain bike. Performance-  
         enhancing options include the innovative HL Frame, super-smooth   
         front suspension, and traction for all terrain.</p1:p>  
  </PD:Summary>  
</Result>';

-- setup the XML namespaces in play
WITH XMLNAMESPACES('uri:SomeNamespace' AS ns1,
                   'https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription' AS pd,
                   'http://www.w3.org/1999/xhtml' AS p1)
    -- select the /Result/Summary/p element respecting all the involved namespaces
    SELECT
        BodyText = @XmlData.value('(/ns1:Result/pd:Summary/p1:p/text())[1]', 'varchar(2000)')

你会得到类似的结果:

BodyText
------------------------------------------------------------------------
        Our top-of-the-line competition mountain bike. Performance-            
        enhancing options include the innovative HL Frame, super-smooth             
        front suspension, and traction for all terrain.
© www.soinside.com 2019 - 2024. All rights reserved.