这可以通过我们自己处理反序列化过程来实现(至少对于根类)
请让我提醒您,您提供的 XML 内容不足以运行单元测试,所以这是一个非常基本的实现,但是应该可以直接为您工作,或者只是在这里和那里稍微调整一下。
首先,我们将 Item 类 XML 序列化属性更改为 root。 “为什么”很快就会得到解答。
[XmlRoot("item")]
public class Item
{
[XmlAttribute("type")]
public string Type { get; set; }
[XmlElement("prop1")]
public int Prop1 { get; set; }
}
我还添加了一个简单的整数属性来证明反序列化按预期工作。
我还更改了 XML 内容以匹配新类型,以进行测试。
<root>
<item type="b">
<prop1>5</prop1>
</item>
<item type="a">
<prop1>5</prop1>
</item>
<item type="a">
<prop1>5</prop1>
</item>
<item type="b">
<prop1>5</prop1>
</item>
<item type="c">
<prop1>5</prop1>
</item>
</root>
现在是 Root 类,它现在显式实现 IXmlSerializable:
[XmlRoot("root")]
public class Root : IXmlSerializable
{
[XmlElement("item")]
public Item[] Items { get; set; }
// These two methods are not implemented for you need to deserialize only,
// and because you haven't provided the schema for your XML content
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { throw new NotImplementedException(); }
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { throw new NotImplementedException(); }
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
{
// The element is <root> when here for the first time.
// Maintain a list to keep items with type "a"
List<Item> typeAItems = new List<Item>();
// Create a serializer for the type Item
XmlSerializer deserializer = new XmlSerializer(typeof(Item));
while (reader.Read())
{
// The code is self explanatory.
// Skip() will help omitting unnecessary reads
// if we are not interested in the Item
if (reader.IsStartElement() && reader.Name == "item")
{
if (reader.GetAttribute("type") == "a")
{
// This works, and deserializes the current node
// into an Item object. When the deserialization
// is completed, the reader is at the beginning
// of the next <Item> element
typeAItems.Add((Item)deserializer.Deserialize(reader));
}
else
{
// skip element with all its children
reader.Skip();
}
}
else
{
// skip element with all its children
reader.Skip();
}
}
Items = typeAItems.ToArray();
}
}
反序列化逻辑保持不变,如 new XmlSerializer(typeof(Root)).Deserialize()。
剩下的就是测试了。