【问题标题】:How to deserialize XML attribute of type long to UTC DateTime?如何将 long 类型的 XML 属性反序列化为 UTC DateTime?
【发布时间】:2011-02-23 09:56:58
【问题描述】:

theseanswers之后,我决定使用xsd.exeXmlSerializer作为解析XML的最简单方法。

但我想要一些改进:

  1. 我的首要要求是将MyRoot.Time 类型从long 更改为DateTime。使用DateTime.FromFileTimeUtcnew DateTime可以通过代码轻松实现,但是可以直接通过XmlSerializer来实现吗?
  2. 我能否将MyRoot.Children 类型更改为更复杂的类型,例如Dictionary<string,Tuple<int,ChildState>>

我的 XML:

<Root timeUTC="129428675154617102">
    <Child key="AAA" value="10" state="OK" />
    <Child key="BBB" value="20" state="ERROR" />
    <Child key="CCC" value="30" state="OK" />
</Root>

我的班级:

[XmlRoot]
[XmlType("Root")]
public class MyRoot
{
    [XmlAttribute("timeUTC")]
    public long Time { get; set; }

    [XmlElement("Child")]
    public MyChild[] Children{ get; set; }
}

[XmlType("Child")]
public class MyChild
{
    [XmlAttribute("key")]
    public string Key { get; set; }

    [XmlAttribute("value")]
    public int Value { get; set; }

    [XmlAttribute("state")]
    public ChildState State { get; set; }
}

public enum ChildState
{
    OK,
    BAD,
}

【问题讨论】:

  • 我从风滚草中救了自己。亲爱的社区,您对#1 有更好的答案,对#2 有任何答案吗?或者,我应该接受自己的答案吗?
  • XML 序列化程序没有您想要的功能。如果您想要一种处理 XML 的简单方法,请查看 LINQ to XML。

标签: c# .net utc xmlserializer


【解决方案1】:

答案还是一样:XmlSerializer 不提供这种自定义。您可以对其他功能使用相同的技术,但是它会更长一些……(如您所说,XmlSerializer 很简单,您应该为此类自定义内容考虑不同的序列化程序。)

[XmlRoot]
[XmlType("Root")]
public class MyRoot
{
    // ...

    [XmlIgnore]
    public Dictionary<string, Tuple<int, ChildState>> Children { get; set; }

    [XmlElement("Child")]
    public MyChild[] ChildrenRaw
    {
        get
        {
            return Children.Select(c => new MyChild { Key = c.Key, Value = c.Value.Item1, State = c.Value.Item2 }).ToArray();
        }

        set
        {
            var result = new Dictionary<string, Tuple<int, ChildState>>(value.Length);
            foreach(var item in value)
            {
                result.Add(item.Key, new Tuple<int, ChildState>(item.Value, item.State));
            }
            Children = result;
        }
    }
}

【讨论】:

  • 谢谢。我忘了XmlIgnore
  • 顺便说一句,ToDictionary:value.ToDictionary(c =&gt; c.Key, c =&gt; new Tuple(c.Value, c.State));
【解决方案2】:

我在two years old answer by Marc Gravell♦ 中挖掘并找到了这个方法:

public class MyChild
{
    //...

    [XmlIgnore]
    public DateTime Time { get; set; }

    [XmlAttribute("timeUTC")]
    [Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public long TimeInt64 
    {
        get { return Date.ToFileTimeUtc(); }
        set { Date = DateTime.FromFileTimeUtc(value); }
    }
}

这是解决问题 #1 的公平方法。 #2仍然没有答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 2021-12-13
    • 2021-11-20
    • 1970-01-01
    • 2020-02-19
    相关资源
    最近更新 更多