Introduction
The static function extracts the Soap Body (XML Data) from a Soap Message.
Using the Code
To extract the soap body, the key point is to get the soap envelope prefix. The soap prefix can be found from the first level Nodes.
For example, the soap message may look like:
<?Xml version="1.-" encoding="utf-8">
<soap:envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:header>
<id>AAA</id>
</soap:header>
<soap:body>
<order>
<id>1234</id>
</order>
</soap:body>
</soap:envelope>
The second element of the message declared the soap Envelope namespace prefix, "Soap".
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/".
System.Xml.XMLNode class provides a function for us to lookup the prefix from the namespace. So we have to locate the xmlnode which has namespace declaration, and lookup the "http://schemas.xmlsoap.org/soap/envelope/" namespace's prefix.
System.Xml.XmlDocument doc=new System.Xml.XmlDocument();
doc.LoadXml(SoapMessage);
string prefix = "";
for(int i=0; i<doc.ChildNodes.Count;i++)
{
System.Xml.XmlNode soapNode= doc.ChildNodes[i];
prefix= soapNode.GetPrefixOfNamespace(http: if(prefix!=null&&prefix.Length>0)
break;
}
After determining the prefix, use the prefix to help us locate soap body (XML Data), start and end index in the soap message, then extract the body substring out.
int iSoapBodyElementStartFrom=SoapMessage.IndexOf("<"+ prefix+":Body");
int iSoapBodyElementStartEnd=SoapMessage.IndexOf(">",iSoapBodyElementStartFrom);
iSoapBodyStartIndex=iSoapBodyElementStartEnd+1;
iSoapBodyEndIndex=SoapMessage.IndexOf("</"+prefix+":Body>")-1;
return SoapMessage.Substring
(iSoapBodyStartIndex,iSoapBodyEndIndex-iSoapBodyStartIndex+1);
History
- 17th April, 2007: First release