在C#中用反射将XML转化成实体类时,发现了一个大小写的问题。
<?xml version="1.0" encoding="gb2312"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://ww w.w3.org/2001/XMLSchema"> <common> <project_id>1</project_id> <gateway_id>1</gateway_id> <type>md5</type> </common> <gateway_id>1</gateway_id> <id_validate operation="md5"> <md5>061e85ee43152b671a5f49039a6042cbb </md5> </id_validate> </root> |
[XmlRoot("root")] public class MD5 { public MD5(string p, string p_2, string p_3) { this.Common = new common(p, p_2, "md5"); this.idvalidate = new id_validate(p_3); } public MD5() { this.Common = new common(string.Empty, string.Empty, "md5"); this.idvalidate = new id_validate(string.Empty); } [XmlElement(ElementName = "common")] public common Common { get; set; } [XmlElement(ElementName = "id_validate")] public id_validate idvalidate { get; set; } [XmlElement(ElementName = "gateway_Id")] public string gateway_Id { get; set; } public class id_validate { public id_validate() { this.operation = "md5"; this.StrMD5 = ""; } public id_validate(string p_3) { this.operation = "md5"; this.StrMD5 = p_3; } [XmlAttribute(AttributeName = "md5")] public string operation { get; set; } [XmlElement(ElementName = "md5")] public string StrMD5 { get; set; } } } |
这个时候,想要进行序列化和反序列化操作,其中对普通数据类型的序列化反序列化,比如gateway_Id节点,那么默认将实体类中的属性名作为对应的XML文本中节点名称。这样乍看一下好像没有什么问题,但是实际上,我发现,这样经常会出现反射到实体类中属性值有时候为空,在几经测试之后发现,原来是Xml文本反射到实体类中,根据实体类的属性名进行反射时,是大小写敏感的(我用的是XmlSerializer x = new XmlSerializer(md5.GetType());
x.Serialize(Console.Out, md5);来反射实体类)
如果没有注意大小写,就没有办法正确地为实体类中的属性或公有字段赋值。
本文转自陈哈哈博客园博客,原文链接http://www.cnblogs.com/kissazi2/archive/2012/04/01/2977142.html如需转载请自行联系原作者
kissazi2