Last active
February 10, 2017 09:48
-
-
Save margani/884f2a84ce4c5e848c743b787d44fbc4 to your computer and use it in GitHub Desktop.
This class demonstrates methods for serializing and deserializing object to and from an xml string
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
class XmlSerializationProgram | |
{ | |
static void Main(string[] args) | |
{ | |
var person = new Person | |
{ | |
firstName = "John", | |
lastName = "Doe", | |
dateOfBirth = new MyDate | |
{ | |
year = 1901, | |
month = 4, | |
day = 30 | |
} | |
}; | |
Method1(person); | |
Method2(person); | |
Console.WriteLine("\r\nFinished."); | |
Console.ReadLine(); | |
} | |
#region Method1 | |
private static void Method1(Person person) | |
{ | |
var ser = new System.Xml.Serialization.XmlSerializer(typeof(Person)); | |
var writer = new StringWriter(); | |
ser.Serialize(writer, person); | |
var xml = writer.ToString(); | |
var reader = new StringReader(xml); | |
var anotherObject = ser.Deserialize(reader) as Person; | |
} | |
#endregion | |
#region Method2 | |
private static void Method2(Person person) | |
{ | |
var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(Person)); | |
var output = ""; | |
using (var ms = new MemoryStream()) | |
{ | |
ser.WriteObject(ms, person); | |
output = Encoding.Default.GetString(ms.ToArray()); | |
} | |
using (var ms = new MemoryStream(Encoding.Default.GetBytes(output))) | |
{ | |
var anotherObject = ser.ReadObject(ms) as Person; | |
} | |
} | |
#endregion | |
public class MyDate | |
{ | |
public int year; | |
public int month; | |
public int day; | |
} | |
public class Person | |
{ | |
public string firstName; | |
public string lastName; | |
public MyDate dateOfBirth; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment