ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Deserialize<T>

Deserialize an XDocument to a generic type

Source

public static T Deserialize<T>(this XDocument xmlDocument)
{
	XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
	using (XmlReader reader = xmlDocument.CreateReader())
		return (T)xmlSerializer.Deserialize(reader);
}

Example

string hi = "hello world";
string xml = hi.SerializeToXml();
Console.WriteLine(xml);

string hi2 = XDocument.Parse(xml).Deserialize<string>();
Console.WriteLine(hi2);

Output:

<string>hello world</string>
hello world

Author: asawyer

Submitted on: 8 jul. 2010

Language: C#

Type: System.Xml.Linq.XDocument

Views: 12662