Stephen,
By the time the constructor runs the object's memory is already created, so
no the constructor cannot deserialize itself.
I would recommend you add a Shared method to the class that does the
deserialization for you..
Something like:
> Dim NewObject As ObjectType = ObjectType.FromXml("<?xml
version=""1.0""
>
encoding=""UTF-8""?><ObjectType><SomeValue>Hello.</SomeValue></ObjectType>")
> Public Class ObjectType
> Public SomeValue As System.String
>
> Public Shared Sub FromXml(ByVal xml As System.String) As
ObjectType
> Dim r As New System.IO.StringReader(xml)
> Dim d As New
System.XML.Serialization.XmlSerializer(GetType(ObjectType))
I would then consider adding a "matching" "serialize" method to the class
Public Function ToXml() As String
Dim d as XmlSerializer(...)
Hope this helps
Jay
"Stephen Travis" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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
>
>
>
>
|