Skip to content

Instantly share code, notes, and snippets.

@huoxudong125
Last active September 2, 2015 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huoxudong125/f800ea0b5463e95ab392 to your computer and use it in GitHub Desktop.
Save huoxudong125/f800ea0b5463e95ab392 to your computer and use it in GitHub Desktop.
.NET/C# XML Serialization: Generic Helper for Loading/Saving
<?xml version="1.0" encoding="utf-8"?>
<Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Make>Peugeot</Make>
<Model>406</Model>
<DoorCount>3</DoorCount>
</Car>
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int DoorCount { get; set; }
}
public class Program
{
static void Main(string[] args)
{
Car myCar = new Car()
{
DoorCount = 3,
Make = "Peugeot",
Model = "406"
};
XmlSerializationHelper.Save(myCar, "myCar.xml");
Car myXmlCar = XmlSerializationHelper.Load("myCar.xml");
}
}
public abstract class XmlSerializationHelper
{
public static T Load<T>(string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
TextReader reader = new StreamReader(fileName);
T obj = (T)serializer.Deserialize(reader);
reader.Close();
return obj;
}
public static void Save<T>(T obj, string fileName)
{
TextWriter writer = new StreamWriter(fileName);
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, obj);
writer.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment