我有一个继承自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参数。
那我该如何解决呢?
答案 0 :(得分:3)
你将无法直接执行此操作,因为XmlSerializer
对ICollection<T>
对象进行了特殊处理(正如您所注意到的)几乎忽略了该类并且只是将其序列化内容。两个选项:
IXmlSerializable
并进行自己的序列化。List<T>
类型的成员,而不是继承该类。List<T>
。IList<T>
而不是List<T>
。使用私有列表实现所有接口成员,如:public void Add(T item) => this.list.Add(item);
public void Clear() => this.list.Clear();
[...]
IXmlSerializable
- 首先编写自己的变量,然后使用私有列表输出其他所有变量。