Monthly Archives: May 2014

C# XML Serialize and Deserialize

public class SomeOtherClass
{
	public Listings GetData()
	{
		// run it only once
		Listings listings = new Listings()
		{
			new Listing() { Name = "Commensal, phone: (416) 596-9364", Address = "655 Bay St, M5G 2K4" },
			new Listing() { Name = "St Louis Bar & Grill, phone: (647) 435-9464", Address = "595 Bay St, M5G 2C2" },
			new Listing() { Name = "Pogue Mahone Irish Pub, phone: (416) 598-3339", Address = "777 Bay St, M5G 2N8" }
		};
		listings.Save(System.Web.HttpContext.Current.Server.MapPath("~/folder/listings.xml"));

		return Listings.GetListings(System.Web.HttpContext.Current.Server.MapPath("~/folder/listings.xml"));
	}
}

public class Listing
{
	public string Name { get; set; }
	public string Address { get; set; }
	public string Cousines { get; set; }
}

public class Listings : List<Listing>
{
	public static List<Listing> GetListings(string path)
	{
		Listings listings;
		using (System.IO.FileStream ts = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
		{
			listings = (new System.Xml.Serialization.XmlSerializer(typeof(Listings)).Deserialize(ts) as Listings);
		}
		return listings;
	}

	public void Save(string path)
	{
		System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(this.GetType());
		using (System.IO.TextWriter w = new System.IO.StreamWriter(path))
		{
			xs.Serialize(w, this);
			w.Flush();
			w.Close();
		}
	}
}