To deserialize a Object to XML in C# and VB.NET you can use the following snippet.

Sample C#

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

Sample Vb.NET

Public Shared Function Deserialize(Of T)(xmlDocument As XDocument) As T
	Dim xmlSerializer = New XmlSerializer(GetType(T))
	Using reader = xmlDocument.CreateReader()
		Return DirectCast(xmlSerializer.Deserialize(reader), T)
	End Using
End Function

One thought on “How to deserialize XML to Object in C# and VB.NET”

Leave a Reply