在C#中反序列化自定义XML数据类型

jim*_*nes 5 c# xml serialization types

我有一个我无法控制的xml文档,它有一个带有自定义数据类型的元素

<foo>
   <time type="epoch_seconds">1295027809.26896</time>
</foo>
Run Code Online (Sandbox Code Playgroud)

我想有一个类可以自动转换为Epoch秒:

[Serializable]
public class Foo
{
      public Foo()
      {
      }

      public EpochTime Time { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法定义一个EpochTime类,以便XML序列化器知道在查找XML时使用它type="epoch_time"?如果是这样,我该如何设置WriteXmlReadXml执行此操作?

Mar*_*ell 4

正常的方法是简单地用一个行为如您所期望的属性来填充它:

public class EpochTime {
    public enum TimeType {
       [XmlEnum("epoch_seconds")] Seconds
    }
    [XmlAttribute("type")] public TimeType Type {get;set;}
    [XmlText] public string Text {get;set;}

    [XmlIgnore] public DateTime Value {
        get { /* your parse here */ }
        set { /* your format here */ }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,你需要:

[XmlElement("time")]
public EpochTime Time { get; set; }
Run Code Online (Sandbox Code Playgroud)

这是 xml 的完整示例:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
static class Program
{
    static void Main()
    {
        Foo foo;
        var ser = new XmlSerializer(typeof(Foo));
        using (var reader = XmlReader.Create(new StringReader(@"<foo>
   <time type=""epoch_seconds"">1295027809.26896</time>
</foo>")))
        {
            foo = (Foo)ser.Deserialize(reader);
        }
    }
}
public class EpochTime
{
    public enum TimeType
    {
        [XmlEnum("epoch_seconds")]
        Seconds
    }
    [XmlAttribute("type")]
    public TimeType Type { get; set; }
    [XmlText]
    public string Text { get; set; }
    private static readonly DateTime Epoch = new DateTime(1970, 1, 1);
    [XmlIgnore] public DateTime Value
    {
        get
        {
            switch (Type)
            {
                case TimeType.Seconds:
                    return Epoch + TimeSpan.FromSeconds(double.Parse(Text));
                default:
                    throw new NotSupportedException();
            }
        }
        set {
            switch (Type)
            {
                case TimeType.Seconds:
                    Text = (value - Epoch).TotalSeconds.ToString();
                    break;
                default:
                    throw new NotSupportedException();
            }
        }
    }
}
[XmlRoot("foo")]
public class Foo
{
    public Foo()
    {
    }

    [XmlElement("time")]
    public EpochTime Time { get; set; }
}
Run Code Online (Sandbox Code Playgroud)