...">

Deserializing XML returns null for collection property

I am trying to deserialize the following 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>

Using the following classes:

[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

But no matter what I try, the CurrentAccounts array is null when I deserialize it. I tried every combination that I can think of with attributes (I also tried XmlArray and XmlArrayItem).

What am I doing wrong ?: S

+5
source share
2 answers

The problem is with Namespaces.

When I created this setting for the whole class in a test situation, I got a completely different conclusion. here is what i think you should try to read:

    <?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.

+2

, MfCurrentAccounts :

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

}

fooobar.com/questions/19578/...

,

0

All Articles