Consider creating a helper class that uses XML serialization. That decouples the XML formatting from the main class's design, and generally speaking is in keeping with the idea of adding functionality to classes through composition. (In fact, it's often a good idea to do it this way even if the helper class doesn't use XML serialization.) It also lets you format the XML declaratively without getting having to write a lot of procedural code.
How to do this: design the helper class so that it exposes public properties in a fashion that XmlSerializer
likes, and gets those values from an instance of your class that's passed in to a private constructor. Add a static XmlSerializer
property, and a public static method that uses the XmlSerializer
to write the data to a file or a stream or whatever. Something like:
[XmlRoot("MyClass")]
public class MyClassXmlWriter
{
private static XmlSerializer Serializer = new XmlSerializer(typeof MyClassXmlWriter);
public static void Write(MyClass source, Stream st)
{
Serializer.Serialize(new MyClassXmlWriter(source), st);
}
private MyClass Source;
private MyClassXmlWriter(MyClass source)
{
Source = source;
}
[XmlElement("SomeElement")]
public string SomeProperty { get { return Source.SomeProperty; } }
}
Using this is as simple as:
using (FileStream fs = new FileStream(filename))
{
MyClassXmlWriter.Write(myObject, fs);
}
Note that if you ever need to implement deserialization, you just give its properties public getters and then implement a static Read
method that deserializes into a new MyClassXmlWriter
object and then creates and populates a MyClass
object from its properties. (You'd probably change the name of the class, though.)