-
Apr 2nd, 2015, 09:03 AM
#1
Thread Starter
New Member
serialize object/expandoobject/dynamicobject/anonymous type object to XML
Hello, I have some trouble on how I should start on this one:
I want to create a function that can handle all of the above types and serilize them, so far I have this to serilize a normal object:
Code:
Public Function SerializeToXmlDocument(ByVal ObjInput As Object, Optional ByVal ParentNodeName As String = "") As XmlDocument
Dim ser As New XmlSerializer(ObjInput.GetType, New XmlRootAttribute(ParentNodeName))
Dim xd As XmlDocument = Nothing
Using memStm As New MemoryStream()
ser.Serialize(memStm, ObjInput)
memStm.Position = 0
Dim settings As New XmlReaderSettings()
settings.IgnoreWhitespace = True
Using xtr = XmlReader.Create(memStm, settings)
xd = New XmlDocument()
xd.Load(xtr)
End Using
End Using
Return xd
End Function
Like how to parse them to the function and thereafter detect which is which and do the different procedure for each case.
And if you have some vb.net code to serilize expandoobject or dynamicobject to XML, please feel free to share as I think the only solution for this is to handle each type differently.
-
Apr 3rd, 2015, 08:12 AM
#2
Re: serialize object/expandoobject/dynamicobject/anonymous type object to XML
Hi,
You need to look into Using Generics in the .NET Framework. Generics allow you pass different types to a Routine and then deal with them as per the Type that was passed. As a quick Example, I use two regular Extension Methods in my regular coding to Serialize and Deserialize different object types into a JSON Structure. i.e:-
vb.net Code:
<Extension()> Public Function SerializeToJSON(Of T)(ByVal dataToSerialize As T) As String Dim jsonTool As New JavaScriptSerializer Return jsonTool.Serialize(dataToSerialize) End Function <Extension()> Public Function DeserializeFromJSON(Of T)(ByVal dataToDeserialize As String, ByVal typeToDeserializeTo As T) As T Dim jsonTool As New JavaScriptSerializer Return jsonTool.Deserialize(Of T)(dataToDeserialize) End Function
Even though this is Not XML this does demonstrate the principle of Serializing and Deserializing any object type using Generics.
I will now leave this to you to get working with XML rather than JSON.
Hope that helps.
Cheers,
Ian
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|