Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

How to Save a Class Instance to an XML File

4.20/5 (3 votes)
8 Feb 2014CPOL 81.9K  
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:

C#
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:

XML
<platypus xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <id>42</id>
  <nickname>Snoop Platypuppy Pup</nickname>
  <seriousname>Platypup</seriousname>
  <birthyear>1835</birthyear>
  <feed>Purina Platypus Chow</feed>
  <language>Plattdeutsch</language>
  <favoritemovie>Naplatypus Dynamite</favoritemovie>
</platypus>

If you find this tip useful, consider adopting an exceedingly neutral stand towards ambivalence.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)