S
Stephen Travis
I would like an Object's Constructor to create itself by deserializing from XML. Is there an easy way to do this?
I could use a separate function to deserialize to an object but I'd like to do it in the Constructor. Here's an example of what I
mean;
Private Sub Page_Load()
' Sample XML:
' <?xml version=""1.0"" encoding=""UTF-8""?>
' <ObjectType>
' <SomeValue>Hello.</SomeValue>
' </ObjectType>
Dim NewObject As ObjectType = New ObjectType("<?xml version=""1.0""
encoding=""UTF-8""?><ObjectType><SomeValue>Hello.</SomeValue></ObjectType>")
End Sub
Public Class ObjectType
Public SomeValue As System.String
Public Sub New(ByVal xml As System.String)
Dim r As New System.IO.StringReader(xml)
Dim d As New System.XML.Serialization.XmlSerializer(GetType(ObjectType))
'
' this works but is not very elegant since every property must be set manually.
'
Dim NewMe As New ObjectType
NewMe = d.Deserialize(r)
Me.SomeValue = NewMe.SomeValue
'
' this doesn't work but it's what I'm looking for.
'
Me = d.Deserialize(r)
End Sub
Public Sub New()
End Sub
End Class
I could use a separate function to deserialize to an object but I'd like to do it in the Constructor. Here's an example of what I
mean;
Private Sub Page_Load()
' Sample XML:
' <?xml version=""1.0"" encoding=""UTF-8""?>
' <ObjectType>
' <SomeValue>Hello.</SomeValue>
' </ObjectType>
Dim NewObject As ObjectType = New ObjectType("<?xml version=""1.0""
encoding=""UTF-8""?><ObjectType><SomeValue>Hello.</SomeValue></ObjectType>")
End Sub
Public Class ObjectType
Public SomeValue As System.String
Public Sub New(ByVal xml As System.String)
Dim r As New System.IO.StringReader(xml)
Dim d As New System.XML.Serialization.XmlSerializer(GetType(ObjectType))
'
' this works but is not very elegant since every property must be set manually.
'
Dim NewMe As New ObjectType
NewMe = d.Deserialize(r)
Me.SomeValue = NewMe.SomeValue
'
' this doesn't work but it's what I'm looking for.
'
Me = d.Deserialize(r)
End Sub
Public Sub New()
End Sub
End Class