5

I have to deserialize xml with date looking like this:

<date>2015/10/16 00:00:00.000000000</date>

My class contains this field:

[XmlAttribute("date")]
public DateTime StartDate { get; set; }

But I always receive default date. Is it possible to parse this format of datetime?

Edit: When I change XmlAttribute to XmlElement, I get exception:

There is an error in XML document

So I think DateTime can's parse this format.

petros
  • 705
  • 1
  • 8
  • 26
  • 3
    Possible duplicate of [Force XmlSerializer to serialize DateTime as 'YYYY-MM-DD hh:mm:ss'](http://stackoverflow.com/questions/3534525/force-xmlserializer-to-serialize-datetime-as-yyyy-mm-dd-hhmmss) – Volkan Paksoy Jan 11 '16 at 15:51
  • 2
    And also [Can you specify format for XmlSerialization of a datetime?](https://stackoverflow.com/questions/1118833/can-you-specify-format-for-xmlserialization-of-a-datetime). `[XmlElement]` is the correct annotation to use, you get the default `DateTime` value with `[XmlAttribute("date")]` because the element value is being ignored. – dbc Jan 11 '16 at 15:56

1 Answers1

0

One way to handle this is to decorate the DateTime member with [System.Xml.Serialization.XmlIgnore]

This tells the serializer to not serialize or de-serialize it at all.

Then, add an additional property to the class, called, for example DateString. It might be defined as

public string DateString {
    set { ... }
    get { ... }
}

Then you can serialize and de-ser the DateString in the get/set logic:

public string DateString {
    set {
    // parse value here - de-ser from your chosen format
    // use constructor, eg, Timestamp= new System.DateTime(....);
    // or use one of the static Parse() overloads of System.DateTime()
    }
    get {
        return Timestamp.ToString("yyyy.MM.dd");  // serialize to whatever format you want.
    }
}

Within the get and set you are manipulating the value of the Date member, but you are doing it with custom logic. The serialized property need not be a string of course, but that is a simple way to do it. You could also ser/de-ser using an int, as with the unix epoch, for example

by Dino Chiesa

andreikashin
  • 1,528
  • 3
  • 14
  • 21