如何解析SOAP消息中的特定部分并获取它们的值?
例如,如果soap响应消息是这样的:
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<GetCountryListResponse xmlns="http://example.org/">
<GetCountryListResult>
<string>string</string>
<string>string</string>
</GetCountryListResult>
</GetCountryListResponse>
</soap12:Body>
</soap12:Envelope>
我想获取GetCountryListResult值并将其保存到一个String变量中。
对于这个问题,我在Java中找到了一个很好的答案:
Java 中从SOAP消息中获取字符串
这个例子将从文件中读取xml并构建找到的字符串列表,但您可以了解如何解析它。
using (FileStream fs = new FileStream(@"c:tempsoap.xml", FileMode.Open))
{
var sr = new StreamReader(fs);
var str = sr.ReadToEnd();
XmlDocument document = new XmlDocument();
document.LoadXml(str);
XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
manager.AddNamespace("soap12", "http://www.w3.org/2003/05/soap-envelope");
manager.AddNamespace("", "http://example.org/");
XmlNodeList xnList = document.SelectNodes("//soap12:Envelope/soap12:Body/GetCountryListResponse/GetCountryListResult", manager);
if (xnList.Count == 0) return;
XmlNode countryListResult = xnList[0];
List<string> result = new List<string>();
foreach (XmlNode childNode in countryListResult.ChildNodes)
{
result.Add(childNode.FirstChild.Value);
}
}
您还需要添加错误处理。
var service=new WebService((;var result=服务。Invoke(soapAction、方法、参数(;
XNamespace nsSoap = "http://www.w3.org/2003/05/soap-envelope";
XNamespace ns = "link-to-namespace";
// Look for the "Fault" element in the response. If present, there was an error.
var fault = result.Root.Element("{" + nsSoap + "}Body").Element("{" + ns_soap + "}Fault");
if (error != null)
{
var codeWithNs = error.Element("{" + nsSoap + "}Code").Element("{" + ns_soap + "}Value").Value;
var codeSplit = codeWithNs.Split(':');
var code = codeSplit.Length == 2 ? codeSplit[1] : codeSplit[0];
if (code == "InvalidUsernameOrPassword")
{
throw new InvalidUsernameOrPasswordException();
}
else
{
throw new Exception("Something went wrong.");
}
}