How to de-serialize from an XML file to .Net Object

XML deserialization is the process of converting an XML file or XML data into its corresponding .Net object representation. This allows developers to easily work with and manipulate the data within their .Net applications.

XML deserialization

During XML deserialization, the XML data is parsed and mapped to the properties and fields of the target .Net object. This process essentially reverses the serialization process, restoring the data structure from its XML representation back into its original form.

To perform XML deserialization in .Net, developers can utilize the XmlSerializer class, which is provided by the .Net Framework. This class offers a set of methods and attributes that enable seamless conversion between XML and .Net objects.

The XmlSerializer class provides various options for customizing the deserialization process. For example, developers can specify the XML element names that should be mapped to specific properties or fields of the .Net object. They can also handle any exceptions or errors that may occur during deserialization, ensuring robust error handling and recovery. The following source code shows how to de-serialize the DataSet as it is streamed from an XML file back into memory.

Full Source VB.NET
Imports System.Xml.Serialization Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType) Dim readStream As FileStream = New FileStream("serialXML.xml", FileMode.Open) ds = CType(xmlSerializer.Deserialize(readStream), DataSet) readStream.Close() DataGridView1.DataSource = ds.Tables(0) End Sub End Class

Click here to download serialXML.xml

The XmlSerializer class supports the deserialization of complex object graphs, where one object may contain references to other objects. By appropriately annotating the .Net object classes with attributes such as XmlElement and XmlAttribute, developers can establish the necessary relationships and dependencies between objects for accurate deserialization.

By using XML deserialization, developers can seamlessly retrieve and utilize data stored in XML format within their .Net applications. This process simplifies the integration of external data sources or the exchange of data between different systems, ensuring efficient data processing and manipulation.

Conclusion

XML deserialization is a crucial process that allows developers to convert XML data into .Net objects. With the help of the XmlSerializer class, developers can effortlessly map XML elements to object properties and fields, enabling easy manipulation and utilization of the data within their .Net applications.