0

我有模型:

    [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 { get;set;} 转换为 DatiTime:

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

我怎样才能做到这一点?

4

1 回答 1

3

您没有什么特别的事情要做,只需将属性声明为DateTime. XmlSerializer 会自动将其转换为类似的字符串2012-03-27T16:21:12.8135895+02:00

如果你需要使用特定的格式,你必须使用一个小技巧......在[XmlIgnore]属性上放置一个属性DateTime,并添加一个新的字符串属性来处理格式:

[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]属性是为了避免在智能感知中显示该属性,因为它仅对序列化有用)

于 2012-03-27T14:21:26.990 回答