MaxP
MaxP

Reputation: 437

How to deserialize XML child elements

I have the following class:

[XmlElement]
public class Container
{
   [XmlAttribute]
   public string Name { get; set; }

   //TODO: set xml serialization attribute.
   public List<Item> Items { get; set; }
}

What attribute should I use on the Itmes property to have it deserialize the child-elements into the list given the following XML:

<Container Name="Container1">
   <Item>
   <Item>
   <Item>
</Container>

Upvotes: 1

Views: 78

Answers (2)

MaxP
MaxP

Reputation: 437

This is the attribute I needed:

[XmlElement("Item")]

Upvotes: 1

Sunil
Sunil

Reputation: 3424

Use CollectionDataContract. Your Item is a collection inside container, so they should be part of Container instead of a separate list property.

[CollectionDataContract(Name = "Container", Namespace = "")]
public class Container : System.Collections.Generic.List<Item>
{
     [XmlAttribute]
     public string Name { get; set; }
}

[DataContract(Name = "Item", Namespace = "")]
public class Item
{
   // Properties
}

Upvotes: 1

Related Questions