Extract The Node Value From SOAP Response In ASP.NET Application

Introduction

 
Consider a scenario where you need to extract the node value from the SOAP response. This blog will explain  how to extract the node value from the SOAP response using C#.
 

Extract a node value from SOAP response

 
Consider the below SOAP response,
  1. <?xml version=""1.0"" encoding=""utf-8""?>    
  2.            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-   instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">    
  3.             <soap:Body>                    
  4.                <InitializeResponse  xmlns=""http://test.testtech.com/"">  
  5.                     <InitializeResult>TUJBIQBVHAXZE6H6PCQ0</InitializeResult>  
  6.              </InitializeResponse >  
  7.              </soap:Body>    
  8.            </soap:Envelope>  
Let’s see how to extract the value from IntializeResult node.
  1. public string GetXMLResponseValue()  
  2. {  
  3.     var serviceResult = string.Empty;  
  4.     var xmlStr = @"<?xml version=""1.0"" encoding=""utf-8""?>    
  5.     <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-   instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">    
  6.      <soap:Body>                    
  7.         <InitializeResponse  xmlns=""http://test.testtech.com/"">  
  8.              <InitializeResult>TUJBIQBVHAXZE6H6PCQ0</InitializeResult>  
  9.       </InitializeResponse >  
  10.       </soap:Body>    
  11.     </soap:Envelope>";  
  12.     var doc = XDocument.Parse(xmlStr);  
  13.     XNamespace ns = "http://test.testtech.com/";  
  14.     var result = doc.Root.Descendants(ns + "InitializeResponse").Elements(ns + "InitializeResult").FirstOrDefault();  
  15.     if (!String.IsNullOrEmpty(result.Value.ToString()))  
  16.     {  
  17.         serviceResult = result.Value.ToString();  
  18.     }  
  19.     return serviceResult;  
  20. }  
The XDocument.Parse will parse the XML string (xmlStr) to document.
 
XML namespace is defined to the Local Variable ns:
  1. doc.Root.Descendants(ns + "InitializeResponse")  
The above statement is used to fetch the Descendants “IntialzeResponse” node from the root and the Elements function is used to fetch the list of Elements within the descendants.
  1. doc.Root.Descendants(ns + "InitializeResponse").Elements(ns + "InitializeResult").FirstOrDefault(),   
The above statement extracts the first element from the list of “InitializeResult” node within “InitializeResponse” node.
 
 
 
From the above figure you can notice the Value inside IntializeResponse node is extracted as a string and returned. 
 

Summary

 
We saw how to extract the node value from the SOAP response using C#.
 
I hope you have enjoyed this blog. Your valuable feedback, questions, or comments about this blog are always welcomed.
 
Happy Coding!