How To Read Message From SOAP In C#

In this blog, you will learn how to read a message from SOAP in C#.

To read a message from SOAP in C#, we can use the XDocument class provided by "System.Xml.Linq". The other namespaces are "System.Xml" and "System.Xml.Serialization". Here is a custom code snippet where the first parameter is the SOAP response and the second parameter is the node name which you want to read.
  1. public static string GetSoapMessage(string soapBody, string nodeName)    
  2. {    
  3.    XNamespace soapNameSpace  
  4.       = XNamespace.Get("YOUR SOAP NAMESPACE URL");    
  5.    var document = XDocument.Parse(soapBody);    
  6.     
  7.    var soapMessage = document?.Root?.Descendants()?.Where(p =>   
  8.                p.Name.LocalName.Equals(nodeName) && p.Name.Namespace   
  9.                == soapNameSpace).FirstOrDefault()?.ToString();    
  10.     
  11.     soapMessage = soapMessage?.Replace("xmlns:urn=""xmlns=")    
  12.                                       .Replace("<urn:""<")    
  13.                                       .Replace("</urn:""</");    
  14.     
  15.     return soapMessage;    
  16. }