Apr
4
Written by:
Steve Gray
4/4/2011 5:45 PM
Here is a simple code example showing how to take a VB Class object and us 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:

Code Snippet
- 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
As always, I welcome your comments!