System.XML.Serialization Serialize a Class into an XML Document

Here is a simple code example showing how to take a VB Class object and use Xml.Serialization to turn it into an XML string. I had a little trouble finding this code because all the examples wanted to write the XML to disk using a StreamWriter… I needed it in memory as a string 

The resulting string looks like this:

 

Public Module Module1
 
    Public Class Product
        'this is our simple class of 'product' that we'll create
        Public Property ProductID As String
        Public Property ProductName As String
        Public Property cost As Double
    End Class
    Public Sub Main()
 
        'to make it a little more interesting, we'll serialize an Array of Product
        'declare the array
        Dim oProducts(1) As Product
        'declare the product class
        Dim oProduct As Product
 
        'create the first product
        oProduct = New Product
        oProduct.ProductID = "1"
        oProduct.ProductName = "Hammer"
        oProduct.cost = 5.12
        oProducts(0) = oProduct
 
        'create the second product
        oProduct = New Product
        oProduct.ProductID = "2"
        oProduct.ProductName = "Chisel"
        oProduct.cost = 9.99
        oProducts(1) = oProduct
 
        'Serialize the array to a string
        Dim sw As New IO.StringWriter
        Dim oSerializer As New Xml.Serialization.XmlSerializer(oProducts.GetType)
        oSerializer.Serialize(sw, (oProducts))
        MsgBox(sw.ToString)
 
    End Sub
End Module

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences