saucer能帮忙看一下吗,关于xml反序列化,可是.net的bug?

tlping 2003-06-17 11:17:56
using System;
using System.IO;
using System.Xml.Serialization;
using System.Xml;



namespace Customers
{
[XmlRoot("customer")]
public class Customer
{
public String Name;
public String Address;
public String PhoneNumber;

}

[XmlRoot("customer")]
public class CustomerType
{
public String name;
public String address;
public String phone;
}


public class Class1
{

[STAThread]
public static void Main(string[] args)
{
Customer t=new Customer();
t.Name=" Ballinger";
t.Address="1 Microsoft Way";
t.PhoneNumber="(425)555-1212";

System.Xml.Serialization.XmlSerializer ser=new System.Xml.Serialization.XmlSerializer(typeof(Customer));
FileStream stream=new FileStream(
"cust.xml",FileMode.OpenOrCreate);
ser.Serialize(stream,t);
stream.Close();

System.Xml.Serialization.XmlSerializer ser2=new System.Xml.Serialization.XmlSerializer(typeof(CustomerType));
FileStream inStream=new FileStream("cust.xml",FileMode.Open);
XmlReader reader=new XmlTextReader(inStream);

//这里判断该xml是否可被序列化为customerType的对象
//奇怪的是竟然canserialize的结果为true,但该对象中的字段却没有值
if(ser2.CanDeserialize(reader))
{
Console.WriteLine("Deserializing.........");
CustomerType cust=(CustomerType)ser2.Deserialize(reader);
Console.WriteLine("name:{0}",cust.name);
Console.WriteLine("address:{0}",cust.address);
Console.WriteLine("phone:{0}",cust.phone);



}
else {Console.WriteLine("the type doesn't match");}

inStream.Close();


}

}



}

我觉得这里既然可被序列化,那么应该对象中的字段会有值才对阿
...全文
35 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
saucer 2003-06-18
  • 打赏
  • 举报
回复
I think CanDeserialize() only checks the root element
saucer 2003-06-18
  • 打赏
  • 举报
回复
I think CanDeserialize() only checks the root element
tlping 2003-06-18
  • 打赏
  • 举报
回复
thanks,我很奇怪的是ser2.CanDeserialize(reader)这个方法返回为什么是true,在这里CustomerType应该是不匹配的,对这一点很疑惑
saucer 2003-06-18
  • 打赏
  • 举报
回复
the public field needs to match and xml is case-sensitive, look in the cust.xml, you will know

if you insist, you could try something like

[XmlRoot("customer")]
public class CustomerType
{
[XmlElement("Name")]
public String name;
[XmlElement("Address")]
public String address;
[XmlElement("PhoneNumber")]
public String phone;
}

62,025

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧