Click here to Skip to main content
15,891,943 members
Articles / Programming Languages / XML

Using the XmlSerializer Attributes

Rate me:
Please Sign up or sign in to vote.
4.58/5 (51 votes)
28 Jun 2006CPOL8 min read 315.1K   4.9K   126  
How to serialize and de-serialize .NET objects and XML using the XmlSerializer and the serializer attributes.
using System;
using System.Collections;
using System.Xml.Serialization;

namespace GameList {
	public class Cheats {
		private string setup;
		private Hashtable codes;

		public Cheats() {
			codes = new Hashtable();
		}

		[XmlElement("Setup")]
		public string SetupInformation {
			get { return setup; }
			set { setup = value; }
		}

		public void ClearCodes() {
			codes.Clear();
		}

		public void AddCode(Cheat cheat) {
			try {
				codes.Add(cheat.Code, cheat.Description);
			} catch {
			}
		}

		public void AddCode(string code, string desc) {
			codes.Add(code, desc);
		}

		[XmlArrayItem("Code", typeof(Cheat))]
		[XmlArray("CheatCodes")]
		public Cheat[] CheatCodes {
			get {
				Cheat[] cs = new Cheat[codes.Count];
				int i = 0;
				foreach (string code in codes.Keys) {
					Cheat c = new Cheat(code, codes[code].ToString());
					cs[i++] = c;
				}
				Array.Sort(cs, new CheatComparer());
				return cs;
			}
			set {
				foreach (Cheat c in value) {
					codes.Add(c.Code, c.Description);
				}
			}
		}
	}

	public class Cheat {
		private string code;
		private string desc;

		public Cheat() {
		}

		public Cheat(string code) : this() {
			this.code = code;
		}

		public Cheat(string code, string description) : this(code) {
			this.desc = description;
		}

		[XmlAttribute("code")]
		public string Code {
			get { return code; }
			set { code = value; }
		}

		[XmlElement("Effect")]
		public string Description {
			get { return desc; }
			set { desc = value; }
		}
	}

	public class CheatComparer : System.Collections.IComparer {
		public int Compare(object x, object y) {
			Cheat c1 = x as Cheat;
			Cheat c2 = y as Cheat;
			if (x == null || y == null) {
				return 0;
			}
			return c1.Code.CompareTo(c2.Code);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) BoneSoft Software
United States United States
I've been in software development for more than a decade now. Originally with ASP 2.0 and VB6. I worked in Japan for a year doing Java. And have been with C# ever since.

In 2005 I founded BoneSoft Software where I sell a small number of developer tools.
This is a Organisation (No members)


Comments and Discussions