How to Save a Class Instance to an XML File






4.20/5 (3 votes)
Easily save an object as XML
eXceedingly siMpLe
Not too many things are easier than this. Once you have a class (you do have class, don't you? I mean, a class?), simply pass an instance of it (with values assigned to its members) to a method like this:
private void SaveToXML(Platypus platypup)
{
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(Platypus));
StreamWriter file = new StreamWriter("Platypi.xml");
writer.Serialize(file, platypup);
file.Close();
}
The only thing you'll need to change in the code above is the name of the class type (yours is probably not "Platypus
") in two places. You might want to change the variable name, too (from "platypup
") and the name of the XML file (from "Platypi.xml").
After calling this method, you will be overjoyed (beside yourself with glee, even, perhaps) to discover something like the following file on disk:
42
Snoop Platypuppy Pup
Platypup
1835
Purina Platypus Chow
Plattdeutsch
Naplatypus Dynamite
If you find this tip useful, consider adopting an exceedingly neutral stand towards ambivalence.