Created
October 7, 2014 10:20
-
-
Save laynor/ca1011ae64eb2859a6a7 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Xml.Serialization; | |
namespace XmlExample | |
{ | |
[Serializable] | |
public class Structure | |
{ | |
public static string ListToString<T>(List<T> l) | |
{ | |
var csv = l.Select(o => o.ToString()).Aggregate((s1, s2) => s1 + ", " + s2); | |
return "(" + csv + ")"; | |
} | |
public string Name { get; set; } | |
public string Description { get; set; } | |
public List<string> Tags { get; set; } | |
public List<string> GridSet { get; set; } | |
public string StartingGrid { get; set; } | |
public override string ToString() | |
{ | |
return string.Format("Name: {0} | |
Description: {1} | |
Tags: {2} | |
GridSet: {3} | |
StartingGrid: {4}", Name, Description, ListToString(Tags), ListToString(GridSet), StartingGrid); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string fname = Path.GetTempFileName(); | |
var structure = new Structure { | |
Name = "Example structure", | |
Description = "Just an example structure used to test structure serialization.", | |
Tags = new List<string> { "Example", "Structure", "Serialization" }, | |
GridSet = new List<string> { "Grid 1", "Grid 2", "Grid 3" }, | |
StartingGrid = "Grid 1" | |
}; | |
Console.WriteLine("Testing serialization of structure:"); | |
Console.WriteLine(structure); | |
Console.WriteLine(); | |
Console.WriteLine(Enumerable.Repeat("-", 70)); | |
Console.WriteLine(); | |
// Serialization | |
var serializer = new XmlSerializer(typeof(Structure)); | |
using (var stream = File.OpenWrite(fname)) { | |
serializer.Serialize(stream, structure); | |
} | |
// Read from file and print xml | |
using (var stream = File.OpenText(fname)) { | |
var serialized = stream.ReadToEnd(); | |
Console.WriteLine(serialized); | |
} | |
Console.WriteLine(); | |
Console.WriteLine(Enumerable.Repeat("-", 70)); | |
Console.WriteLine(); | |
//Deserialization | |
var deserializer = new XmlSerializer(typeof(Structure)); | |
using (var stream = File.OpenRead(fname)) { | |
var deserialized = (Structure)serializer.Deserialize(stream); | |
Console.WriteLine("Deserialized structure:"); | |
Console.WriteLine(deserialized); | |
} | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment