【问题标题】:C# XML Serialization - How to Serialize attribute in Class that inherits List<Object>?C# XML 序列化 - 如何序列化继承 List<Object> 的类中的属性?
【发布时间】:2013-02-11 12:27:40
【问题描述】:

我需要使用 C# 创建一个 XML 文件。 我正在使用一个继承 List 的类,该 List 表示计算机列表,然后用值对其进行初始化,但序列化程序没有获取此类的属性,仅获取其后代的属性。 这是课程:

public class Computers : List<Computer>
    {
        [XmlAttribute("StorageType")]
        public int StorageType { get; set; }


        [XmlAttribute("StorageName")]
        public string StorageName { get; set; }            

    }

    public class Computer 
    {
        [XmlAttribute("StorageType")]
        public int StorageType { get; set; }

        [XmlAttribute("StorageName")]
        public string StorageName { get; set; }

        public string IPAddress { get; set; }
        public string Name { get; set; }
    }

结果应该是这样的:

<fpc4:Computers StorageName="Computers" StorageType="1">
    <fpc4:Computer StorageName="{D37291CA-D1A7-4F34-87E4-8D84F1397BEA}" StorageType="1">
        <fpc4:IPAddress dt:dt="string">127.0.0.1</fpc4:IPAddress>
        <fpc4:Name dt:dt="string">Computer1</fpc4:Name>
    </fpc4:Computer>
    <fpc4:Computer StorageName="{AFE5707C-EA71-4442-9CA8-2A6264EAA814}" StorageType="1">
        <fpc4:IPAddress dt:dt="string">127.0.0.1</fpc4:IPAddress>
        <fpc4:Name dt:dt="string">Computer2</fpc4:Name>
    </fpc4:Computer>

但到目前为止我得到的是:

<fpc4:Computers>
    <fpc4:Computer StorageType="1" StorageName="{7297fc09-3142-4284-b2e9-d6ea2fb1be78}">
      <fpc4:IPAddress>127.0.0.1</fpc4:IPAddress>
      <fpc4:Name>Computer1</fpc4:Name>
    </fpc4:Computer>
    <fpc4:Computer StorageType="1" StorageName="{eab517f6-aca9-4d01-a58b-143f2e3211e7}">
      <fpc4:IPAddress>127.0.0.1</fpc4:IPAddress>
      <fpc4:Name>Computer2</fpc4:Name>
    </fpc4:Computer>
  </fpc4:Computers>

如您所见,作为父节点的 Computers 节点没有获取属性。

你们有解决办法吗?

【问题讨论】:

    标签: c# xml xml-serialization xmlserializer


    【解决方案1】:

    XmlSerializer 将列表与叶节点完全分开;列表中的属性不存在 - 它只是所包含数据的集合。更好的方法是:

    public class Computers {
        private readonly List<Computer> items = new List<Computer>();
        [XmlElement("Computer")]
        public List<Computer> Items { get { return items; } }
    
        [XmlAttribute("StorageType")]
        public int StorageType { get; set; }
    
        [XmlAttribute("StorageName")]
        public string StorageName { get; set; }   
    }
    

    这是一个一组计算机并且两个属性的对象——但它本身并不是一个列表。对列表使用XmlElementAttribute 可以根据需要展平嵌套。请注意,为方便起见,我省略了命名空间。

    从列表继承(以添加成员为目的)效果不佳,不仅适用于 XmlSerlaizer,而且适用于各种序列化程序和绑定框架。

    【讨论】:

    • myabe 你碰巧知道如何将数据类型作为属性添加到元素中?像 127.0.0.1
    • @MentalBrake 我不知道
    猜你喜欢
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多