如何在C#中反序列化以下XML响应

时间:2015-03-25 10:03:28

标签: c# xml deserialization

我从java网络服务收到以下回复。当尝试使用DataContractSerializer反序列化它时,我收到以下错误

<ns:redeemVoucherResponse xmlns:ns="http://vouchers.example.com">
    <ns:return xmlns:ax236="http://util.vouchers.example.com/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax236:RedeemStatus">
        <ax236:status>fail</ax236:status>
        <ax236:statusCode>4</ax236:statusCode>
        <ax236:statusMessage>Error message</ax236:statusMessage>
        <ax236:redeemData xsi:nil="true" />
    </ns:return>
</ns:redeemVoucherResponse>


Error in line 1 position 65. Expecting element VoucherService.redeemVoucherResponse' from namespace 'http://schemas.datacontract.org/2004/07/Service.Internal.VoucherServices'.. Encountered 'Element'  with name 'redeemVoucherResponse', namespace 'http://vouchers.example.com'.

用于反序列化的类:

public class redeemVoucherResponse {
        [DataMember]
        public RedeemStatus @return { get; set; }
    }

    public class RedeemStatus {
        [DataMember]
        public string status { get; set; }

        [DataMember]
        public byte statusCode { get; set; }

        [DataMember]
        public string statusMessage { get; set; }

        [DataMember]
        public object redeemData { get; set; }
    }

用于反序列化的代码:

HttpWebResponse objWebResponse = HttpWebResponse)objWebRequest.GetResponse();
Stream objResponseStream = objWebResponse.GetResponseStream(); 

Type objType = typeof(redeemVoucherResponse);
DataContractSerializer objXmlSerializer = new DataContractSerializer(objType);

redeemVoucherResponse objMessage = (redeemVoucherResponse)objXmlSerializer.ReadObject(objResponseStream);

1 个答案:

答案 0 :(得分:0)

试试这个......虽然没经过测试。

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://vouchers.example.com")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://vouchers.example.com", IsNullable = false)]
public class redeemVoucherResponse
{
    public redeemVoucherResponseReturn @return { get; set; }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://vouchers.example.com")]
public class redeemVoucherResponseReturn
{
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://util.vouchers.example.com/xsd")]
    public string status { get; set; }

    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://util.vouchers.example.com/xsd")]
    public byte statusCode { get; set; }

    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://util.vouchers.example.com/xsd")]
    public string statusMessage { get; set; }

    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://util.vouchers.example.com/xsd", IsNullable = true)]
    public object redeemData { get; set; }
}