【发布时间】:2018-01-18 22:47:01
【问题描述】:
我有以下 SOAP 响应:
<?xml version="1.0"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<insertResponse xmlns="order">
<out xmlns="order">
<actionType xmlns="http://serverurl.com">insert</actionType>
<orderNumber xmlns="http://serverurl.com">54556100766</orderNumber>
<errorMsg xmlns="http://serverurl.com">
<ns1:Error xmlns:ns1="http://exception.serverurl.com">
<code xmlns="http://exception.serverurl.com">12345</code>
<message xmlns="http://exception.serverurl.com">Unable to acquire ID. Record does not exist.</message>
</ns1:Error>
</errorMsg>
<orderID xmlns="http://serverurl.com">0000005555</orderID>
<region xmlns="http://serverurl.com">Region11</region>
<successMsg xmlns="http://serverurl.com" xsi:nil="true"/>
</out>
</insertResponse>
</soap:Body>
</soap:Envelope>
我想将其反序列化为以下类:
public class insertResponse
{
public string successMsg { get; set; }
public errorMsg error { get; set ;}
}
public class errorMsg
{
List<Error> errorList { get; set; }
}
public class Error
{
public string code { get; set; }
public string message { get; set; }
}
我有一个方法可以做到这一点:
private T DeserializeSoapResponse<T>(string soapResponse)
{
System.Xml.XmlDocument xmlDocument = new System.Xml.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);
}
}
在执行它时,我在return 语句的行中收到异常消息“XML 文档 (1,2) 中存在错误”。
我错过了什么?如果这是解决问题的正确方法?
【问题讨论】:
-
请发布正确的 XML。那些
-标志不属于这里。或者当它们出现在您的数据中时,它们就是问题所在。 -
而且您的开始/结束标签也不匹配。
orderNumber/customerNumber等 -
很少有问题。首先,您忽略了目标类中的所有命名空间。其次,你忽略了一些元素——比如
out。在 Visual Studio 中尝试Edit |> Paste Special |> Paste XML as Classes。
标签: c# soap xml-deserialization