Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you specify format for XmlSerialization of a datetime?

I need to serialize / deserialize a datetime into yyyyMMdd format for an XML file. Is there an attribute / workaround I can use for this?

like image 257
cjk Avatar asked Jul 13 '09 10:07

cjk


People also ask

What is the correct way of using XML serialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of the class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.

Is XML a serialization format?

XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it is deserialized into an object of the same type.

Can you serialize dateTime?

Serialize datetime by converting it into StringYou can convert dateTime value into its String representation and encode it directly, here you don't need to write any encoder. We need to set the default parameter of a json. dump() or json. dumps() to str like this json.

What is the difference between binary serialization and XML serialization?

Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.


2 Answers

No, there isn't. If it's in that format, then it's not a valid dateTime as far as XML Schema is concerned.

The best you can do is as follows:

[XmlIgnore] public DateTime DoNotSerialize {get;set;}  public string ProxyDateTime {     get {return DoNotSerialize.ToString("yyyyMMdd");}     set {DoNotSerialize = DateTime.Parse(value);} } 
like image 50
John Saunders Avatar answered Oct 11 '22 08:10

John Saunders


XmlElementAttribute#DataType should provide what you need:

[XmlElement(DataType="date")]     public DateTime Date1 {get;set;} 

This will get Date1 property serialized to the proper xml date format.

like image 41
th2tran Avatar answered Oct 11 '22 07:10

th2tran