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)

        Console.Write(string_writer.ToString())
	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="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Name>Dot</Name>
  <Surname>Maui</Surname>
  <Age>33</Age>
  <Products>
    <Product>
      <Name>Hosting</Name>
      <Price>9.99</Price>
    </Product>
    <Product>
      <Name>Domain</Name>
      <Price>9.99</Price>
    </Product>
  </Products>
</Customer>

Leave a Comment

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