How to: Serialize Using XmlSerializer (Visual Basic)

This topic shows an example that serializes and deserializes using XmlSerializer.


The following example creates a number of objects that contain XElement objects. It then serializes them to a memory stream, and then deserializes them from the memory stream.

Imports System  
Imports System.Xml  
Imports System.Xml.Linq  
Imports System.IO  
Imports System.Runtime.Serialization  
Imports System.Xml.Serialization  
Public Class XElementContainer  
    Public member As XElement  
    Public Sub XElementContainer()  
        member = XLinqTest.CreateXElement()  
    End Sub  
    Overrides Function ToString() As String  
        Return member.ToString()  
    End Function  
End Class  
Public Class XElementNullContainer  
    Public member As XElement  
    Public Sub XElementNullContainer()  
        member = Nothing  
    End Sub  
End Class  
Public Class XLinqTest  
    Shared Sub Main()  
        Test(Of XElementNullContainer)(New XElementNullContainer())  
        Test(Of XElement)(CreateXElement())  
        Test(Of XElementContainer)(New XElementContainer())  
    End Sub  
    Public Shared Function CreateXElement() As XElement  
        Dim ns As XNamespace = ""  
        Return New XElement(ns + "aw")  
    End Function  
    Public Shared Sub Test(Of T)(ByRef obj)  
        Using stream As New MemoryStream()  
            Dim s As XmlSerializer = New XmlSerializer(GetType(T))  
            Console.WriteLine("Testing for type: {0}", GetType(T))  
            s.Serialize(XmlWriter.Create(stream), obj)  
            stream.Seek(0, SeekOrigin.Begin)  
            Dim o As Object = s.Deserialize(XmlReader.Create(stream))  
            Console.WriteLine("  Deserialized type: {0}", o.GetType())  
        End Using  
    End Sub  
End Class  

This example produces the following output:

Testing for type: XElementNullContainer  
  Deserialized type: XElementNullContainer  
Testing for type: System.Xml.Linq.XElement  
  Deserialized type: System.Xml.Linq.XElement  
Testing for type: XElementContainer  
  Deserialized type: XElementContainer  

See also