Created
May 19, 2017 15:56
-
-
Save mstewio/aed94255854df675dc99f7b4dd4e0f19 to your computer and use it in GitHub Desktop.
Serialization and Deserialization with C#
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Xml.Serialization; | |
namespace ConsoleDev | |
{ | |
public class XmlDemo | |
{ | |
public static void Main(string[] args) | |
{ | |
var parent = new Parent | |
{ | |
Child = new List<Child> | |
{ | |
{ new Child { Name = "Mitch" } }, | |
{ new Child { Name = "Stewart" } } | |
} | |
}; | |
XmlSerializer serializer = new XmlSerializer(parent.GetType()); | |
string xml = null; | |
using (MemoryStream stream = new MemoryStream()) | |
{ | |
serializer.Serialize(stream, parent); | |
stream.Position = 0; | |
xml = new StreamReader(stream).ReadToEnd(); | |
} | |
Console.WriteLine(xml); | |
Parent newParent = null; | |
using (Stream stream = ToStream(xml)) | |
{ | |
newParent = (Parent)serializer.Deserialize(stream); | |
} | |
Console.WriteLine(newParent.Child.First().Name); | |
} | |
/// <summary> | |
/// Adapted from: http://stackoverflow.com/questions/1879395/how-to-generate-a-stream-from-a-string | |
/// </summary> | |
/// <param name="s"></param> | |
/// <returns>Stream</returns> | |
public static Stream ToStream(string s) | |
{ | |
MemoryStream stream = new MemoryStream(); | |
StreamWriter writer = new StreamWriter(stream); | |
writer.Write(s); | |
writer.Flush(); | |
stream.Position = 0; | |
return stream; | |
} | |
} | |
/// <summary> | |
/// Generated using: http://xmltocsharp.azurewebsites.net/ | |
/// </summary> | |
[XmlRoot(ElementName = "Child")] | |
public class Child | |
{ | |
[XmlElement(ElementName = "Name")] | |
public string Name { get; set; } | |
} | |
[XmlRoot(ElementName = "Parent")] | |
public class Parent | |
{ | |
[XmlElement(ElementName = "Child")] | |
public List<Child> Child { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment