【发布时间】:2011-12-27 21:42:20
【问题描述】:
我有一个对象结构,我试图将其序列化为 xml,这会导致节点级别重复。我很确定它与子类化有关,因为我必须实现自己的反序列化,但我不确定另一个方向到底发生了什么。在应用程序启动时反序列化我的数据时使用相同的 xml 结构作为输入,就像重新序列化它以供以后保存时一样。
以下是错误输出 xml 的样子:
<Keyboarding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Exercises>
<Exercise>
<Exercise Id="3" ActivityNumber="5" SubActivityNumber="b" Type="Standard">
<Title>Test Title</Title>
<Instructions>Downloaded Update Instructions</Instructions>
</Exercise>
</Exercise>
</Exercises>
</Keyboarding>
它应该是这样的(初始反序列化时的样子):
<Keyboarding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Exercises>
<Exercise Id="3" ActivityNumber="5" SubActivityNumber="b" Type="Standard">
<Title>Test Title</Title>
<Instructions>Downloaded Update Instructions</Instructions>
</Exercise>
</Exercises>
</Keyboarding>
根对象包含一组练习。练习是我的基类,而子类由 Type 属性确定。我正在使用自定义 xml 序列化程序来构建来自练习的不同派生类型的对象,因为它允许我使用反射来匹配 2 打左右的潜在派生类型中的任何一个,这些类型在第一次读入时的顺序和数量未知通过我的申请。
这是根元素的集合,使用自定义的 xml 序列化器:
[XmlArray("Exercises")]
[XmlArrayItem("Exercise", Type = typeof (ExerciseXmlSerializer<Exercise>))]
public Collection<Exercise> UnprocessedExercises { get; set; }
我的基本练习类声明如下:
[Serializable]
[XmlType(AnonymousType = true)]
public class Exercise
我的派生类声明如下:
[Serializable]
[XmlType(AnonymousType = true)]
[XmlRoot(ElementName = "Exercise", IsNullable = false)]
public class StandardExercise : Exercise
这是我的自定义 xml 序列化程序的编写器部分:
public class ExerciseXmlSerializer<T> : IXmlSerializable where T : class
{
private T _data;
...
public void WriteXml(XmlWriter writer)
{
Type type = _data.GetType();
new XmlSerializer(type).Serialize(writer, _data);
}
...
}
在WriteXml() 方法中,类型变量被正确设置为派生类型,那么为什么它为基类型和派生类型都创建了节点级别呢?如何防止它这样做?
【问题讨论】:
标签: c# .net xml-serialization