Serialize to and from XML

Posted on: Wed Mar 18 17:51:12 -0700 2009. Updated on: Wed Mar 18 17:59:16 -0700 2009.
Category: DotNet

Do you ever have an object lying around that you would like to save off to the database and then be able to retrieve it later as that same object type? Then this might help you. Note that it only works with class objects that are serializable, and these must have a parameterless constructor.

They come in handy to serialize Generic List objects too.

		public static string SerializeToString(object obj)
		{
			string output = null;
			if (obj != null)
			{
				XmlSerializer serializer = new XmlSerializer(obj.GetType());

				using (StringWriter writer = new StringWriter())
				{
					serializer.Serialize(writer, obj);

					output = writer.ToString();
				}
			}
			return output;
		}

And then to serialize back into the object:

		public static T SerializeFromString(string xml)
		{
			XmlSerializer serializer = new XmlSerializer(typeof(T));

			using (StringReader reader = new StringReader(xml))
			{
				return (T)serializer.Deserialize(reader);
			}
		}

Comments:

Add a Comment:

simple_captcha.jpg
(human authentication)


Ads

Categories

About

Random foliage

This website is meant to be a reference for ASP Dot Net developers. The entries are a compilation of things I've figured out how to do and that I deem useful to keep of track for future reference. Assumptions: web development with: C Sharp (vb sucks), visual studio 05/08, .net 3.5, meant for programmers. Written by: James Reategui.