使用C#读取Soap消息

   sfasfasfasfsfsf    123456 successful  105     

我试图使用C#阅读上面的肥皂消息XmlDocument

 XmlDocument document = new XmlDocument(); document.LoadXml(soapmessage); //loading soap message as string XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable); manager.AddNamespace("d", "http://someURL"); XmlNodeList xnList = document.SelectNodes("//bookHotelResponse", manager); int nodes = xnList.Count; foreach (XmlNode xn in xnList) { Status = xn["d:bookingStatus"].InnerText; } 

计数始终为零,并且未读取bookingstatus值。

BookHotelResponse位于命名空间urn:schemas-test:testgate:hotel:2012-06 (示例xml中的默认命名空间),因此您需要在查询中提供该命名空间:

 XmlDocument document = new XmlDocument(); document.LoadXml(soapmessage); //loading soap message as string XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable); manager.AddNamespace("d", "http://someURL"); manager.AddNamespace("bhr", "urn:schemas-test:testgate:hotel:2012-06"); XmlNodeList xnList = document.SelectNodes("//bhr:bookHotelResponse", manager); int nodes = xnList.Count; foreach (XmlNode xn in xnList) { Status = xn["d:bookingStatus"].InnerText; } 

使用LINQ2XML

要阅读bookingStatus,请执行此操作

 XElement doc = XElement.Load("yourStream.xml"); XNamespace s = "http://schemas.xmlsoap.org/soap/envelope/";//Envelop namespace s XNamespace bhr="urn:schemas-test:testgate:hotel:2012-06";//bookHotelResponse namespace XNamespace d="http://someURL";//d namespace foreach (var itm in doc.Descendants(s + "Body").Descendants(bhr+"bookHotelResponse")) { itm.Element(d+"bookingStatus").Value;//your bookingStatus value } 

LINQ2XML虽然很酷 …. 🙂

首先,您要创建一个类来将xml值解析为

  public class bookHotelResponse { public int bookingReference { get; set; } public int bookingStatus { get; set; } } 

然后,您可以利用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); } } 

据我所知,你想得到肥皂服务的回应。 如果是这样,你不必自己完成所有这些艰苦的工作(调用,解析xml,选择节点以获得响应值)……而是你需要为你的项目添加服务引用,它将完成所有的工作rest为你工作,包括生成类,进行asmx调用等等…在这里阅读更多相关信息https://msdn.microsoft.com/en-us/library/bb628649.aspx

添加引用后你需要做的就是调用类似这样的类方法

 var latestRates = (new GateSoapClient())?.ExchangeRatesLatest(); return latestRates?.Rates;