简体   繁体   中英

How to extract a LookupCustomerIdResult element value from XML text using t-sql XQuery

I want to determine LookupCustomerIdResult value from following XML SOAP 1.1 response:

Declare @ResponseText as Varchar(8000)
SET @ResponseText = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <LookupCustomerIdResponse xmlns="http://www.alarm.com/WebServices">
      <LookupCustomerIdResult>54949945</LookupCustomerIdResult>
    </LookupCustomerIdResponse>
  </soap:Body>
</soap:Envelope>'

I tried following but I get NULL result:

Declare @XmlResponse as xml
select @XmlResponse = CAST(@ResponseText as xml) 
DECLARE @customerID VARCHAR(500)

SELECT @customerID = @XmlResponse.value
('(/LookupCustomerIdResponse/LookupCustomerIdResult)[1]', 'varchar(550)')

SELECT @customerID

Thank you.

At least there are two problems, first LookupCustomerIdResponse is not the root element so you can't start with /LookupCustomerIdResponse . This can be fixed by using descendant-or-self axis ( // ) instead.

The second problem is, that the XML has default namespace declaration -namespace declared without prefix- at the LookupCustomerIdResponse level. That causes LookupCustomerIdResponse and all the descendant elements without explicit prefix -and without local default namespace- to be considered in that same namespace. You can use ;WITH XMLNAMESPACES() construct to specify default namespace to be used in the following XPath/XQuery statements.

;WITH XMLNAMESPACES(default 'http://www.alarm.com/WebServices')
SELECT @customerID = @XmlResponse.value
('(//LookupCustomerIdResponse/LookupCustomerIdResult)[1]', 'varchar(550)')

SELECT @customerID

Sqlfiddle Demo

output :

54949945

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM