2014-03-06 80 views
2

我是一名編程學生,我想知道當我在xml文件中序列化它時是否可以更改日期的格式。此日期是對象「Loan」的ObservableCollection的屬性,此對象具有兩個DateTime屬性,其中一個日期是可爲空的對象。我序列化包括日期在內的所有集合。在C#中將XML的DateTime屬性序列化爲XML

我想獲得在xml文件:

<OutDate> 15-03-2014 </OutDate> 
<!--If the date is null I don´t want to appear the node--> 

而且I'm得到這個:

<OutDate>2014-03-15T00:00:00</OutDate> 
<InDate xsi:nil="true" /> 

這是我的代碼項目的一部分:我類貸款 部分,已標記爲可序列化,如下所示:

private string isbn; 
    private string dni; 
    private DateTime dateOut; 
    private DateTime? dateIn;  
    // Setters and Gettters and constructors 

這是序列化:

// I will pass three collections to this method loans, books and clients 
public void SerializeToXML<T>(string file, string node, ObservableCollection<T> collection) 
     { 
      XmlRootAttribute root = new XmlRootAttribute(node); 
      XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<T>), root); 
      using (FileStream fs = new FileStream(file, FileMode.Create)) 
      { 
       serializer.Serialize(fs, collection); 
      } 
     } 

召喚:

SerializeToXML<Loan>(_file, "Library", manager.LoansCollection); 

Thnks。

回答

1

可能最簡單的方法是實現類的IXmlSerializable接口。大意如下

public class Loan : IXmlSerializable 
{ 
    public void WriteXml(XmlWriter writer) 
    { 
     if(dateIn.HasValue) 
     { 
      writer.WriteElementString("dateIn", dateIn.Value.ToString()); 
     } 
    } 
} 

在讀的東西,你需要閱讀該元素的名稱,如果是dateIn設置,否則設置適當的值。基本上檢查它是否存在於XML中。

1

如果您不希望實現IXmlSerializable,一些日期時間以支持字段的字符串轉換應該做的伎倆,這樣的事情:

public class Loan 
    { 
     [XmlIgnore] 
     private DateTime _dateOut; 

     public string OutDate 
     { 
      get { return _dateOut.ToString("dd-MM-yyyy"); } 
      set { _dateOut = DateTime.Parse(value); } 
     } 
    } 
1

有看看的XmlElement屬性類(在系統.Xml.Serialization)。如果不工作,那麼this answer展示瞭如何使用代理物業

[XmlElement("TheDate", DataType = "date")] 
    public DateTime TheDate { get; set; } 
1

我知道它的晚讓我的答案標記爲「一」,但你可以有超過序列化的控制而無需實現複雜的接口或包裹東西作爲解決方法。

public DateTime? InDate { get; set } 

public bool ShouldSerializeInDate() 
{ 
    return InDate.HasValue; 
} 

C#XML序列化程序沒有很好的記錄功能。每個公共財產都可以有一個打開或關閉財產序列化的方法。該方法必須被調用:ShouldSerializeXYZ其中XYZ是您想要控制的屬性的確切名稱。

請參閱: Xml serialization - Hide null values