如何在C#中对24小时制时间进行XML序列化与反序列化?
C# XML序列化DateTime为无秒数的24小时制时间
默认的[XmlElement(DataType = "time")]会遵循XML Schema标准输出带秒(甚至毫秒)的时间格式,无法直接得到10:00这种无秒的24小时制格式。你可以通过代理属性的方式实现需求,具体步骤如下:
- 给原DateTime属性添加
[XmlIgnore]特性,让它不参与XML序列化:
using System.Xml.Serialization; using System.Globalization; // 忽略原DateTime属性的序列化 [XmlIgnore] public DateTime CurrentMeetingTime { get => _CurrentMeetingTime; set => _CurrentMeetingTime = value; } private DateTime _CurrentMeetingTime;
- 创建一个字符串类型的代理属性,指定XML元素名称为原属性名,在get方法中按
HH:mm格式输出时间,set方法中解析字符串还原为DateTime:
// 代理属性,负责XML的序列化与反序列化 [XmlElement("CurrentMeetingTime")] public string CurrentMeetingTimeString { get => _CurrentMeetingTime.ToString("HH:mm", CultureInfo.InvariantCulture); set => _CurrentMeetingTime = DateTime.ParseExact(value, "HH:mm", CultureInfo.InvariantCulture); }
说明
HH:mm格式符对应24小时制的小时(00-23)和分钟,不会包含秒数;- 使用
CultureInfo.InvariantCulture可以避免因系统区域设置导致的格式解析错误; - 反序列化时,
ParseExact能严格按照指定的HH:mm格式解析XML中的时间字符串,还原为DateTime对象(日期部分会默认设为当前日期,若需要指定固定日期可自行调整)。
内容的提问来源于stack exchange,提问作者Andrew Truckle
相关产品推荐
相关产品推荐

