【问题标题】:XML Serializing a generic list with an additional propertyXML序列化具有附加属性的通用列表
【发布时间】:2021-04-13 09:04:47
【问题描述】:

我需要创建一个序列化为此的对象模型:

<RootItem>
    <PropertySet name="SomePropList">
        <Property name="SomeProp" value="SomeValue"/>
    </PropertySet>
</RootItem>

我想不通。我有以下内容:

[XmlRoot("RootItem")]
public class RootItem
{
    public AuthResponse()
    { 
        PropertySet = new PropertySet();
    }

    public PropertySet PropertySet { get; set; }
}

    
public class PropertySet : List<Property>
{
    public PropertySet()
    {
    }

     [XmlAttribute]
     public string name { get; set; }
}


[XmlType("Property")]
public class Property
{
    [XmlAttribute]
    public string name { get; set; }

    [XmlAttribute]
    public string value { get; set; }
}

不幸的是,当它序列化时,它忽略了 name 属性,而我得到了这个:

<RootItem>
    <PropertySet>
        <Property name="externalId" value="55555555"/>
    </PropertySet>
</RootItem>

我需要什么类型的对象模型/技巧/属性才能使用 PropertySet 中的 name 属性进行序列化?

【问题讨论】:

    标签: c# xml .net-core serialization


    【解决方案1】:

    我为 PropertySet 和 Property 找到了一个类似这样的解决方案:

    public class PropertySet
    {
        public PropertySet()
        {
            Properties = new List<Property>();
        }
        
        [XmlAttribute]
        public string name { get; set; }
    
        [XmlElement("Property")]
        public List<Property> Properties { get; set; }    
    }
    
    [XmlType("Property")]
    public class IgtProperty
    {
        [XmlAttribute]
        public string name { get; set; }
        [XmlAttribute]
        public string value { get; set; }
    }
    

    最大的收获是你可以从泛型集合继承你的类,而不是你必须在你的类中包含你想要序列化的其他道具的列表,然后使用 XmlElement 来控制所有项目的命名,所以它不会'不做 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      相关资源
      最近更新 更多