XML Serialization

XML, serving as a versatile and widely adopted general-purpose tag-based language, provides a seamless and efficient means to transfer and store data across diverse applications. XML Serialization, on the other hand, refers to the process of converting a .NET object into an XML file or vice versa. This process enables the representation of complex .NET objects in an XML format, allowing for easy interchange and persistence of data.

XML serialization

During XML serialization, it is important to note that only the public properties and fields of an object are serialized. This means that private or internal members of an object are not included in the serialized XML representation. By selectively serializing public properties and fields, XML serialization offers a controlled and streamlined approach to representing and storing object data in XML format.

The following C# program shows how to serialize a Dataset to an XML disk file . Here we are using XmlSerializer Class for serialize the Dataset Object.

Full Source C#
using System; using System.Data; using System.Windows.Forms; using System.Xml.Serialization ; using System.IO; namespace WindowsApplication1 { public partial class Form1 : Form { DataTable dt; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); dt = new DataTable(); dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.Int32"))); dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32"))); fillRows(1, "product1", 9999); fillRows(2, "product2", 2222); fillRows(3, "product3", 3333); fillRows(4, "product4", 4444); ds.Tables.Add(dt); ds.Tables[0].TableName = "product"; StreamWriter serialWriter ; serialWriter = new StreamWriter("serialXML.xml"); XmlSerializer xmlWriter = new XmlSerializer(ds.GetType()); xmlWriter.Serialize(serialWriter, ds); serialWriter.Close(); ds.Clear(); } private void fillRows(int pID, string pName, int pPrice) { DataRow dr ; dr = dt.NewRow(); dr["Product_ID"] = pID; dr["Product_Name"] = pName; dr["product_Price"] = pPrice; dt.Rows.Add(dr); } } }

Click here to download serialXML.xml

Conclusion

The XML serialization process plays a critical role in scenarios where data needs to be transmitted or stored in a format that can be readily understood and processed by different systems and platforms. By converting .NET objects to XML files, or vice versa, XML serialization bridges the gap between object-oriented programming and XML-based data representation, facilitating seamless data exchange and interoperability across different applications and environments.