0

I have model:

    [XmlRoot(ElementName = "event", IsNullable=true)]
public class Event
{
    public int id { get; set; }
    public string title { get; set; }
    public eventArtists artists { get; set; }
    public venue venue { get; set; }
    public string startDate { get;set;}
    public string description { get; set; }
    [XmlElement("image")]
    public List<string> image { get; set; }
    public int attendance { get; set; }
    public int reviews { get; set; }
    public string url { get; set; }
    public string website { get; set; }
    public string tickets { get; set; }
    public int cancelled { get; set; }
    [XmlArray(ElementName="tags")]
    [XmlArrayItem(ElementName="tag")]
    public List<string> tags { get; set; }
}

now I want to convert public string startDate { get;set;} to DatiTime:

public DateTime startDate { get{return startDate;} set{startDate. = DateTime.Parse(startDate);}}

How can I do that?

1 Answer 1

3

You don't have anything special to do, just declare the property as a DateTime. The XmlSerializer will convert it automatically to a string like 2012-03-27T16:21:12.8135895+02:00

If you need to use a specific format, you have to use a small trick... Put a [XmlIgnore] attribute on the DateTime property, and add a new string property that handles the formatting:

[XmlIgnore]
public DateTime startDate { get;set;}

private const string DateTimeFormat = "ddd, dd MMM yyyy HH:mm:ss";

[XmlElement("startDate")]
[EditorBrowsable(EditorBrowsableState.Never)]
public string startDateXml
{
    get { return startDate.ToString(DateTimeFormat, CultureInfo.InvariantCulture); }
    set { startDate = DateTime.ParseExact(value, DateTimeFormat, CultureInfo.InvariantCulture); }
}

(the [EditorBrowsable] attribute is there to avoid showing the property in intellisense, since it's only useful for serialization)

Sign up to request clarification or add additional context in comments.

1 Comment

Exception: The string 'Fri, 30 Mar 2012 20:00:00' is not a valid AllXsd value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.