反序列化XML为集合属性返回null

时间:2013-02-08 19:32:46

标签: c# xml deserialization xmlserializer

我正在尝试反序列化以下XML:

<?xml version="1.0" encoding="utf-8" ?> 
<mf:somedata xmlns:mf="urn:somedata">
    <CurrentAccount>
        <AccountType>test</AccountType>
        <Charge>
            <ChargeType>test</ChargeType>
        </Charge>
    </CurrentAccount>
    <CurrentAccount>
        <AccountType>test 2</AccountType>
        <Charge>
            <ChargeType>test 2</ChargeType>
        </Charge>
    </CurrentAccount>
</mf:somedata>

使用以下类:

[XmlRoot("somedata", Namespace = "urn:somedata")]
public class MfCurrentAccounts
{
    [XmlElement("CurrentAccount")]
    public CurrentAccount[] CurrentAccounts { get; set; }
}

public class CurrentAccount
{
    public string AccountType { get; set; }

    [XmlElement("Charge")]
    public Charge[] Charges { get; set; }
}

public class Charge
{
    public string ChargeType { get; set; }
}

var c = new XmlSerializer(typeof(MfCurrentAccounts)).Deserialize(new StringReader(xml)) as MfCurrentAccounts;

c.CurrentAccounts // <-- is always null

但无论我尝试什么,当我反序列化它时,CurrentAccounts数组为null。我已经尝试了我能想到的每个组合的属性(我也尝试过XmlArray和XmlArrayItem)。

我做错了什么? :S

2 个答案:

答案 0 :(得分:2)

问题在于命名空间。

当我在测试环境中创建整个类设置时,我得到了一个非常不同的输出。这是我认为您应该尝试阅读的内容:

    <?xml version="1.0"?>
    <mf:somedata xmlns:mf="urn:somedata">
        <mf:CurrentAccount>
            <mf:AccountType>something 1</mf:AccountType>
            <mf:Charge>
                <mf:ChargeType>Charge Type 1</mf:ChargeType>
            </mf:Charge>
        </mf:CurrentAccount>
        <mf:CurrentAccount>
            <mf:AccountType>something 2</mf:AccountType>
            <mf:Charge>
                <mf:ChargeType>Charge Type 2</mf:ChargeType>
            </mf:Charge>
        </mf:CurrentAccount>
    </mf:somedata>

注意所有额外的mf:。声明命名空间时,序列化程序将使用该命名空间,并且仅反序列化正确属于该命名空间的节点。你要么完全摆脱它,要么适当地修改你的输入。以下是我用于生成输出的代码注意:类定义完全不变

XmlSerializer ser = new XmlSerializer(typeof(MfCurrentAccounts));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("mf", "urn:somedata");

MemoryStream ms = new MemoryStream();
ser.Serialize(ms, a, ns);

在阅读时:

ms.Position = 0;
b = ser.Deserialize(ms) as MfCurrentAccounts;

运行这两个部分后,b现在是a的完美克隆,我上面显示的xml是生成的xml。

答案 1 :(得分:0)

也许你应该尝试用以下代码替换你的MfCurrentAccounts类:

[XmlRoot("somedata", Namespace = "urn:somedata")]
public class MfCurrentAccounts : List<CurrentAccount>
{
   public MfCurrentAccounts():base()
   {}

}

或查看https://stackoverflow.com/a/364410/1236044

希望这会有所帮助