从SOAP消息中提取SOAP主体

我想从SOAP消息中提取SOAP主体,我在SOAP主体中有一些数据,我必须在日期库中解析,所以这是代码:

public string Load_XML(string SoapMessage) { //check soap message if (SoapMessage == null || SoapMessage.Length <= 0) throw new Exception("Soap message not valid"); //declare some local variable int iSoapBodyStartIndex = 0; int iSoapBodyEndIndex = 0; //load the Soap Message //Učitaj string XML-a i pretvori ga u XML XmlDocument doc = new XmlDocument(); try { doc.Load(SoapMessage); } catch (XmlException ex) { WriteErrors.WriteToLogFile("WS.LOAD_DOK_LoadXML", ex.ToString()); throw ex; } //search for the "http://schemas.xmlsoap.org/soap/envelope/" URI prefix string prefix = string.Empty; for (int i = 0; i  0) break; } //prefix not founded. if (prefix == null || prefix.Length <= 0) throw new Exception("Can't found the soap envelope prefix"); //find soap body start index int iSoapBodyElementStartFrom = SoapMessage.IndexOf("", iSoapBodyElementStartFrom); -> HERE I HAVE AN ERROR!!!! iSoapBodyStartIndex = iSoapBodyElementStartEnd + 1; //find soap body end index iSoapBodyEndIndex = SoapMessage.IndexOf("") - 1; //get soap body (xml data) return SoapMessage.Substring(iSoapBodyStartIndex, iSoapBodyEndIndex - iSoapBodyStartIndex + 1); } 

我在这里得到一个错误:

 int iSoapBodyElementStartEnd = SoapMessage.IndexOf(">", iSoapBodyElementStartFrom); 

错误:

指数超出范围。 必须是非负数且小于集合的大小。

如果有人知道如何解决这个问题?

对于这样的请求:

 String request = @"   some data  "; 

以下代码完成了解包数据并仅获取 xml内容的工作:

 XDocument xDoc = XDocument.Load(new StringReader(request)); var unwrappedResponse = xDoc.Descendants((XNamespace)"http://schemas.xmlsoap.org/soap/envelope/" + "Body") .First() .FirstNode 

Linq2Xml更易于使用。

 string xml = @" ;   1234   "; XDocument xDoc = XDocument.Load(new StringReader(xml)); var id = xDoc.Descendants("id").First().Value; 

– 编辑 –

循环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); } 

您可以使用GetElementsByTagName来提取soap请求的正文。

 private static T DeserializeInnerSoapObject(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); } }