1

I have a SQL Server procedure which calls a web service and the web service returns response in the following format:

<?xml version="1.0" encoding="UTF-8" ?>  
 <ProductServiceOutput ProductID="160" TransactionID="315" AMT="10000.00" TransactionStatus="SUCCESS" EntityID="1000005580401" Comments="Successfull" TxnDate="2017-12-19 19:31:45" UDF9="null" stdCode="null"/>

I would like to parse this XML and get the values of ProductID, TransactionID, Amt, TransactionStatus and TxnDate.

I've tried the following SQL, but I'm getting encoding error.

DECLARE @sql NVARCHAR(MAX)
SET @sql = '<?xml version="1.0" encoding="UTF-8" ?>  
 <ProductServiceOutput ProductID="160" TransactionID="315" AMT="10000.00" 
 TransactionStatus="SUCCESS" EntityID="1000005580401" Comments="Successfull" 
 TxnDate="2017-12-19 19:31:45" UDF9="null" stdCode="null"/>'

DECLARE @xmlData XML
SET @xmlData = CONVERT(XML, @sql, 1);
SELECT 
      T.C.value('(ProductID)[1]', 'int')
      ,T.C.value('(TransactionID)[1]', 'nvarchar(20)')
      ,T.C.value('(AMT)[1]', 'decimal(15,2)')
      ,T.C.value('(TransactionStatus)[1]', 'nvarchar(30)')
   FROM @xmlData.nodes('ProductServiceOutput') T(C)

Even after solving encoding error, I'm getting NULL values. Please help me to get the values.

1 Answer 1

2

Please review the image and/or code. You nearly had it! :)

  DECLARE @sql NVARCHAR(MAX)
SET @sql = '
 <ProductServiceOutput ProductID="160" TransactionID="315" AMT="10000.00" 
 TransactionStatus="SUCCESS" EntityID="1000005580401" Comments="Successfull" 
 TxnDate="2017-12-19 19:31:45" UDF9="null" stdCode="null"/>'

DECLARE @xmlData XML
SET @xmlData = CONVERT(XML, @sql, 1);
SELECT 
      T.C.value('@ProductID[1]', 'int') AS ProductId
      ,T.C.value('@TransactionID[1]', 'nvarchar(20)') As TransactionID
      ,T.C.value('@AMT[1]', 'decimal(15,2)') AS AMT
      ,T.C.value('@TransactionStatus[1]', 'nvarchar(30)') AS TransactionStatus
   FROM @xmlData.nodes('ProductServiceOutput') T(C)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot @Epistaxis. I've missed the @ symbol :)
No probs! We all miss something sometime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.