Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Serialize an Object to XML in CSharp
From Wiki
Every once in a while we all find the need to persist objects to local storage. Access databases and even SQL CE can be a bit much for such a simple task, so sometimes a small XML file will do the trick. Most recently I've used this to store different configurations that an application uses at runtime. This class uses generics so that it can serialize and deserialize any type. Here is the code:
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
- using System.Xml;
- using System.Xml.Serialization;
- using System.Reflection;
- namespace MyApp
- {
- class XMLClassMapper<T> where T: new()
- {
- private XmlSerializer _serializer;
- private FileStream _stream;
- public bool WriteClass(T toWrite, String fileName)
- {
- //FileMode.Create overwrites existing by default, be aware of this
- _stream = new FileStream(fileName, FileMode.Create);
- _serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
- try
- {
- _serializer.Serialize(_stream, toWrite);
- return true;
- }
- catch(XmlException ex)
- {
- throw ex;
- }
- finally
- {
- _stream.Close();
- _stream = null;
- _serializer = null;
- }
- }
- public T ClassFromFile(string fileName)
- {
- T ret = new T();
- _stream = new FileStream(fileName, FileMode.Open);
- _serializer = new XmlSerializer(typeof(T));
- try
- {
- ret = (T)_serializer.Deserialize(_stream);
- }
- catch(XmlException ex)
- {
- throw ex;
- }
- finally
- {
- _stream.Close();
- _stream = null;
- _serializer = null;
- }
- return ret;
- }
- }
- }
Instantiate it like
- XMLClassMapper<MyType> mpr = new XMLClassMapper<MyType>();
WriteClass() saves your object to an XML file. ClassFromFile() loads your XML file into a class instance. In both cases, fileName is the full path to the file ie C:\folder\subfolder\file.xml. I hope you find this helpful.



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.