.NET Xml Deserialization example

CSharp · Console

/Program.cs

using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class Program
{
	public static void Main()
	{
		var result = Serializer.Deserialize();

		Console.WriteLine("text: {0}", result.StringProperty);
		Console.WriteLine("number: {0}", result.IntegerProperty);
		Console.WriteLine("enum: {0}", result.EnumProperty);
		Console.WriteLine("child[0].Value: {0}", result.CollectionProperty[0].Value);
		Console.WriteLine("other@[0]: {0}", result.OtherAttributes[0].InnerText);
		Console.WriteLine("other*[0]: {0}", result.OtherElements[0].InnerText);
	}
}

public static class Serializer
{
	public static RootClass Deserialize()
	{
		var type = typeof (RootClass);

		var serializer = new XmlSerializer(type);

		var xmlString = @"
               	<root textAttribute='tex1t' numberAttribute='1' enumAttribute='item1' attributeToIgnore1='ignored1' attributeToIgnore2='ignored2'>
                    <children>
                        <child>text2</child>
                        <child>text3</child>
                    </children>
                    <childToIgnore>ignored3</childToIgnore>
                </root>";

		using (var stringReader = new StringReader(xmlString))
		{
			return serializer.Deserialize(stringReader) as RootClass;
		}
	}
}

[XmlRoot("root")]
public class RootClass
{
	[XmlAttribute("textAttribute")]
	public string StringProperty;

	[XmlAttribute("numberAttribute")]
	public int IntegerProperty;

	[XmlAttribute("enumAttribute")]
	public Enumeration EnumProperty;

	[XmlAnyAttribute]
	public XmlAttribute[] OtherAttributes;

	[XmlArray("children")]
	[XmlArrayItem("child")]
	public Collection<ChildClass> CollectionProperty;

	[XmlAnyElement]
	public XmlElement[] OtherElements;
}

public enum Enumeration
{
	[XmlEnum("item1")]
	Item1,

	[XmlEnum("item2")]
	Item2
}

public class ChildClass
{
	[XmlText]
	public string Value;
}
;