In part one, two and three we looked at how we can take a normal .net object and serialize it out to XML, along the way we also took a look at some of the XML attributes we can apply to our property and class declaration. In this final part of the series we will take a look at how we can read the XML then de-serialize it back into our .net object.
The .net framework makes de-serialising back into a .net object straightforward, in the below example we will de-serialize the employee XML file that we serialized in part three back into the employee class that we also defined in part three, below is a recap on what the XML file looks like.
<?xml version="1.0" encoding="utf-8"?> <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <FirstName>Joe</FirstName> <FamilyName>Bloggs</FamilyName> <DateOfBirth>1995-03-02T00:00:00</DateOfBirth> <Occupation>Student</Occupation> <ListOfAddresses> <Address> <AddressType>Home</AddressType> <HouseNumberOrName>437</HouseNumberOrName> <AddressLine1>Mayfair Road</AddressLine1> <AddressLine2>London</AddressLine2> <Country>UK</Country> <PostalCode>SW1</PostalCode> </Address> <Address> <AddressType>PreivousAddress</AddressType> <HouseNumberOrName>Pickett House</HouseNumberOrName> <AddressLine1>Any Old Road</AddressLine1> <AddressLine2>London</AddressLine2> <Country>UK</Country> <PostalCode>SW1</PostalCode> </Address> </ListOfAddresses> <Salary>33300</Salary> <TaxCode>999L</TaxCode> <LastPayDate>2014-08-29T00:00:00</LastPayDate> </Employee>
For a recap on what the employee class looks like check part three.
Now for reading the XML and de-serializing into our employee object, first we create a new instance of a XMLSerializer and tell it what type it will be handling which in this case will be our employee class. Next we create a new file stream object that will open and read our XML file from disk which we will then use in our XMLReader. The last thing we need to do is assign the output from the XMLSerializer and type cast it to employee.
Dim oEmployee = New Employee Try Dim sFileName As String = "MyNewXMLFile.XML" Dim mySerializer As New XmlSerializer(oEmployee.GetType) Using myFileStream As FileStream = New FileStream(sFileName, FileMode.Open) Dim reader As XmlReader = XmlReader.Create(myFileStream) oEmployee = CType(mySerializer.Deserialize(reader), Employee) End Using mySerializer = Nothing Catch ex As Exception End Try
Once the above code has ran the oEmployee object will now hold the de-serliazed XML and the XMLSerialzer has no problem with handling our inherited class or our list of addresses property as you will see from the screen shot below which shows the member information for our object after the reader code has ran,
Further information on the XMLSerialzer class can be found on the MSDN website http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx