简体   繁体   中英

How to read value from xml in SQL Server

I want to read the value in xml returned by a WCF service which gets called by a stored procedure. The code below returns a null:

declare @xmlValue  varchar(1000)
declare @responseString varchar(100)
declare @idoc int

set @xmlValue = '<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">220</string>'

EXEC sp_xml_preparedocument @idoc OUTPUT, @xmlValue

SELECT *
FROM OPENXML (@idoc, '/*',3)
      WITH (string  varchar(100))

EXEC sp_xml_removedocument @idoc

Of course - the XML has a XML namespace that you're ignoring - you need to pay attention to that!

I would also recommend to use the native XQuery support in SQL Server.

Try this:

DECLARE @xmlvalue XML
SET @xmlValue = '<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">220</string>'

-- define the XML namespace
;WITH XMLNAMESPACES('http://schemas.microsoft.com/2003/10/Serialization/' AS ns)
SELECT
    @xmlValue.value('(ns:string)[1]', 'int')  -- and **use** the XML namespace!

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