Now let's look at this from the opposite angle. We've just seen how to serialize
an object into an XML file and save it to disk, but now suppose we already
had an XML file saved and wanted to use it to instantiate an object. In the
downloadable code found at the end of this article, you will find a file
called, ned.xml
. We’re going to use that XML file to create a Person
object. Its contents look like this:
<?xml version="1.0" encoding="utf-8"?>
<Class_Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Property_Age>47</Property_Age>
<Property_Name>Ned Nederlander</Property_Name>
</Class_Person>
You'll notice that this XML document has exactly the same structure as the XML file that we wrote to disk a moment ago but the data it contains is, of course, different. Now put on your wicked mad scientist grins and look at the code required to bring this beast of an object to life:
dim oNed as Person
dim oStmR as StreamReader
'Pull in contents of an object serialized into an XML file
'and deserialize it into an object
oStmR = new StreamReader(Server.MapPath("ned.xml"))
oNed = oXS.Deserialize(oStmR)
oStmR.Close()
'Display property values
Response.Write("Hello() = " & oNed.Hello() & "<br />")
Response.Write("Goodbye() = " & oNed.Goodbye() & "<br />")
Before anything else, we declare a Person
object and StreamReader
object. Next,
we create an instance of the StreamReader
object and feed it the stored XML
file. Then we instantiate the Person
object by calling the Deserialize()
method of the XMLSerializer
object. This method uses the StreamReader
object
to read the contents of the XML file and then instantiates an object whose
state matches that described in the XML file. Finally, we close up the StreamReader
object and then output the results of the newly created object's Hello()
and Goodbye()
methods just to prove that it was successfully created. It's
just like that instant oatmeal Mom used to make.
Note: Something important to remember is that when an object is instantiated through Deserialization, its constructor is not called. Just keep that in mind if you plan on doing this with any objects which are very dependent on their constructors performing some crucial function.
Comments