C# 为包含集合的类实现 IXmlSerializable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/955875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing IXmlSerializable for Classes Containing Collections
提问by Pr?riewolf
I need to be able to Xml Serialize a class which is internal, so I must implement IXmlSerializable.
我需要能够 Xml 序列化一个内部类,所以我必须实现 IXmlSerializable。
This class has a two strings and a List in it.
这个类有一个两个字符串和一个列表。
I know to read and write the strings using WriteElementString & ReadElementContentAsString.
我知道使用 WriteElementString 和 ReadElementContentAsString 读取和写入字符串。
However, I'm lost on how to read & write the List in the ReadXml & WriteXml methods.
但是,我不知道如何在 ReadXml 和 WriteXml 方法中读取和写入列表。
How do I do this, or is there a way to serialize and deserialize the object while maintaining it's internal accessibility?
我该怎么做,或者有没有办法在保持其内部可访问性的同时序列化和反序列化对象?
采纳答案by John Saunders
Just write a <List>
element for the list itself, then loop over the items and write them out as <Item>
elements.
只需<List>
为列表本身编写一个元素,然后遍历项目并将它们作为<Item>
元素写出。
If the elements are instances of a class that can be XML Serialized, then you could create an XmlSerializer instance for the type of the element, then just serialize each one to the same XmlWriter you're already using. Example:
如果元素是可以进行 XML 序列化的类的实例,那么您可以为该元素的类型创建一个 XmlSerializer 实例,然后只需将每个元素序列化为您已经在使用的同一个 XmlWriter。例子:
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("XmlSerializable");
writer.WriteElementString("Integer", Integer.ToString());
writer.WriteStartElement("OtherList");
writer.WriteAttributeString("count", OtherList.Count.ToString());
var otherSer = new XmlSerializer(typeof(OtherClass));
foreach (var other in OtherList)
{
otherSer.Serialize(writer, other);
}
writer.WriteEndElement();
writer.WriteEndElement();
}
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement("XmlSerializable");
reader.ReadStartElement("Integer");
Integer = reader.ReadElementContentAsInt();
reader.ReadEndElement();
reader.ReadStartElement("OtherList");
reader.MoveToAttribute("count");
int count = int.Parse(reader.Value);
var otherSer = new XmlSerializer(typeof (OtherClass));
for (int i=0; i<count; i++)
{
var other = (OtherClass) otherSer.Deserialize(reader);
OtherList.Add(other);
}
reader.ReadEndElement();
reader.ReadEndElement();
}