2012-03-27 85 views
0

我有模式:xmlconvert字符串到日期

[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; } 
} 

現在我想轉換公共字符串的startDate {獲取;集;}到DatiTime:

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

我怎麼能這樣做?

回答

3

您沒有什麼特別的事情要做,只需要聲明屬性爲DateTime。 XmlSerializer的會自動轉換爲字符串像2012-03-27T16:21:12.8135895+02:00

如果需要使用特定的格式,你必須使用一個小竅門......戴上DateTime財產[XmlIgnore]屬性,並添加一個新字符串屬性,處理的格式:

[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); } 
} 

(該[EditorBrowsable]屬性是有避免顯示在智能感知的屬性,因爲它是唯一的序列化有用)

+0

例外:字符串「星期五,2012年03月30 20時00分00秒'不是有效的AllXsd值。 – Evgeniy 2012-03-27 14:24:59

+0

@Evg,看我更新的答案 – 2012-03-27 14:29:59

+0

很酷的把戲!謝謝! – Evgeniy 2012-03-27 15:10:08