_LastInvited; set => _Las" /> _LastInvited; set => _Las" /> _LastInvited; set => _Las"/>

How can I serialize 24 hours time to / from XML using C#?

72 Views Asked by At

I know how to serialize a "Date" to / from XML using C#:

[XmlElement(DataType ="date")]
public DateTime LastInvited { get => _LastInvited; set => _LastInvited = value; }
private DateTime _LastInvited;

But what about time?

public DateTime CurrentMeetingTime { get => _CurrentMeetingTime; set => _CurrentMeetingTime = value; }
private DateTime _CurrentMeetingTime;

I know that there is [XmlElement(DataType ="time")] but I only want to have 24 hour times with no seconds in the XML. Eg:

  • <CurrentMeetingTime>10:00</CurrentMeetingTime>
  • <CurrentMeetingTime>14:00</CurrentMeetingTime>
2

There are 2 best solutions below

0
Swedish Zorro On BEST ANSWER

You could try to add a string property that represents the time. Something like this:

public class YourModel
{

    [XmlIgnore] // This will prevent LastInvited from being serialized directly
    public DateTime LastInvited { get; set; }
 
    public string LastInvitedTime => LastInvited.ToString("HH:mm");
}
0
djv On

This is really the only way to get around it unless you just treat CurrentMeetingTime as a string

public class Model
{
    [XmlElement(DataType = "date")]
    public DateTime LastInvited { get => _LastInvited; set => _LastInvited = value; }
    private DateTime _LastInvited;

    [XmlElement("CurrentMeetingTime"), Browsable(false)]
    public String CurrentMeetingTimeString { get => $"{CurrentMeetingTime:HH:mm}"; set => CurrentMeetingTime = DateTime.Parse(value); }
    [XmlIgnore]
    public DateTime CurrentMeetingTime;
}
<Model xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <LastInvited>2023-08-01</LastInvited>
  <CurrentMeetingTime>09:52</CurrentMeetingTime>
</Model>