Reputation: 555
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?
Upvotes: 0
Views: 931
Reputation: 292765
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)
Upvotes: 3