C# XMLSerializer未序列化日期时间
注意,注释是从xsd工具生成的代码。它在一个31834行文件中,是专有的,但我在这里给出了一个粗略的近似值C# XMLSerializer未序列化日期时间,c#,xml-serialization,C#,Xml Serialization,注意,注释是从xsd工具生成的代码。它在一个31834行文件中,是专有的,但我在这里给出了一个粗略的近似值 [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public cl
[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>
我的评论文本
日期在哪里?以下作品中,您需要显示注释的定义:
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());
}
帕维尔的评论是正确的答案 还有,你说“省略了其他字段” 为清楚起见”。是否有一个偶然的机会 名为的字段或属性 在这些文件中指定了注释 田地
您需要设置才能包含在XML中
c.commentDateSpecified = true;
我们可以看看你的
注释类关于这两个属性的定义吗?给出的代码不可编译。如果调整为编译,它将正常工作。你真的需要发布真实的代码,或者试着提出一个最简单的复制问题的独立示例(即可以复制粘贴、编译和运行)。它不会编译,因为没有类XMLSerializer
(它是XMLSerializer
),类似于xmlementattribute
和serialize()
和typeof(Comment)
,变量txtcoment
未定义,并且在任何方法定义之外都有一堆代码。此外,您还说“为了清晰起见,省略了其他字段”。这些字段中是否碰巧有一个名为commentDateSpecified
的字段或属性?@Matt,读一下这篇文章,我不知道测试的关键性。我曾经抱怨过其他人也没有在这里使用语句,所以我接受你的观点。我想你是对的,他们对测试不重要。只是说其他人在这里没有使用语句我把这段代码作为自己的代码使用,可能只是盲目地复制和粘贴代码。为复制粘贴人群修改。我也考虑过使用
语句包含,然后我想如果paster不能在C中破译正确的用法,那么他们很可能也找不到C编译器,也不知道如何设置断点来分析sni他们还想知道为什么粘贴的代码无法编译(缺少一个类)等等……需要一定程度的基本能力,特别是当我们已经在这里的XML名称空间中处理序列化时。更不用说如果您正在复制和粘贴代码,并且您不理解或测试代码,那么您应该得到任何内存泄漏。在每个人的答案中,您的答案是唯一正确的谢谢!@AndHeCodedIt我同意,这应该是公认的答案。在我在对原始问题的评论中得到Pavel的答案大约15个月后,它为我节省了很多时间。