Extract SOAP body from a SOAP message
You can utilize GetElementsByTagName
to extract the body of the soap request.
private static T DeserializeInnerSoapObject<T>(string soapResponse)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(soapResponse);
var soapBody = xmlDocument.GetElementsByTagName("soap:Body")[0];
string innerObject = soapBody.InnerXml;
XmlSerializer deserializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(innerObject))
{
return (T)deserializer.Deserialize(reader);
}
}
Linq2Xml is simpler to use.
string xml = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>
<soap:envelope xmlns:xsd=""w3.org/2001/XMLSchema"" xmlns:xsi=""w3.org/2001/XMLSchema-instance"" xmlns:soap=""schemas.xmlsoap.org/soap/envelope/"">;
<soap:body>
<order> <id>1234</id> </order>
</soap:body>
</soap:envelope>";
XDocument xDoc = XDocument.Load(new StringReader(xml));
var id = xDoc.Descendants("id").First().Value;
--EDIT--
To loop elements in body
:
XDocument xDoc = XDocument.Load(new StringReader(xml));
XNamespace soap = XNamespace.Get("schemas.xmlsoap.org/soap/envelope/");
var items = xDoc.Descendants(soap+"body").Elements();
foreach (var item in items)
{
Console.WriteLine(item.Name.LocalName);
}
For a request like this:
String request = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:soapenc=""http://schemas.xmlsoap.org/soap/encoding/""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<ResponseData xmlns=""urn:Custom"">some data</ResponseData>
</soap:Body>
</soap:Envelope>";
The following code did the work to unwrap the data and get only the <ReponseData>
xml content:
XDocument xDoc = XDocument.Load(new StringReader(request));
var unwrappedResponse = xDoc.Descendants((XNamespace)"http://schemas.xmlsoap.org/soap/envelope/" + "Body")
.First()
.FirstNode