反序列化Soap响应C#

时间:2018-08-30 11:51:15

标签: c# xml soap deserialization

我对Soap响应进行反序列化时遇到一些问题,当尝试使用XmlSerializer类进行反序列化时会遇到异常

肥皂数据:

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?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>
    <IsWmsLoginCorrectResponse xmlns="http://pehade.be/">
      <IsWmsLoginCorrectResult>
        <UserId>int</UserId>
        <LoginToken>guid</LoginToken>
        <ErrorId>int</ErrorId>
        <ErrorDescription>string</ErrorDescription>
      </IsWmsLoginCorrectResult>
    </IsWmsLoginCorrectResponse>
  </soap12:Body>
</soap12:Envelope>

TokenInfo模型:

public const string DefaultSoapNamespace = "http://pehade.be/";

//...

[XmlRoot("IsWmsLoginCorrectResponse", Namespace = Consts.DefaultSoapNamespace)]
    public class TokenInfo : BaseSoapInfo
    {
        [XmlAttribute(AttributeName = "UserId", Namespace = Consts.DefaultSoapNamespace)]
        public int UserId { get; set; }

        [XmlAttribute(AttributeName = "LoginToken", Namespace = Consts.DefaultSoapNamespace)]
        public string LoginToken { get; set; }
    }

public class BaseSoapInfo
    {
        [XmlAttribute(AttributeName = "ErrorId", Namespace = Consts.DefaultSoapNamespace)]
        public int ErrorId { get; set; }

        [XmlAttribute(AttributeName = "ErrorDescription", Namespace = Consts.DefaultSoapNamespace)]
        public string ErrorDescription { get; set; }
    }

解析方法:

public override T ParseSoap<T>(string resultSoap)
        {
            var document = XDocument.Parse(resultSoap);
            var xmlSerializer = new XmlSerializer(typeof(T));

            var soapBody = XName.Get("Body", Consts.DefaultSoapNamespace);

// Exception
            var tokenInfo = (T)xmlSerializer.Deserialize(document.Descendants(soapBody)
                .First()
                .FirstNode
                .CreateReader());         

            return tokenInfo;
        }

我是否正确制作了模型?可以使用其他方法来接收XmlSerializer的流吗?

更新:添加例外详细信息

System.InvalidOperationException:序列不包含任何元素   在System.Linq.Enumerable.First [TSource](System.Collections.Generic.IEnumerable`1 [T]源)中:[0x00010],其位于:0   在C:\ Work \ Projects \ Apro \ Other MDO \ WarehouseMS \ DAL \ SoapConverters \ LoginSoapConverter.cs:40中的DAL.SoapConverters.LoginSoapConverter.ParseSoap [T](System.String resultSoap)[0x00031]:40 08-30 14:56 :01.858 I / mono-stdout(4702):System.InvalidOperationException:序列不包含任何元素

1 个答案:

答案 0 :(得分:2)

我认为XmlAttribute应该更改为XmlElement。例如,UserId应该为:

[XmlElement(Namespace = Consts.DefaultSoapNamespace)]
public int UserId { get; set; }