导航

反序列化和序列化xml使用反射处理节点的属性

Posted on 2018-03-23 14:10  Hosseini  阅读(156)  评论(0编辑  收藏  举报

当一个xml中有大量的属性XmlAttribute需要序列化和反序列化,通常需要复制粘贴大量的如下代码,显得很丑陋,而且容易出错:

XmlAttribute attr = Doc.CreateAttribute("MaterialMark");
attr.Value = myObject.MaterialMark;
xmlroot.Attributes.Append(attr)

 

XmlAttribute attr = mlnode.Attributes["MaterialMark"];
if (attr != null)
myObject.index = findex.Value;

 

可以使用反射技术,做出修改,如下:

public Class MyObject
{
   public string A
{
  get;
  set;
}

   public int B
{
  get;
  set;
}

   public double C
{
  get;
  set;
}



}
    void getAttrFromXml(MyObject myObject,XmlNode xmlNode)
        {
            foreach (XmlAttribute attr in xmlNode.Attributes)
            {
                    object val = attr.Value;
                    Type type = typeof(MyObject);
                    PropertyInfo proInf = type.GetProperty(attr.Name);
            switch (proInf.PropertyType.ToString())
                    {
                        case "System.String":
                            proInf.SetValue(myObject, val, null);
                            break;

                        case "System.Double":
                            double result = 0;
                            double.TryParse(val.ToString(), out result);
                            proInf.SetValue(myObject, result, null);
                            break;
                            
                        default:
                            //自己添加用到的类型
                            break;
                    }
            }
        }
        void setAttrFromObject(MyObject myobject, XmlNode xmlNode)
        {
             Type type = typeof(MyObject);
             foreach (PropertyInfo proInf in type.GetProperties())
             {
                 XmlAttribute attr = xmlNode.OwnerDocument.CreateAttribute(proInf.Name);
if(proInf.GetValue(myObject,null)!=null) attr.Value
= proInf.GetValue(myObject,null).ToString(); xmlNode.Attributes.Append(attr); } }