Haegendoorn
New member
- Joined
- Apr 7, 2008
- Messages
- 4
- Programming Experience
- Beginner
Hi,
I have a question regarding xml (de)serialization. I have a class (person) with 3 properties: Name, birthdate and age. I want to do a quick test to save the data stored in my Person1 to disk using xml serialization.
This works ok, but when I want to increase the performance by ignoring the age property (which i can calculate from birthdate), using XmlIgnore(), I can not calculate this property at deserialization.
Which Event should i use to call the function calculateAge()?
My code:
Thanks in advance
Haegendoorn
I have a question regarding xml (de)serialization. I have a class (person) with 3 properties: Name, birthdate and age. I want to do a quick test to save the data stored in my Person1 to disk using xml serialization.
This works ok, but when I want to increase the performance by ignoring the age property (which i can calculate from birthdate), using XmlIgnore(), I can not calculate this property at deserialization.
Which Event should i use to call the function calculateAge()?
My code:
VB.NET:
Imports System.Runtime.Serialization
Imports System.Xml
Imports System.Xml.Serialization
Public Class Person
Public name As String
Public dateOfBirth As DateTime
<XmlIgnore()> Public age As Integer
Public Sub New(ByVal _name As String, ByVal _dateOfBirth As DateTime)
MyBase.New()
name = _name
dateOfBirth = _dateOfBirth
CalculateAge()
End Sub
Public Overrides Function ToString() As String
Return (name + (" was born on " _
+ (dateOfBirth.ToShortDateString + (" and is " _
+ (age.ToString + " years old.")))))
End Function
Private Sub CalculateAge()
age = (DateTime.Now.Year - dateOfBirth.Year)
If (dateOfBirth.AddYears((DateTime.Now.Year - dateOfBirth.Year)) > DateTime.Now) Then
age = (age - 1)
End If
End Sub
Public Sub New()
MyBase.New()
End Sub
End Class
Imports System.io
Imports System.Xml.Serialization
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Person1 As New Person(TextBox1.Text, CType(TextBox2.Text, Date))
Dim Person2 As New Person(T
Serialize(Person1)
End Sub
Sub Serialize(ByVal Person1 As Person)
Dim FS As FileStream = New FileStream("F:\Person1.xml", FileMode.Create)
Dim XS As XmlSerializer = New XmlSerializer(GetType(Person))
XS.Serialize(FS, Person1)
FS.Close()
Dim File1 As New FileInfo("F:\Person1.xml")
If File1.Exists Then
Deserialize()
End If
End Sub
Sub Deserialize()
Dim FS As FileStream = New FileStream("F:\Person1.xml", FileMode.Open)
Dim XS As XmlSerializer = New XmlSerializer(GetType(Person))
Dim Person2 As Person = CType(XS.Deserialize(FS), Person)
TextBox3.Text = Person2.name
TextBox4.Text = Person2.dateOfBirth.ToShortDateString
TextBox5.Text = Person2.age
FS.Close()
End Sub
End Class
Haegendoorn