Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I XML Serialize a DateTimeOffset Property?

The DateTimeOffset property I have in this class doesn't get rendered when the data is represented as Xml. What do I need to do to tell the Xml serialization to render that proper as a DateTime or DateTimeOffset?

[XmlRoot("playersConnected")] public class PlayersConnectedViewData {     [XmlElement("playerConnected")]     public PlayersConnectedItem[] playersConnected { get; set; } }  [XmlRoot("playersConnected")] public class PlayersConnectedItem {     public string name { get; set; }     public DateTimeOffset connectedOn { get; set; }  // <-- This property fails.     public string server { get; set; }     public string gameType { get; set; } } 

and some sample data...

<?xml version="1.0" encoding="utf-8"?> <playersConnected       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xmlns:xsd="http://www.w3.org/2001/XMLSchema">   <playerConnected>     <name>jollyroger1000</name>     <connectedOn />     <server>log1</server>     <gameType>Battlefield 2</gameType>   </playerConnected> </playersConnected> 

Update

I'm hoping there might be a way through an Attribute which I can decorate on the property...

Bonus Question

Any way to get rid of those two namespaces declared in the root node? Should I?

like image 421
Pure.Krome Avatar asked Jul 31 '10 06:07

Pure.Krome


People also ask

What is the correct way of using XML serialization?

XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.

What does serialize XML mean?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

Which class should be used to serialize an object in XML format?

Xml. Serialization namespace) class is used to serialize and deserialize. The class method Serialize is called. Since we have to serialize in a file, we create a " TextWriter ".


2 Answers

It's a few years late, but here's the quick and easy way to completely serialize DateTimeOffset using ISO 8601:

[XmlElement("lastUpdatedTime")] public string lastUpdatedTimeForXml // format: 2011-11-11T15:05:46.4733406+01:00 {    get { return lastUpdatedTime.ToString("o"); } // o = yyyy-MM-ddTHH:mm:ss.fffffffzzz    set { lastUpdatedTime = DateTimeOffset.Parse(value); }  } [XmlIgnore]  public DateTimeOffset lastUpdatedTime; 
like image 121
Peter Avatar answered Sep 19 '22 01:09

Peter


I came up with this struct which implements XML serialization based on ISO 8601 formatting (e.g. 2011-11-11T15:05:46.4733406+01:00). Hint: Trying to parse a DateTime value such as 2011-11-11T15:05:46 fails as expected.

Feedback welcome. I didn't include the unit tests here because that would be too much text.

/// <remarks> /// The default value is <c>DateTimeOffset.MinValue</c>. This is a value /// type and has the same hash code as <c>DateTimeOffset</c>! Implicit /// assignment from <c>DateTime</c> is neither implemented nor desirable! /// </remarks> public struct Iso8601SerializableDateTimeOffset : IXmlSerializable {     private DateTimeOffset value;      public Iso8601SerializableDateTimeOffset(DateTimeOffset value)     {         this.value = value;     }      public static implicit operator Iso8601SerializableDateTimeOffset(DateTimeOffset value)     {         return new Iso8601SerializableDateTimeOffset(value);     }      public static implicit operator DateTimeOffset(Iso8601SerializableDateTimeOffset instance)     {         return instance.value;     }      public static bool operator ==(Iso8601SerializableDateTimeOffset a, Iso8601SerializableDateTimeOffset b)     {         return a.value == b.value;     }      public static bool operator !=(Iso8601SerializableDateTimeOffset a, Iso8601SerializableDateTimeOffset b)     {         return a.value != b.value;     }      public static bool operator <(Iso8601SerializableDateTimeOffset a, Iso8601SerializableDateTimeOffset b)     {         return a.value < b.value;     }      public static bool operator >(Iso8601SerializableDateTimeOffset a, Iso8601SerializableDateTimeOffset b)     {         return a.value > b.value;     }      public override bool Equals(object o)     {         if(o is Iso8601SerializableDateTimeOffset)             return value.Equals(((Iso8601SerializableDateTimeOffset)o).value);         else if(o is DateTimeOffset)             return value.Equals((DateTimeOffset)o);         else             return false;     }      public override int GetHashCode()     {         return value.GetHashCode();     }      public XmlSchema GetSchema()     {         return null;     }      public void ReadXml(XmlReader reader)     {         var text = reader.ReadElementString();         value = DateTimeOffset.ParseExact(text, format: "o", formatProvider: null);     }      public override string ToString()     {         return value.ToString(format: "o");     }      public string ToString(string format)     {         return value.ToString(format);     }      public void WriteXml(XmlWriter writer)     {         writer.WriteString(value.ToString(format: "o"));     } } 
like image 30
AndiDog Avatar answered Sep 21 '22 01:09

AndiDog