Net-informations.com
SiteMap  | About    

How to serialize a .Net Object to XML

Serialization of XML to common language runtime objects enables one to convert XML documents into a form where they are easier to process using conventional programming languages. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .

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




Public Class Form1
    Dim dt As DataTable
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim ds As 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"

        Dim serialWriter As StreamWriter
        serialWriter = New StreamWriter("serialXML.xml")
        Dim xmlWriter As New XmlSerializer(ds.GetType())
        xmlWriter.Serialize(serialWriter, ds)
        serialWriter.Close()
        ds.Clear()
    End Sub

    Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer)
        Dim dr As DataRow
        dr = dt.NewRow()
        dr("Product_ID") = pID
        dr("Product_Name") = pName
        dr("product_Price") = pPrice
        dt.Rows.Add(dr)
    End Sub
End Class

Click here to download serialXML.xml

 VB.NET XML - Related Contents