views:

128

answers:

3

How to deserialize "<MyType><StartDate>01/01/2000</StartDate></MyType>"

below is the MyType definition

[Serializable]
public class MyType
{
    DateTime _StartDate;
    public DateTime StartDate
    {
        set
        {
            _StartDate = value;
        }
        get
        {
            return _StartDate;
        }
    }
}

Got the following error while deserializing

{"The string '01/01/2000' is not a valid AllXsd value."} [System.FormatException]: {"The string '01/01/2000' is not a valid AllXsd value."} Data: {System.Collections.ListDictionaryInternal} HelpLink: null InnerException: null Message: "The string '01/01/2000' is not a valid AllXsd value." Source: "System.Xml" StackTrace: " at System.Xml.Schema.XsdDateTime..ctor(String text, XsdDateTimeFlags kinds)\r\n at System.Xml.XmlConvert.ToDateTime(String s, XmlDateTimeSerializationMode dateTimeOption)\r\n at System.Xml.Serialization.XmlCustomFormatter.ToDateTime(String value)\r\n at System.Xml.Serialization.XmlSerializationReader.ToDateTime(String value)\r\n at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderMyType.Read2_MyType(Boolean isNullable, Boolean checkType)\r\n
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderMyType.Read3_MyType()" TargetSite: {Void .ctor(System.String, System.Xml.Schema.XsdDateTimeFlags)}

A: 

In short I think you don't. Your problem is that that the XmlSerializer tries to parse the 01/01/2000 into a DateTime value, but 01/01/2000 is not a valid XML date.

How is the XML string created? Do you have control over that code? If so, use the XmlConvert.ToString(DateTime) method to get a string that conforms to the standard.

Fredrik Mörk
@Fredrik: No, I don't have control over XML string formation. It is sent from client. In my side I am trying to Deserialize the given xml string.
afin
+1  A: 

Probably DateTime deserializer expects a different format to the one you have there.

The format I use looks like this:

2010-01-20T13:40

(This is for a UTC DateTime, you can also have timezones on the end of the string)

I use this format to send to with [DataMember] properties and the DataContractSerializer deals with it fine, so I guess it will work with Xml Serialization as well.

There's a thread about the error you are getting here that looks like it might be helpful.

DanK
+1  A: 

If you really can't control the input XML but still have to parse it(despite being improper), something like this is what I've done in the past.

[Serializable]
public class MyType
{
    DateTime _StartDate;
    public string StartDate
    {
        set
        {
            _StartDate = DateTime.Parse(value);
        }
        get
        {
            return _StartDate.ToShortDateString();
        }
    }
}
@awlawl: So, no way to deserialize DateTime type?
afin