XMLSerializer не сериализует DateTime - PullRequest
2 голосов
/ 08 января 2010

Ввод ... обратите внимание, что комментарий генерируется кодом из инструмента xsd. Он находится в файле с 31 834 строками и является частной собственностью, но я добавил здесь приблизительное приближение.

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class comment
{
   private System.DateTime commentDateField;
   private bool commentDateFieldSpecified;
   [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
   public System.DateTime commentDate
   { 
      get 
      {
         return this.commentDateField;
      }
      set
      {
         this.commentDateField = value;
      }  
   }
   [System.Xml.Serialization.XmlIgnoreAttribute()]
   public bool commentDateSpecified
   { 
      get 
      {
         return this.commentDateFieldSpecified;
      }
      set
      {
         this.commentDateFieldSpecified = value;
      }  
   }
   //other fields omitted for clarity
}
comment c = new comment();
c.text = txtComment.Text;
c.commentDate = DateTime.Now;
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlSerializer xs = new XmlSerializer(typeof(comment));
xs.serialize(sw as TextWriter, c);
string output = sb.ToString();

выход ->

<comment>
  <text>My Comment Text</text>
</comment>

Где дата?

Ответы [ 3 ]

10 голосов
/ 16 марта 2011

Вам необходимо установить для включения в XML

 c.commentDateSpecified = true;
3 голосов
/ 08 января 2010

В следующих работах необходимо показать определение комментария:

public class comment
{
    public string text { get; set; }
    public DateTime commentDate { get; set; }
}

XmlSerializer serializer = new XmlSerializer(typeof(comment));
comment comment = new comment { text = "test", commentDate = DateTime.Now };
using (MemoryStream stream = new MemoryStream())
using (StreamReader reader = new StreamReader(stream))
{
    serializer.Serialize(stream, comment);
    stream.Position = 0;
    Console.WriteLine(reader.ReadToEnd());
}
2 голосов
/ 11 января 2010

Комментарий Павла был правильным ответом.

Кроме того, вы говорите "пропущены другие поля для ясности ". Есть, случайно, поле или свойство с именем commentDateSpecified среди тех, поля

...