I'm trying to find out the best methods for Deserializing XML.

The main problem I've come across is if I have the following example.

DateTime _SomeTime;

[XmlElement("some-time")]
public DateTime CancelledAt
{
    get { return _SomeTime; }
    set { _SomeTime = value; }
}

Usually this is fine and serializes correctly however when it's null which from the feed I am dealing with it can be, am I better off just serializing it as String the converting it in to Datetime OR is there something else I can do to stop it throwing when attempting to deserialize.

Is it just safer to Deserialize everything to string then convert to it's proper type, or is there a better way?

Any help/advice would be much appreciated.

Is it necessary for you to use XML? What is it you are doing or trying to do?

Yes it is necessary for me to use XML.

Basically it's an XML feed of data from an external source.

The issue I'm having is that if I do not declare everything as String if there are elements that are null or even removed (for which ever reason) it quite rightly throws errors when attempting to serialize.

Hmmm...

I must preface this and say that I truly believe XML is the spawn of Satan and I do everything I can to avoid it like the plague, but I'll offer what I can.

Is it possible to do something like this:

DateTime _SomeTime;

[XmlElement("some-time")]
public DateTime CancelledAt
{
    get { return _SomeTime; }
    set { _SomeTime = value ?? //insert some default value here; }
}

or

DateTime _SomeTime = DateTime.MinValue;

[XmlElement("some-time")]
public DateTime CancelledAt
{
    get { return _SomeTime; }
    set { _SomeTime = value; }
}

If this is not helpful, can you post your source where the exception is occuring and post the XML file it is reading?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.