简体   繁体   中英

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>

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
}

这是我需要的属性:

[XmlElement("Item")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM