今天是大年初一,先来无事,突然想起之前项目用到的东西,想起来要分享给大家,同时,过年好!
首先这个实现的方式借鉴了 :
https://blog.csdn.net/shuliuzh/article/details/49426711
主要是适用了实现自己的 IXmlSerializable ,简化了些方式,通过反射自动包装处理数据。源码如下:
public class MyXmlSerializable : IXmlSerializable
{
public XmlSchema GetSchema()
{
return null;
}
public virtual void ReadXml(XmlReader reader)
{
reader.ReadStartElement("xml");
for (int i = 0; i < this.GetType().GetProperties().Length; i++)
{
PropertyInfo property = this.GetType().GetProperty(reader.Name);
if(property!=null)
{
property.SetValue(this, reader.ReadElementContentAsString(property.Name, ""));
}
}
reader.ReadEndElement();
}
public virtual void WriteXml(XmlWriter writer)
{
foreach (PropertyInfo property in this.GetType().GetProperties())
{
writer.WriteStartElement(property.Name);
writer.WriteCData((property.GetValue(this, null)??"").ToString());
writer.WriteEndElement();
}
}
}
使用方式:
[XmlRoot("xml")]
public class SandboxSignResult: MyXmlSerializable
{
public string retmsg { get; set; }
public string retcode { get; set; }
public string return_code { get; set; }
public string return_msg { get; set; }
public string sandbox_signkey { get; set; }
}
ps:这里是在微信接口中调用的,所以根节点直接设置了 "xml",其实也只是把读写值得操作通过反射自动处理,这样就不需要在每个类中重复实现这个方法,直接继承这个,如果又需要自己定制读写的话,也只需要在子类重写这两个虚拟方法。