Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think Dreas' approach is ok. An alternative to this however is to have some static helper methods and implement IXmlSerializable on each of your methods e.g an XmlWriter extension method and the XmlReader one to read it back.</p> <pre><code>public static void SaveXmlSerialiableElement&lt;T&gt;(this XmlWriter writer, String elementName, T element) where T : IXmlSerializable { writer.WriteStartElement(elementName); writer.WriteAttributeString("TYPE", element.GetType().AssemblyQualifiedName); element.WriteXml(writer); writer.WriteEndElement(); } public static T ReadXmlSerializableElement&lt;T&gt;(this XmlReader reader, String elementName) where T : IXmlSerializable { reader.ReadToElement(elementName); Type elementType = Type.GetType(reader.GetAttribute("TYPE")); T element = (T)Activator.CreateInstance(elementType); element.ReadXml(reader); return element; } </code></pre> <p>If you do go down the route of using the XmlSerializer class directly, create serialization assemblies before hand if possible, as you can take a large performance hit in constructing new XmlSerializers regularly.</p> <p>For a collection you need something like this:</p> <pre><code>public static void SaveXmlSerialiazbleCollection&lt;T&gt;(this XmlWriter writer, String collectionName, String elementName, IEnumerable&lt;T&gt; items) where T : IXmlSerializable { writer.WriteStartElement(collectionName); foreach (T item in items) { writer.WriteStartElement(elementName); writer.WriteAttributeString("TYPE", item.GetType().AssemblyQualifiedName); item.WriteXml(writer); writer.WriteEndElement(); } writer.WriteEndElement(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload