.NET 如何将 TimeSpan 序列化为 XML(不是同一个问题!)

标签 .net xml-serialization

我的问题是 How to serialize a TimeSpan to XML 的延续

我有很多 DTO 对象通过 TimeSpan周围的实例。使用原始帖子中描述的 hack 有效,但它要求我在每个 DTO 中为每个 TimeSpan 重复相同的大量代码。属性(property)。

所以,我带来了以下包装类,它是 XML 可序列化的就好了:

#if !SILVERLIGHT
[Serializable]
#endif
[DataContract]
public class TimeSpanWrapper
{
  [DataMember(Order = 1)]
  [XmlIgnore]
  public TimeSpan Value { get; set; }

  public static implicit operator TimeSpan?(TimeSpanWrapper o)
  {
    return o == null ? default(TimeSpan?) : o.Value;
  }

  public static implicit operator TimeSpanWrapper(TimeSpan? o)
  {
    return o == null ? null : new TimeSpanWrapper { Value = o.Value };
  }

  public static implicit operator TimeSpan(TimeSpanWrapper o)
  {
    return o == null ? default(TimeSpan) : o.Value;
  }

  public static implicit operator TimeSpanWrapper(TimeSpan o)
  {
    return o == default(TimeSpan) ? null : new TimeSpanWrapper { Value = o };
  }

  [JsonIgnore]
  [XmlElement("Value")]
  [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
  public long ValueMilliSeconds
  {
    get { return Value.Ticks / 10000; }
    set { Value = new TimeSpan(value * 10000); }
  }
}

问题是它生成的 XML 看起来像这样:
<Duration>
  <Value>20000</Value>
</Duration>

而不是自然
<Duration>20000</Duration>

我的问题是我可以既“吃蛋糕又吃蛋糕”吗?意思是,享受所描述的 hack,而不会用相同的重复代码将所有 DTO 弄得一团糟,而且还有一个自然的 XML?

谢谢。

最佳答案

更改 [XmlElement("Value")][XmlText] .然后,如果你序列化这样的东西:

[Serializable]
public class TestEntity
{
    public string Name { get; set; }
    public TimeSpanWrapper Time { get; set; }
}

你会得到这样的 XML:
<TestEntity>
    <Name>Hello</Name>
    <Time>3723000</Time>
</TestEntity>

关于.NET 如何将 TimeSpan 序列化为 XML(不是同一个问题!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7483233/

相关文章:

.net - 虚拟泛型方法调用的静态分析

.net - Login failed for user "xxx"Failed to open the explicitly specified database解决方法

c# - IIS 托管 WCF 与 SSL 安全 -"The HTTP request was forbidden with client authentication scheme ' 匿名'"错误

c# - xml 序列化 - 删除命名空间

c# - XML 将 null 属性反序列化为零和 false

c# - Winforms 用户控件自定义事件

c# - 如何将属性从一个 .net 对象复制到另一个

c# - XmlDocument.Load(xml) 从 XmlSerializer 序列化代码生成“无根元素”错误

java - jaxb设置字符串类型

java - 将数据库表结果隐藏为 XML - 如何生成 XML 文档