2011-07-14 101 views
0

我想從下面的XML中讀取ContactId和Notes。我嘗試使用Openxml並聲明命名空間,但我無法得到我的預期結果。要求您提供解決方案。在SQL Server 2008中讀取XML

<ArrayOfContact xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<Contact> 
<ContactId xmlns="http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData">100</ContactId> 
<Notes xmlns="http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData">Test1</Notes> 
</Contact> 
<Contact> 
<ContactId xmlns="http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData">101</ContactId> 
<Notes xmlns="http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData">Test2</Notes> 
</Contact> 
</ArrayOfContact> 

回答

2

OPENXML funcation是SQL Server 2000舊XML支持,我會使用的數據類型xml推出了新的XML的方法。

DECLARE @x xml; 
SET @x = '<ArrayOfContact xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<Contact> 
<ContactId xmlns="http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData">100</ContactId> 
<Notes xmlns="http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData">Test1</Notes> 
</Contact> 
<Contact> 
<ContactId xmlns="http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData">101</ContactId> 
<Notes xmlns="http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData">Test2</Notes> 
</Contact> 
</ArrayOfContact>'; 

WITH XMLNAMESPACES ('http://www.thomsonreuters.com/2011/02/25/CMS/CmsService/ContactData' AS cms) 
SELECT 
    contact.value('cms:ContactId[1]', 'int') ContactId, 
    contact.value('cms:Notes[1]', 'nvarchar(MAX)') Notes 
    FROM @x.nodes('/ArrayOfContact/Contact') AS contacts(contact);