How to serialize an object to XML by using Visual Basic .NET

The .NET Framework provides the System.Xml.Serialization namespace to serialize an object to XML.

Here’s a full example:

Imports System
Imports System.Collections.Generic

Public Class Test
	Public Shared Sub Main()
        Dim p1 = New Product() With {.Name = "Hosting", .Price = 9.99}
        Dim p2 = New Product() With {.Name = "Domain", .Price = 9.99}

        Dim c = New Customer With {
        .Name = "Dot",
        .Surname = "Maui",
        .Age = 33,
        .Products = New List(Of Product)(New Product() {p1, p2})}

        Dim x As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(c.GetType)
        Dim string_writer As New System.IO.StringWriter
        Dim ns As New System.Xml.Serialization.XmlSerializerNamespaces
        x.Serialize(string_writer, c, ns)

	End Sub
End Class

Public Class Customer
    Public Name As String
    Public Surname As String
    Public Age As Integer
    Public Products As List(Of Product)
End Class

Public Class Product
    Public Name As String
    Public Price As Decimal
End Class

The result will be:

<?xml version="1.0" encoding="utf-16"?>
<Customer xmlns:xsd="" xmlns:xsi="">

Leave a Comment

Your email address will not be published. Required fields are marked *