2010-01-08 66 views
2

輸入...注意,註釋是由xsd工具生成的代碼。這是在31,834線文件和專有,但我在這裏粗略近似。XMLSerializer未序列化DateTime

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

在哪裏約會?

+1

我們可以看到關於這兩個屬性你'Comment'類的定義? – 2010-01-08 20:16:23

+0

我們需要看到註釋類的定義。 – 2010-01-08 20:18:46

+0

順便說一句,你缺少一些使用條款 – empi 2010-01-08 20:21:12

回答

1

帕維爾的評論是正確的答案。

此外,你說「爲了清楚起見省略其他字段 」。有機會, 字段或屬性名爲 commentDateSpecified當中那些 字段?

+0

請參閱@ panpawel的評論,這是正確的。 – AndHeCodedIt 2011-07-13 22:10:27

+0

可悲的是,在我從Pavel得到關於原始問題的評論的答案後大約15個月。 – MattMcKnight 2011-09-12 14:21:19

3

下工作,你需要顯示評論的定義:

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()); 
} 
+0

你錯過了一些關鍵的'使用'語句以及... – 2010-01-08 20:24:18

+4

不知道*關鍵*測試。我對其他人沒有在這裏使用陳述嗤之以鼻,所以我明白你的觀點。 – 2010-01-08 20:25:33

+1

我想你說得對,他們對測試並不重要。只是說其他碰到此代碼的人可能會盲目地複製和粘貼代碼。 – 2010-01-08 20:30:41

8

你需要爲了設置爲包含在XML

c.commentDateSpecified = true; 
+1

在每個人的答案中,你是唯一真正正確並幫助我的人。謝謝! – AndHeCodedIt 2011-07-13 22:09:48

+0

@AndHeCodedIt我同意,這應該是公認的答案。它爲我節省了很多時間 – johnc 2013-06-04 02:56:39

相關問題