我从Web请求接收到一个响应,该响应实际上是一个XML字符串,根据我发送的请求,此响应可能有所不同。它 可以是带有成功节点或错误节点的XML。
在我的代码中处理此问题的最佳方法是什么?
我可以将String用作对象来访问响应的每个节点吗?
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns1:myService xmlns:ns1="http://site.de/alpm">
<ns1:Response>
<ns1:OrganisationData>
<ns1:ClientId>myID</ns1:ClientId>
<ns1:UserId>service</ns1:UserId>
<ns1:Pass>myPass</ns1:Pass>
</ns1:OrganisationData>
<ns1:TransactionData>
<ns1:TrxId>tg0rta1a1-6fh-hfh5-ryyb-ryyt56</ns1:CSDBTrxId>
<ns1:TimeOfProcessing>2018-11-28T13:09:41.179Z</ns1:TimeOfProcessing>
</ns1:TransactionData>
<ns1:Error>
<ns1:ReturnCode>lpt-978-jh</ns1:ReturnCode>
<ns1:Description>my description</ns1:Description>
</ns1:Error>
</ns1:Response>
</ns1:myService>
</soap:Body>
</soap:Envelope>
<ns1:Error></ns1:Error>
的更改是什么,如果成功,它将是一个新标记。
如何在我的代码中处理这个问题。别忘了我以字符串形式接收此信息吗?这是代码,字符串是“ myResult”:
using (var webResponse = soapRequest.EndGetResponse(asyncResult))
{
string myResult;
var responseStream = webResponse.GetResponseStream();
if (responseStream == null)
{
return null;
}
using (var reader = new StreamReader(responseStream))
{
myResult = reader.ReadToEnd();
}
}
答案 0 :(得分:0)
您可以包括期望的所有可能的属性(以防您仅在“ Error”和“ NewTag”之间切换)并继续正常解析请求。
作为类的外观示例:
public class Response
{
[XmlElement("OrganisationData")]
public OrganisationData OrganisationData { get; set; }
[XmlElement("TransactionData")]
public TransactionData TransactionData { get; set; }
[XmlElement("Error")]
public Error Error { get; set; }
[XmlElement("NewTag")]
public NewTag NewTag { get; set; }
}
现在,您只需在反序列化XML字符串并检查所需的每种情况后,即可检查“ Error”或“ NewTag”是否为空:
using (var webResponse = soapRequest.EndGetResponse(asyncResult))
{
string myResult;
var responseStream = webResponse.GetResponseStream();
if (responseStream == null)
{
return null;
}
using (var reader = new StreamReader(responseStream))
{
myResult = reader.ReadToEnd();
}
var deserializedResult = YourDeserializationLogic(myResult);
if(deserializedResult != null && deserializedResult.Error != null)
{
//Do your error handling Logic
}
else if(deserializedResult != null && deserializedResult.NewTag != null)
{
//Do your post success logic
}
}
注意:我已经使用 XmlSerializer
对该概念进行了测试