如何使用自定义参数将继承自List <t>的类序列化为XML?

时间:2016-10-05 10:55:17

标签: c# xml unity3d

我有一个继承自List

的类
[Serializable]
public class ListWithVersion<T> : List<T>
{
    [XmlElement(ElementName = "version")]
    public int version;

    public ListWithVersion(IEnumerable<T> collection) : base(collection)
    {
    }

    public ListWithVersion() : base()
    {

    }
}

我将它序列化为XML

ListWithVersion<Chapter> lwv = new ListWithVersion<Chapter>();
        Chapter chapter = new Chapter();
        chapter.dialogs = new List<Dialog>();
        lwv.version = 1;
        lwv.Add(chapter);

        Serialize("lwv.xml", typeof(ListWithVersion<Chapter>), extraTypes, lwv);

    private void Serialize(string name, Type type, Type[] extraTypes, object obj)
    {
        try
        {
            var serializer = new XmlSerializer(type, extraTypes);
            using (var fs = new FileStream(GetPathSave() + name, FileMode.Create, FileAccess.Write))
            {
                serializer.Serialize(fs, obj);
            }
        }
        catch (XmlException e)
        {
            Debug.LogError("serialization exception, " + name + " Message: " + e.Message);
        }
        catch (System.Exception ex)
        {
            Debug.LogError("exc while ser file '" + name + "': " + ex.Message);
            System.Exception exc = ex.InnerException;
            int i = 0;
            while (exc != null)
            {
                Debug.LogError("inner " + i + ": " + exc.Message);
                i++;
                exc = exc.InnerException;
            }
        }
    }

但XML文件不包含version参数。

<?xml version="1.0" encoding="windows-1251"?>
<ArrayOfChapter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Chapter id="0">
    <dialogs />
  </Chapter>
</ArrayOfChapter>

(version =“1.0”不是我的参数)

我尝试过XmlAttribute而不是XmlElement,并且还尝试了原始的

public int version;

没有任何东西可以帮助获取XML中的version参数。

那我该如何解决呢?

1 个答案:

答案 0 :(得分:3)

你将无法直接执行此操作,因为XmlSerializerICollection<T>对象进行了特殊处理(正如您所注意到的)几乎忽略了该类并且只是将其序列化内容。两个选项:

  • 实施IXmlSerializable并进行自己的序列化。
  • 修改您的类,使其成为List<T>类型的成员,而不是继承该类。
编辑:我会在这里回答您的评论,因为格式化文本更容易。你可以这样做,但这可能需要两种方法的混合。

  1. 在班级内设置私人List<T>
  2. 让您的班级实施IList<T>而不是List<T>。使用私有列表实现所有接口成员,如:
  3. public void Add(T item) => this.list.Add(item);
    
    public void Clear() => this.list.Clear();
    
    [...]
    
    1. 实施IXmlSerializable - 首先编写自己的变量,然后使用私有列表输出其他所有变量。