Ta strona korzysta z ciasteczek cookies Rozumiem.

XML serialization in VB.Net – simple example

16 października 2017, Kasia Ziomek-Zdanowicz

gotowe rozwiązania, VB.Net


Some useful terms

Serialization is a process of converting an object into a form that can be easily transfered, for example using HTTP. The shallow serialization converts the public properties. The deep serialization converts both public and private properties. Deserialization is the reverse of serialization i.e. reconstructiong the object from the stream. There are two main ways to do serialization in VB.Net: XML and binary. In this article I describe how to do the XML serialization in VB.Net.

XML serialization in VB.Net

XML serialization in VB.Net is provided by the XmlSerializer and the the serialize and deserialize methods. XmlSerializer is System.Xml.Serialization. XmlSerializer performs shallow serialization i.e. serializes only the public fields and property values of an object into an XML stream. It includes only the data itself and the structure of the classes, it does not include type information.

Example of XML serialization in VB.Net


In the example I serialize collection of Book objects. The main steps I perform are:

  1. create a class Book,
  2. create a class Books,
  3. create a class XmlControl that will perform serialization,
  4. run a procedure that creates two Book objects, adds them to Books collection and performs the serialization of the Books collection.

Step 1. Create a class Book

The class Book is a standard, simple class with constructor and two properties: Title and Author. There is nothing unusal in this class so I’m not going to discuss it in details.

Create a class Book

Public Class Book

 Private _title As String
 Private _author As String

 Public Sub New()
 End Sub

 Public Sub New(title As String, author As String)
   _title = title
   _author = author
 End Sub
 'property Title
 Property Title() As String
   Return _title
  End Get

  Set(ByVal Value As String)
   _title = Value
  End Set
 End Property

 'property Author
 Property Author As String
   Return _author
  End Get

  Set(ByVal Value As String)
   _author = Value
  End Set
 End Property

End Class

Step 2. Create a class Books

The class Books implements the ICollection interface. Therefore, it has to meet some requirements if we want to serialize it to XML:

  • The class must have a public Item indexed property that takes an Integer,
  • The class must have a public Count property of type Integer,
  • The class must implement a public add method that takes a single parameter,
  • The parameter to the add method must be of the same type as is returned from the Item property.

Values to be serialized are retrieved from the indexed Item property. It means that only the collection contained by the class is serialized. Any public properties or fields added to the class will not be serialized.

Create a class Books

Imports System.Collections

Public Class Books
 Implements ICollection
 Public Books As String
 Private _books As ArrayList = New ArrayList()

'public Item indexed property that takes an Integer
 Default Public ReadOnly Property Item(index As Integer) As Book
    Return CType(_books(index), Book)
   End Get
 End Property

'public Count property of type Integer
 Public ReadOnly Property Count() As Integer _
  Implements ICollection.Count
   Count = _books.Count
  End Get
 End Property

'public add method that takes a single parameter
'parameter of the same type as is returned from the Item property (Book)
 Public Function Add(newBook As Book) As Integer
  Return _books.Count
 End Function

'implement other members required by ICollection interface
 Public Sub CopyTo(a As Array, index As Integer) _
  Implements ICollection.CopyTo
   _books.CopyTo(a, index)
 End Sub

 Public Function GetEnumerator() As IEnumerator _
  Implements IEnumerable.GetEnumerator
   Return _books.GetEnumerator()
 End Function

 Public ReadOnly Property IsSynchronized() As Boolean _
  Implements ICollection.IsSynchronized
    Return False
   End Get
 End Property

 Public ReadOnly Property SyncRoot() As Object _
  Implements ICollection.SyncRoot
    Return Me
   End Get
 End Property

End Class

Step 3. Create a class XmlControl

Class XmlControl performs the serialization. The class uses:

Create a class XmlControl

Imports System.IO
Imports System.Xml.Serialization
Imports System.Xml
Imports System.Text

Public Class XmlControl

 Public Shared Function ToXml(ByVal Obj As Object, ByVal ObjType As System.Type) As String

  Dim XML As String

  'create new MemoryStream and XmlTextWriter that uses this memory stream and UTF8 encoding
  Dim MemStream As MemoryStream = New MemoryStream()
  Dim XmlWriter As XmlTextWriter = New XmlTextWriter(MemStream, Encoding.UTF8)

  'create new XmlSerializer and serialize the stream containing the XML data
  Dim Serializer As XmlSerializer = New XmlSerializer(ObjType)
  Serializer.Serialize(XmlWriter, Obj)

  'get from the MemStream the substring that starts with < and ends wiht >
  XML = Encoding.UTF8.GetString(MemStream.GetBuffer())
  XML = Xml.Substring(Xml.IndexOf("<"))
  XML = XML.Substring(0, (XML.LastIndexOf(">") + 1))

  'close the MemoryStream and XmlTextWriter

  Return XML

 End Function
End Class

Step 4. Run procedure that creates Book objects, Books collection and performs the serialization

Finally, I run the procedure that creates two Book objects, Books collection and performs the serialization. The result of serialization is presented below the code.

Procedure that creates Book objects, Books collection and performs the serialization

Sub Main()

 'create Book objects
 Dim FirstBook As New Book With {
  .Author = "Charles Dickens",
  .Title = "A Christmas Carol"}

 Dim SecondBook As New Book With {
  .Author = "Agatha Christie",
  .Title = "Murder on the Orient Express"}

 'create Books collection with Book objects
 Dim BooksCollection As New Books

 'serialize the Books collection
 Dim XML As New XmlControl
 Dim BooksString = XML.ToXml(BooksCollection, GetType(Books))


End Sub

Result of serialization (formatted to be more readable)

<?xml version="1.0" encoding="utf-8"?>

<ArrayOfBook xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <Title>A Christmas Carol</Title>
  <Author>Charles Dickens</Author>

  <Title>Murder on the Orient Express</Title>
  <Author>Agatha Christie</Author>


Additional resources

If you want to read more about the XML serialization in VB.Net have a look at the articles: Introduction to XML serialization and Examples of XML serialization.


Jeszcze nikt nie skomentował tego wpisu. 

Napisz pierwszy komentarz.

Napisz komentarz

Twój adres email nie zostanie opublikowany.

Wszystkie pola są wymagane.