代码之家  ›  专栏  ›  技术社区  ›  MattMcKnight

XmlSerializer未序列化日期时间

  •  2
  • MattMcKnight  · 技术社区  · 15 年前

    输入…注意注释是从XSD工具生成的代码。它在31834行文件中,并且是专有的,但我在这里给出了一个粗略的近似值。

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

    输出-gt;

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

    日期在哪里?

    3 回复  |  直到 14 年前
        1
  •  10
  •   panpawel    14 年前

    为了包含在XML中,需要进行设置

     c.commentDateSpecified = true;
    
        2
  •  3
  •   Yuriy Faktorovich    15 年前

    下面的工作,您需要显示注释的定义:

    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());
    }
    
        3
  •  2
  •   MattMcKnight    15 年前

    帕维尔的评论是正确的答案。

    另外,你会说“省略了其他字段” 为清晰起见。偶然的是,有没有 名为的字段或属性 其中指定的注释日期 领域?