IXmlSerializable implementation for classes containing collections

I need to be able to Xml Serialize a class that is internal, so I have to implement IXmlSerializable.

This class has two lines and a list in it.

I know how to read and write strings using WriteElementString and ReadElementContentAsString.

However, I lost information on how to read and write a list in the ReadXml and WriteXml methods.

How to do this, or is there a way to serialize and deserialize an object while maintaining its internal availability?

+4
source share
1 answer

Just write the <List> element for the list itself, then loop the elements and write them as <Item> .

If the elements are instances of a class that can be serialized by XML, then you can create an XmlSerializer instance for the element type, and then just serialize each of the same XmlWriter that you already use. Example:


 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(); } 
+8
source

Source: https://habr.com/ru/post/1285804/


All Articles