65.9K
CodeProject is changing. Read more.
Home

Extract Soap Body From Soap Message

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.44/5 (7 votes)

Apr 17, 2007

CPOL
viewsIcon

78737

downloadIcon

892

Extract XML Data from Soap Message

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.

//load the Soap Message
System.Xml.XmlDocument doc=new System.Xml.XmlDocument();
doc.LoadXml(SoapMessage);

//search for the "http://schemas.xmlsoap.org/soap/envelope/" URI prefix
string prefix = "";
for(int i=0; i<doc.ChildNodes.Count;i++)
{
    System.Xml.XmlNode soapNode= doc.ChildNodes[i];
    prefix= soapNode.GetPrefixOfNamespace(http://schemas.xmlsoap.org/soap/envelope/);
    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.

//find soap body start index
int iSoapBodyElementStartFrom=SoapMessage.IndexOf("<"+ prefix+":Body");
int iSoapBodyElementStartEnd=SoapMessage.IndexOf(">",iSoapBodyElementStartFrom);
iSoapBodyStartIndex=iSoapBodyElementStartEnd+1;    

//find soap body end index
iSoapBodyEndIndex=SoapMessage.IndexOf("</"+prefix+":Body>")-1;
            
//get soap body (XML data)
return SoapMessage.Substring
	(iSoapBodyStartIndex,iSoapBodyEndIndex-iSoapBodyStartIndex+1);

History

  • 17th April, 2007: First release