Last active
September 2, 2015 02:30
-
-
Save huoxudong125/f800ea0b5463e95ab392 to your computer and use it in GitHub Desktop.
.NET/C# XML Serialization: Generic Helper for Loading/Saving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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