Click here to Skip to main content
Click here to Skip to main content

How to Save a Class Instance to an XML File

, 8 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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);

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:

<platypus xmlns:xsd="" xmlns:xsi="">
  <nickname>Snoop Platypuppy Pup</nickname>
  <feed>Purina Platypus Chow</feed>
  <favoritemovie>Naplatypus Dynamite</favoritemovie>

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


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


About the Author

B. Clay Shannon
Founder "Across Time & Space"
United States United States
Ideaman and Coder at Across Time & Space, creator of the Windows Store App "Photrax", which can be downloaded as a trial (7 days) from
Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.
I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction:
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

SuggestionThe function can be more generally PinmemberMr. Xie.G.Gang 谢桂纲8-Feb-14 20:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150302.1 | Last Updated 8 Feb 2014
Article Copyright 2014 by B. Clay Shannon
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid