Serializing and deserializing XML
In the previous section, we have seen how we can use the XmlSerializer
class, from the System.Xml.Serialization
namespace, to serialize and deserialize data. This class is handy for serializing objects to XML and deserializing XML to objects. Although, in the previous example, we used a memory stream to serialize, it actually works with any stream; moreover, it also works with the TextWriter
and XmlWriter
adapters.
The following sample shows a modified Serializer<T>
class, where we specify the path of a file where the XML document is to be written to or read from:
public static class Serializer<T> { Â Â Â Â static readonly XmlSerializer _serializer = Â Â Â Â Â Â Â Â new XmlSerializer(typeof(T)); Â Â Â Â public static void Serialize(T value, string path) Â Â Â Â { Â Â Â Â Â Â Â Â using var ms = File.CreateText(path); Â ...