I'm 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've tried every combination I can think of with the attributes (I've tried XmlArray and XmlArrayItem too).
What am I doing wrong? :S
The issue is with Namespaces.
When I created that entire class setup in a test situation, i got a very different looking output. here is what I think you should be trying to read in:
<?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>
Notice all the extra mf:
. When you declare the namespace, the serializer will work with that and only de-serialize nodes that properly belong to that namespace. You either need to get rid of it entirely or fix your input appropriately. Here is the code that I used to generate that output note: the class definitions are completely unchanged
XmlSerializer ser = new XmlSerializer(typeof(MfCurrentAccounts));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("mf", "urn:somedata");
MemoryStream ms = new MemoryStream();
ser.Serialize(ms, a, ns);
and when reading it back in:
ms.Position = 0;
b = ser.Deserialize(ms) as MfCurrentAccounts;
after running both sections, b is now a perfect clone of a, and the xml I showed above is the generated xml.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With