c# - 如何使用 C# XML 序列化序列化 xml 数组和类属性

标签 c# .net xml-serialization

我有一个继承自 List<T> 的类并且还有一些属性,像这样:

[Serializable]
public class DropList : List<DropItem>
{
    [XmlAttribute]
    public int FinalDropCount{get; set;}
}

这个类被序列化为 xml 作为更大类的一部分:

[Serializable]
public class Location
{
    public DropList DropList{get; set;}
    ....
}

问题是,序列化程序将我的列表视为一个集合;生成的 XML 仅包含列表元素,但不包含类属性(在本例中为 FinalDropCount)。这是输出的 XML 示例:

<Location xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <DropList>
        <DropItem ProtoId="3" Count="0" Minimum="0" Maximum="0" />
        <DropItem ProtoId="4" Count="0" Minimum="0" Maximum="0" />
    </DropList>
    ....
</Location>

有没有什么方法可以保存列表内容和属性而不用执行 IXmlSerializable用手?

最佳答案

您还有其他可以考虑的选择。

备选方案 - 转向组合而不是继承:

public class DropInfo
{
    [XmlArray("Drops")]
    [XmlArrayItem("DropItem")]
    public List<DropItem> Items { get; set; }

    [XmlAttribute]
    public int FinalDropCount { get; set; }
}

public class Location
{
    public DropInfo DropInfo { get; set; }
}

备选方案二 - 将属性移出集合:

public class DropList : List<DropItem>
{
}

public class Location
{
    public DropList DropList { get; set; }

    [XmlAttribute]
    public int FinalDropCount { get; set; }
}

关于c# - 如何使用 C# XML 序列化序列化 xml 数组和类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2325745/

相关文章:

c# - 当字符在 CDATA 中时,为什么 XML 序列化程序会抛出无效字符异常?

c# - 如何清除数据库的外键约束?

c# - WPF 附加事件与非附加事件

c# - 代码契约(Contract)的好处

java - “HTML 属性不可序列化”异常 (java)

c# - C# 中的 XML 到 SQL 中的 varbinary 列

c# - NAudio频带强度

c# - 如何在我自己的通用方法中使用 Math.Abs​​?

c# - 是否可以将传递给.NET方法的变量的类型限制为不是派生类?

c# - 如何正确处理类中使用的字节数组?