XML序列化具有附加属性的通用列表

Posted

技术标签:

【中文标题】XML序列化具有附加属性的通用列表【英文标题】:XML Serializing a generic list with an additional property 【发布时间】: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 属性进行序列化?

【问题讨论】:

【参考方案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 来控制所有项目的命名,所以它不会'不做 方法

【讨论】:

以上是关于XML序列化具有附加属性的通用列表的主要内容,如果未能解决你的问题,请参考以下文章

如何在c#中使用具有相同名称但不同属性和结构的元素反序列化XML

将 C# 列表序列化为具有内部数组的复数命名对象

接口属性的 XML 序列化

接口属性的XML序列化

无法序列化 PySpark UDF

如何将 xml 对象反序列化回类列表