Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize XML with multiple nested items?

I have given XML that I can't change and I need to deserialize it to a custom class:

<Person>
   <Addresses>
       <MainAddress>
          <Country />
          <City />
       </MainAddress>
       <AdditionalAddress>
          <Country />
          <City />
       </AdditionalAddress>
       <AdditionalAddress>
          <Country />
          <City />
       </AdditionalAddress>
       ... other additional addresses
   </Addresses>
   ... other elements
</Person>

Then I deserialize:

XmlSerializer serializer = new XmlSerializer(typeof(Person), namespace);
Person person = serializer.Deserialize(stream) as Person;       

Deserializer works fine in case simple elements are deserialized. When there is element like Addresses I implement IXmlSerializable on its class like here: link text

The problem is that reader.ReadElementContentAsString() cannot be used with complex elements.

like image 396
jlp Avatar asked Dec 10 '09 13:12

jlp


1 Answers

Adressess class should be declared this way:

[XmlRoot("Adressess")]
public class Adressess
{
    [XmlElement(ElementName = "MainAddress")]
    public MainAddress Main { get; set; }

    [XmlElement(ElementName = "AdditionalAddress")]
    public List<AdditionalAddress> AdditionalAddresses { get; set; }
}

[XmlRoot("MainAddress")]
public class MainAddress 
{
    public string Country { get; set; }
    public string City { get; set; }
}

[XmlRoot("AdditionalAddress")]
public class AdditionalAddress
{
    public string Country { get; set; }
    public string City { get; set; }
}
like image 74
PanJanek Avatar answered Nov 24 '22 01:11

PanJanek