Hello I have problem with deserialize xml
First I have class like that
public class ReportsViewModel
{
private DateTime fromDateTime;
[XmlIgnore]
public DateTime FromDateTime
{
get { return fromDateTime; }
set
{
fromDateTime = value;
}
}
[XmlElement]
public int FromDateTimeCal
{
get
{
return fromDateTime.Subtract(DateTime.Today).Days;
}
set
{
var a = fromDateTime.Subtract(DateTime.Today).Days;
a = value;
}
}
private DateTime toDateTime;
[XmlIgnore]
public DateTime ToDateTime
{
get { return toDateTime; }
set
{
toDateTime = value;
}
}
[XmlElement]
public int ToDateTimeCal
{
get
{
return ToDateTime.Subtract(DateTime.Today).Days;
}
set
{
var a = ToDateTime.Subtract(DateTime.Today).Days;
a = value;
}
}
}
And then I serialize them
ReportsViewModel reportVM = new ReportsViewModel();
reportVM.FromDateTime = new DateTime(2019, 02, 18);
reportVM.ToDateTime = new DateTime(2019, 02, 22);
using (StreamWriter sw = new StreamWriter(@"D:\Temp\Report.xml"))
{
XmlSerializer xml = new XmlSerializer(typeof(ReportsViewModel));
xml.Serialize(sw, reportVM);
}
Now I get XML file that contain only FromDateTimeCal and ToDateTimeCal
but the problem begin when I deserialize them.
I using deserialize with ReportViewModel class
using (StreamReader sw = new StreamReader(@"D:\Temp\Report.xml"))
{
XmlSerializer xml = new XmlSerializer(typeof(ReportsViewModel));
ReportsViewModel reportVM = (ReportsViewModel)xml.Deserialize(sw);
reportVM.Dump();
reportVM.FromDateTimeCal.Dump();
reportVM.ToDateTimeCal.Dump();
}
It didn't work. I guess the problem is FromDateTime and ToDateTime property wasn't set.
Can I serialize and deserialize with the same class?
FromDateTimeCalto do? I looked at it but can't understand what you wanted to achieve (as it really just fancy way to do absolutely noting)... Clearly that code does not setfromDateTime... did you wanted it to?FromDateCalandToDateCalis used for calculation result ofFromDateTimeand ToDate and I want onlyFromDateCalandToDateCalare in xml fileFromDateTimeCal, applies that to setter of your property, in which variableais assigned and its lost when execution leaves the scope, same happens forToDateTimeCal, alsoFromDateTimeandToDateTimewill never be set. This code will always do serialization only, deserialization will not be possible, also even if you changed bothcalsetters to compute and set value toFromDateTimeorToDateTime, it always hasDateTime.Todaywhich keeps changing and the data might be valid only for a month at max.