提问人:Andrew Truckle 提问时间:8/1/2023 更新时间:8/1/2023 访问量:57
如何使用 C# 将 24 小时时间序列化为 XML 或从 XML 序列化?
How can I serialize 24 hours time to / from XML using C#?
问:
我知道如何使用 C# 将“Date”序列化为 XML 或从 XML 序列化:
[XmlElement(DataType ="date")]
public DateTime LastInvited { get => _LastInvited; set => _LastInvited = value; }
private DateTime _LastInvited;
但是时间呢?
public DateTime CurrentMeetingTime { get => _CurrentMeetingTime; set => _CurrentMeetingTime = value; }
private DateTime _CurrentMeetingTime;
我知道有,但我只想在XML中有24小时的时间,没有秒。例如:[XmlElement(DataType ="time")]
<CurrentMeetingTime>10:00</CurrentMeetingTime>
<CurrentMeetingTime>14:00</CurrentMeetingTime>
答:
2赞
Swedish Zorro
8/1/2023
#1
您可以尝试添加一个表示时间的字符串属性。像这样的东西:
public class YourModel
{
[XmlIgnore] // This will prevent LastInvited from being serialized directly
public DateTime LastInvited { get; set; }
public string LastInvitedTime => LastInvited.ToString("HH:mm");
}
1赞
djv
8/1/2023
#2
这确实是绕过它的唯一方法,除非你只是把它当作一个字符串CurrentMeetingTime
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>
评论