xmlns的XML提取问题

时间:2018-12-10 07:37:42

标签: sql-server xml openxml

我有一些标准的XML代码正在尝试提取,我已经阅读了有关xmlns的各种不同问题,并且我的代码到现在为止,但是我似乎无法做的是提取文本在“”中输入CustomerID-

DECLARE @docHandle INT 
DECLARE @XmlDocument NVARCHAR(1000) 
DECLARE @rootxmlns VARCHAR(1000) 

SET @XmlDocument ='  
<Root xmlns="http://www.adventure-works.com">   
 <Customers>     
  <Customer CustomerID="GREAL">       
   <CompanyName>Great Lakes Food Market</CompanyName>       
   <ContactName>Howard Snyder</ContactName>       
   <ContactTitle>Marketing Manager</ContactTitle>
   <Phone>(503) 555-7555</Phone>       
  </Customer>     
 </Customers>  
</Root>  ' 
SET @rootxmlns = '<Root xmlns:hm="http://www.adventure-works.com"/>' 

-- Create an internal representation of the XML document.   
EXEC Sp_xml_preparedocument 
@docHandle output, 
@XmlDocument, 
@rootxmlns 

-- Execute a SELECT statement using OPENXML rowset provider.   
SELECT * 
FROM   OPENXML (@docHandle, '/hm:Root/hm:Customers', 3) 
      WITH ([CustomerID]           CHAR(10) './hm:CustomerID'
           ,[Customer.CompanyName] VARCHAR(100)'hm:Customer/hm:CompanyName' 
           ,[Customer.ContactName] VARCHAR(100) 
   'hm:Customer/hm:ContactName' ) 

EXEC Sp_xml_removedocument 
@docHandle 

1 个答案:

答案 0 :(得分:1)

您与private int volatile value; public void setValue(int i){ this.value = i; } 一起使用的方法以及用于创建和删除XML文档的存储过程已经过时了,不应再使用。 the native XML methods更好,更快,更容易阅读(自v2005起支持其中的某些功能)。

我将您的XML放在一个本地声明的变量中。但是您可以内联此方法到针对表数据的任何查询中,从而允许在VIEW和iTVF中使用XML。

public void setValue(int i){
   synchronized(this){
      this.value = i;
   }
}

-首先,我们声明默认名称空间(FROM OPENXML

DECLARE @XmlDocument XML;

SET @XmlDocument ='  
<Root xmlns="http://www.adventure-works.com">   
 <Customers>     
  <Customer CustomerID="GREAL">       
   <CompanyName>Great Lakes Food Market</CompanyName>       
   <ContactName>Howard Snyder</ContactName>       
   <ContactTitle>Marketing Manager</ContactTitle>
   <Phone>(503) 555-7555</Phone>       
  </Customer>     
 </Customers>  
</Root>';

根据xmlns="Some URI"的复数,我假设一个XML内可能有多个客户。这就是为什么我使用WITH XMLNAMESPACES(DEFAULT 'http://www.adventure-works.com') SELECT c.value('(Customer/@CustomerID)[1]','nvarchar(max)') AS CustomerID ,c.value('(Customer/CompanyName/text())[1]','nvarchar(max)') AS CompanyName ,c.value('(Customer/ContactName/text())[1]','nvarchar(max)') AS ContactName ,c.value('(Customer/ContactTitle/text())[1]','nvarchar(max)') AS ContactTitle ,c.value('(Customer/Phone/text())[1]','nvarchar(max)') AS Phone FROM @XmlDocument.nodes('/Root/Customers') A(c) 来获取所有客户的派生表的原因(每个客户将按 row-wise 返回)。

<Customers>方法将读取第二个参数中提供的键入的特定值。