How to deserialize an XML attribute of type long for UTC DateTime?

Following these answers , I decided to use xsd.exe and XmlSerializer as the easiest way to parse XML.

But I need some clarification:

  • My top query changes the type of MyRoot.Time from long to DateTime . It can be easily achieved using the DateTime.FromFileTimeUtc or new DateTime code, but can it be done directly using the XmlSerializer?
  • Can I change the type of MyRoot.Children to something more complex, for example Dictionary<string,Tuple<int,ChildState>> ?

My 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> 

My classes are:

 [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, } 
0
c # utc xmlserializer
source share
2 answers

The answer is the same: XmlSerializer does not offer such a setting. You can use the same technique for another function, however it is a little longer ... (XmlSerializer, as you said, is simple, you should consider different serializers for such custom materials.)

 [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; } } } 
+1
source share

I dug up and found this method in a two-year answer by Mark Gravel ♦ :

 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); } } } 

This is a fair method that solves issue number 1. There is no answer to # 2 yet.

+1
source share

All Articles