Saturday, January 28, 2012

Serializing and DeSerializing Objects as XML in VB.NET

It was unbelievably difficult to find a working example where the XML could come from a web server on a different domain. So, I guess I will share with the world how I managed to make it work.

Serialize List of Objects to XML
(Web Server)

Dim xml As String = ""
Dim mstr_XmlFilePath As String = "/myFolder/myFile.xml"
Dim mstr_ServerXmlFilePath As String = Server.mapPath(mstr_XmlFilePath)
Dim obj_objMyObject As New objMyObject
Dim lst_objMyObject As List(Of objMyObject) = [[***populate object***]]


Dim ser As XmlSerializer
ser = New XmlSerializer(GetType(System.Collections.Generic.List(Of objMyObject)))
Dim memStream As New MemoryStream
Dim xmlWriter As New XmlTextWriter(memStream, Encoding.UTF8)
xmlWriter.Namespaces = True
ser.Serialize(xmlWriter, lst_objMyObject)

xml = Encoding.UTF8.GetString(memStream.GetBuffer())
xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)))
xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1))

My.Computer.FileSystem.WriteAllText(XmlFilePath, xml, False)

Catch ex As Exception
Throw New Exception("Error calling ToXML. " & ex.GetBaseException.ToString)
End Try

DeSerialize List of Objects from XML (Client or Cross-Domain Web Server)

str_XmlFullFilePath = "myURL" + mstr_XmlFilePath
Dim objListFromXml As New List(Of objMyObject)

Dim reader As System.Xml.XmlReader
reader = System.Xml.XmlReader.Create(str_XmlFullFilePath)

Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(System.Collections.Generic.List(Of objMyObject)))
objListFromXml = CType(mySerializer.Deserialize(reader), System.Collections.Generic.List(Of objMyObject))

'don't do anything. If error occurs, return an empty object
End Try

I may have some typos above. I replaced all my variables with more generic ones.


Anonymous said...

Thanks dude this worked perfectly for serializing lists and sending over a TCP/IP connection.

Leslie Lim said...

Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.