反序列化XML给我null而不是对象

本文关键字:对象 null XML 给我 反序列化 | 更新日期: 2023-09-27 18:03:14

这是我的XML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//WorldPay//DTD WorldPay PaymentService v1//EN"
                                "http://dtd.worldpay.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="ABC">
    <reply>
        <error code="4">
            <![CDATA[Security violation]]>
        </error>
    </reply>
</paymentService>

我将它反序列化为使用他们提供的XSD创建的类:

var responseStreamReader = new StreamReader(response.GetResponseStream());
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "paymentService";
XmlSerializer mySerializer = new XmlSerializer(typeof(paymentService), xRoot);
var someResponse = (paymentService) mySerializer.Deserialize(responseStreamReader);

它反序列化了paymentService, version, merchantCode,但是Item属性是null

这是模式的一部分:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/worldpa
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/worldpay", IsNullable = false
public partial class paymentService
{
    private object itemField;
    private paymentServiceVersion versionField;
    private string merchantCodeField;
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("inquiry", typeof (inquiry))]
    [System.Xml.Serialization.XmlElementAttribute("modify", typeof (modify))]
    [System.Xml.Serialization.XmlElementAttribute("notify", typeof (notify))]
    [System.Xml.Serialization.XmlElementAttribute("reply", typeof (reply))]
    [System.Xml.Serialization.XmlElementAttribute("submit", typeof (submit))]
    [System.Xml.Serialization.XmlElementAttribute("verify", typeof (verify))]
    public object Item
    {
        get { return this.itemField; }
        set { this.itemField = value; }
    }
    /// <remarks/>
    [System.Xml.Serialization.XmlAttribute]
    public paymentServiceVersion version
    {
        get { return this.versionField; }
        set { this.versionField = value; }
    }
    /// <remarks/>
    [System.Xml.Serialization.XmlAttribute(DataType = "NMTOKEN")]
    public string merchantCode
    {
        get { return this.merchantCodeField; }
        set { this.merchantCodeField = value; }
    }
}

我希望Item是一个reply对象。

我做错了什么?

反序列化XML给我null而不是对象

我已经解决了这个问题,可能不是最好的方式,但为了别人的利益。

我只是删除了所有的命名空间。

我的模式是用XSD.exe生成的,我删除了对Namespace = "http://tempuri.org/worldpay"的所有引用,这就修复了它。这也意味着我不必乱搞XmlRootAttribute。