zoukankan      html  css  js  c++  java
  • 反序列化和序列化xml使用反射处理节点的属性

    当一个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); } }
  • 相关阅读:
    心得sql空值的应用
    C#开发GIS应用简明教程(二)
    网页右下角弹出窗口
    弹出输入框方法汇总
    C#开发GIS应用简明教程(三)
    防刷新的另一种方法
    相册
    网站下载速度限制方法
    .NET下多线程初探
    用DECODE做交叉报表
  • 原文地址:https://www.cnblogs.com/hosseini/p/8630019.html
Copyright © 2011-2022 走看看