Search  
Wednesday, December 03, 2008 ..:: MINA's Blog ::.. Register  Login
 SiteMap Minimize

    

 Blog_List Minimize

      

 New_Blog Minimize

    

   Minimize
Keystroke IT

    

 Serializing and Deserializing XML into Object hierarchies Minimize
Location: BlogsMINA's Blog.NET Basics    
Posted by: Minas Casiou 10/4/2005
Serializing and Deserializing XML into Object hierarchies...One of those questions that's been asked a few times on the AusDotNet Mailing list...

Well, here goes...

In order to serialize your object hierarchy into XML, or conversely, if you want to have a nice & easy way to work with XML, convert it into an object hierarchy...you need to do a couple of things...

1)Best way is to start with an XSD Schema (like everything, Contract-First is the best way to go....) for your data. From this, you can use a number of tools to generate correctly annotated classes for you (with .NET, that just means class and property attributes). You can also start with your existing classes, although you'll need to annotate them appropriately (a bit of a pain). For an example of how to do it, generate some classes from an XSD, run them through XSD.exe or XSDObjectGenerator etc. & see what they spit out. If you couldn't be bothered, here's a couple of examples...

 

System.Xml.Serialization.XmlRootAttribute("ESBEnvelope", [Namespace]:="urn:keystroke-com-au:ESB:Envelope:ESBEnvelope:Version:1-0-3", IsNullable:=False)> _
_
Public Class ESBEnvelopeProvider : Inherits ESBEnvelope.EnvelopeBase
_
'Do not serialize this class...
_
Public Overrides ReadOnly Property XMLSchemaName() As String
'The XMLSchema name of the default document - this is one of the parameters used on the
'ESB server to construct the pipeline for the request
Get
If m_lNumDocs <= 0 Then
Return ""
Else
Return GetDocument(0).GetAsXMLDocument.DocumentElement.Name.Trim
End If
End Get
End Property
...

 

System.Xml.Serialization.XmlRootAttribute([Namespace]:="urn:keystroke-com-au:ESB:Envelope:ESBEnvelope:Version:1-0-3", IsNullable:=False)> _
_
Public Class attachment : Implements IAttachment
Protected sIndex As String
Protected sFilename As String
Protected sDescription As String
Protected sType As String
'
Public Property index() As String Implements IAttachment.index
Get
Return Trim(sIndex)
End Get
Set(ByVal Value As String)
sIndex = Trim(Value)
End Set
End Property
'
Public Property filename() As String Implements IAttachment.filename
Get
Return Trim(sFilename)
End Get
Set(ByVal Value As String)
sFilename = Trim(Value)
End Set
End Property
'
Public Property description() As String Implements IAttachment.description
Get
Return Trim(sDescription)
End Get
Set(ByVal Value As String)
sDescription = Trim(Value)
End Set
End Property
'
Public Property type() As String Implements IAttachment.type
Get
Return Trim(sType)
End Get
Set(ByVal Value As String)
sType = Trim(Value)
End Set
End Property
End Class

A couple of the tools you can use are:

  • XSD.exe - comes with .NET. Disadvantage is that it generates arrays rather than collections.
  • XSDObjectGenerator - developed by some of the Microsoft guys that were part of the original BizTalk JumpStart Kit. This is a good compromise between generated class attributes & methods. Some other tools will generate reams of code for each class, & whilst that may be useful for some scenarios, with large XSD's such as the ACORD OLife schema (~500k XSD), that means a lot of code.

Once you've got your classes, you can start populating them. When you want to turn them into XML, use something like the methods below.

Public Function Serialize(byval oObjectToSerialize As System.Object) As String
        Dim oSer As System.Xml.Serialization.XmlSerializer
        oSer = New XmlSerializer(oObjectToSerialize.GetType())
        Dim oMemStream As New MemoryStream
        Dim sw As New StreamWriter(oMemStream, New System.Text.UTF8Encoding)
        Dim sXML As String
        oSer.Serialize(sw, oObjectToSerialize)
        sXML = Encoding.UTF8.GetString(oMemStream.ToArray())
        oMemStream.Flush()
        oMemStream.Close()
        Return sXML
End Function

 When you want to DeSserialize the XML back into classes, you need to supply the XML string as well as the type of the parent object in the hierarchy.

Public Function DeSerialize(byval sXMLStringToDeSerialize As String, byval tType As Type) As Object
  'Deserialize to the original objects
  Dim sr As New StringReader(sXMLStringToDeSerialize)
  Dim x1 As Object
  Dim oSer As System.Xml.Serialization.XmlSerializer
  oSer = New XmlSerializer(tType)
  x1 = oSer.Deserialize(sr)
  Return x1
End Function

The above two methods are pretty much all you need (& you can pretty much halve the number of lines of code if you wish to reduce line count if you're one of those types...). I purposely leave it verbose as it aids in debugging & I'm not too fussed about how many lines of code are there...(Got over that when I stopped using C++  :(  ).

Here's a few neat little things you might want to know before you start though...

  1. With the XML Serializer, only public properties are serialized. WIth WCF, there's another serializer that can do private properties as well, but it's not the most Contract-First compliant serializer. For maximum portability, stick with the XML Serializer.
  2. The XMLIgnore attribute - specifies to not serialize that object (property, class etc.)
  3. If you want to write out a node based on a true/false condition...then there's a bit of taxonomy that the XML Serializer looks at to help you ger there. Basically, the naming convention MyPropertySpecified will write out a property called MyProperty if the Boolean property called MyPropertySpecified is set to true. If this value is set to false, then MyProperty will not be serialized.
  4. Deserializing Date nodes...If you have a Date node, then it can't be an empty string value in the XML. It must either have a valid date, or the node must not be present in the XML.

Other than that, the attribute details are in the examples above & in the online help etc.

 

With those few tips, happy Serializing/Deserializing your XML... :)

Permalink |  Trackback

Your name:
Title:
Comment:
Add Comment   Cancel 

  

 Text/HTML Minimize
Listed on BlogShares

      

 Search_Blog Minimize

    

 Blog_Archive Minimize

    

Copyright 2006 Keystroke IT   Terms Of Use  Privacy Statement
DotNetNuke® is copyright 2002-2008 by Perpetual Motion Interactive Systems Inc.