当我反序列化XML,我得到一个错误,XML是无效的

问题描述:

我有以下SOAP响应:当我反序列化XML,我得到一个错误,XML是无效的

<?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); 
    } 
} 

当执行它,我得到的消息来异常“有一个在XML d错误(1,2)“与return声明一致。

我错过了什么?如果这是解决问题的正确方法?

+0

请发布正确的XML。那些''''符号不属于这里。或者当他们在你的数据,他们是问题。 –

+2

而且你的开始/结束标签不匹配.' OrderNumber' /'customerNumber'等。 –

+1

有几个问题。首先,你忽略了目标类中的所有命名空间。其次,你忽略了一些元素 - 比如“out”。在Visual Studio中尝试编辑|>选择性粘贴|>将XML粘贴为类。 –

<orderID xmlns="http://serverurl.com">0000005555</orderID> <region xmlns="http://serverurl.com">Region11</region> 

您的订单ID结束标记丢失。