【问题标题】:How to deserialize XML child elements如何反序列化 XML 子元素
【发布时间】:2018-05-23 09:47:13
【问题描述】:

我有以下课程:

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

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

在给定以下 XML 的情况下,我应该在 Itmes 属性上使用什么属性来将子元素反序列化到列表中:

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

【问题讨论】:

    标签: c# xml xml-serialization


    【解决方案1】:

    使用CollectionDataContract。您的 Item 是容器内的集合,因此它们应该是 Container 的一部分,而不是单独的列表属性。

    [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
    }
    

    【讨论】:

    • 好点,但它会重新定义问题。在另一种情况下,我可能需要您的提示。
    【解决方案2】:

    这是我需要的属性:

    [XmlElement("Item")]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多