.NET如何序列化时间跨度为XML(不一样的问题!)跨度、时间、序列化、问题

2023-09-04 11:41:07 作者:我比钻石还耀眼

我的问题是一个延续 .NET中如何序列化一个时间跨度以XML

我有很多它周围通过时间跨度实例DTO对象。采用在原岗位工作描述的黑客,但它要求我重复code在每个相同的体积和每一个DTO为每个时间跨度属性。

I have many DTO objects which pass TimeSpan instances around. Using the hack described in the original post works, but it requires me to repeat the same bulk of code in each and every DTO for each and every TimeSpan property.

于是,我就用下面的包装类,这是XML序列化就好了:

So, I came with the following wrapper class, which is XML serializable just fine:

#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看起来像这样:

The problem is that the XML it produces looks like so:

<Duration>
  <Value>20000</Value>
</Duration>

代替天然

<Duration>20000</Duration>

我的问题是,我可以既吃的蛋糕,把它整体?含义,享受所描述的黑客不会弄乱所有的DTO具有相同的重复code,但有一个自然的XML?

My question is can I both "eat the cake and have it whole"? Meaning, enjoy the described hack without cluttering all the DTOs with the same repetitive code and yet have a natural looking XML?

感谢。

推荐答案

修改 [的XmlElement(值)] [XMLTEXT] 。然后,如果你序列化是这样的:

Change [XmlElement("Value")] to [XmlText]. Then, if you serialize something like this:

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

您会得到这样的XML:

You will get XML like this:

<TestEntity>
    <Name>Hello</Name>
    <Time>3723000</Time>
</TestEntity>