Assume you have a (stripped down) class definition like this:
public class Player
{
[XmlElement("jerseyNumber")]
public int Number { get; set; }
[XmlElement("playerName")]
public string Name { get; set; }
}
And you wanted to read/write an XML file that looked like this:
<Player>
<jerseyNumber>23</jerseyNumber>
<playerName>Dan</playerName>
</Player>
The key to making this happen is the XmlSerializer class. This is the class that will convert between public properties and XML elements. You can also decorate your class with simple attributes to coerce your class into generating custom XML (i.e. XML attributes, hide or rename elements, etc.).
Here are a couple of helper methods, and a sample that uses them to show you how all of this comes together.
static string GetXMLFromObject(object obj)
XmlSerializer ser = new XmlSerializer(obj.GetType());
StringBuilder sb = new StringBuilder();
using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(sb)))
writer.Formatting = Formatting.Indented;
ser.Serialize(writer, obj);
return sb.ToString();
static object CreateObjectFromXML(string xml, Type xmlType)
XmlSerializer ser = new XmlSerializer(xmlType);
object obj = null;
using (StringReader reader = new StringReader(xml))
obj = ser.Deserialize(reader);
return obj;
static void Main(string[] args)
Player p = new Player();
p.Number = 23;
p.Name = "Dan";
string xml = GetXMLFromObject(p);
Console.WriteLine(xml);
Console.WriteLine();
Player q = (Player)CreateObjectFromXML(xml, typeof(Player));
Console.WriteLine(q.Number + " --> " + q.Name);
Console.ReadLine();
Other references:XML Serialization in the .NET Framework
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.