根据XML转换为C#类的对象

    public class InitObjectWithXml
    {
        public object initObject(string xmlDef)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlDef);
            XmlElement rootNode=doc.DocumentElement;
            return getNodeObject(rootNode,null);
        }
        /// <summary>
        /// <id class=\"xxx\">111</id>
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private object getNodeObject(XmlNode node,object parentObject)
        {
            string nodeName = node.Name;
            string nodeJavaClass = getJavaClass(node);
            if (nodeJavaClass == null)
            {
                //1,是列表:<list>
                if (nodeName.ToLower().Equals("list"))
                {
                    ArrayList nodeObjArray=new ArrayList();
                    foreach (XmlNode child in node.ChildNodes)
                    {
                        nodeObjArray.Add(getNodeObject(child, nodeObjArray));
                    }
                    return nodeObjArray;
                }
                //2,根对象或者list下的对象节点: <Easysys_Model_Ums.entity.module.Module>
                object nodeObj = new ObjectReflect().createObjectInstance(nodeName);
                if (nodeObj != null)
                {
                    //除了class的其他属性
                    foreach (XmlAttribute attr in node.Attributes)
                    {
                        if (attr.Name.ToLower().Equals("class"))
                        {
                            continue;
                        }
                        //每个属性都对应对象的一个set方法
                        string attrName = attr.Name;
                        //生成对应的set方法,且第一个字母大写
                        string methodName = "set" + attrName.Substring(0, 1).ToUpper() + attrName.Substring(1);
                        MethodInfo method = nodeObj.GetType().GetMethod(methodName);
                        if (method == null)
                        {
                            //不存在这个属性,跳过
                            continue;
                        }
                        Type[] argTypes = method.GetGenericArguments();
                        //set方法只有一个参数,所以取第一个即可
                        object setValue = getBasicTypeValue(argTypes[0], attr.Value);
                        method.Invoke(nodeObj, new object[] { setValue });
                    }

                    if (node.ChildNodes.Count > 0)
                    {
                        //孩子节点
                        foreach (XmlNode childNode in node.ChildNodes)
                        {
                            object childObject = getNodeObject(childNode, nodeObj);

                            string fieldName = childNode.Name;
                            //生成对应的set方法,且第一个字母大写
                            string methodName = "set" + fieldName.Substring(0, 1).ToUpper() + fieldName.Substring(1);
                            MethodInfo method = nodeObj.GetType().GetMethod(methodName);
                            if (method == null)
                            {
                                //不存在这个属性,跳过
                                continue;
                            }
                            method.Invoke(nodeObj, new object[] { childObject });
                        }
                    }
                    return nodeObj;
                }
                //3,nodeObj==null => 基本值类型节点: <value>111</value>
                string valueFieldName=node.Name;
                string valueMethodName = "set" + valueFieldName.Substring(0, 1).ToUpper() + valueFieldName.Substring(1);
                MethodInfo valueMethod = parentObject.GetType().GetMethod(valueMethodName);
                ParameterInfo[] paras=valueMethod.GetParameters();
                Type parameterType = paras[0].ParameterType;
                return getBasicTypeValue(parameterType,node.InnerText);
            }
            else
            {
                object nodeObj = null;
                //指定了具体的类型
                if (node.Name.ToLower().Equals("id"))
                {
                    string idType =nodeJavaClass + "`1[" + parentObject.GetType().ToString() + "]";
                    nodeObj = new ObjectReflect().createObjectInstance(idType);
                }
                else
                {
                    nodeObj = new ObjectReflect().createObjectInstance(nodeJavaClass);
                }
                if (nodeObj == null)
                {
                    return null;
                }
                //设置除了class的其他属性
                foreach (XmlAttribute attr in node.Attributes)
                {
                    if (attr.Name.ToLower().Equals("class"))
                    {
                        continue;
                    }
                    //每个属性都对应对象的一个set方法
                    string attrName = attr.Name;
                    //生成对应的set方法,且第一个字母大写
                    string methodName = "set" + attrName.Substring(0, 1).ToUpper() + attrName.Substring(1);
                    MethodInfo method = nodeObj.GetType().GetMethod(methodName);
                    if (method == null)
                    {
                        //不存在这个属性,跳过
                        continue;
                    }
                    Type[] argTypes = method.GetGenericArguments();
                    //set方法只有一个参数,所以取第一个即可
                    object setValue = getBasicTypeValue(argTypes[0], attr.Value);
                    method.Invoke(nodeObj, new object[] { setValue });
                }

                if (node.ChildNodes.Count > 0)
                {
                    //孩子节点
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        object childObject = getNodeObject(childNode, nodeObj);

                        string fieldName = childNode.Name;
                        //生成对应的set方法,且第一个字母大写
                        string methodName = "set" + fieldName.Substring(0, 1).ToUpper() + fieldName.Substring(1);
                        MethodInfo method = nodeObj.GetType().GetMethod(methodName);
                        if (method == null)
                        {
                            //不存在这个属性,跳过
                            continue;
                        }
                        method.Invoke(nodeObj, new object[] { childObject });
                    }
                }

                return nodeObj;
            }
        }
        /// <summary>
        /// 根据指定的类型,转换为对应的对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="strValue"></param>
        /// <returns></returns>
        private object getBasicTypeValue(Type type, string strValue)
        {
            if (type.IsValueType)
            {
                //类型是一个值类型
                if (type.ToString().Equals(typeof(Int16).ToString()))
                {
                    return Int16.Parse(strValue);
                }
                if (type.ToString().Equals(typeof(Int32).ToString()))
                {
                    return Int32.Parse(strValue);
                }
                if (type.ToString().Equals(typeof(Int64).ToString()))
                {
                    return Int64.Parse(strValue);
                }
                if (type.ToString().Equals(typeof(string).ToString()))
                {
                    return strValue;
                }
                if (type.ToString().Equals(typeof(bool).ToString()))
                {
                    return bool.Parse(strValue);
                }
                if (type.ToString().Equals(typeof(float).ToString()))
                {
                    return float.Parse(strValue);
                }
                if (type.ToString().Equals(typeof(double).ToString()))
                {
                    return double.Parse(strValue);
                }
                throw new Exception("不支持的类型[" + type.ToString() + "]");
            }
            throw new Exception("属性值不支持非值类型[" + type.ToString() + "]");
        }
        /// <summary>
        /// 从节点中找出class属性的值
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private string getJavaClass(XmlNode node)
        {
            string javaType = null;
            foreach (XmlAttribute attr in node.Attributes)
            {
                if (attr.Name.ToLower().Equals("class"))
                {
                    javaType = attr.Value;
                    break;
                }
            }
            return javaType;
        }
        /// <summary>
        /// 根据JavaType找到对应的CsharpType
        /// </summary>
        /// <param name="javaType"></param>
        /// <returns></returns>
        private string getMappedCsharpTypeByJavaType(string javaType)
        {
            return javaType;
        }
        public void testInitObject()
        {
            string t = new IdentityLong<Module>().ToString();
            string xml="<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            xml += "\n<list><Easysys_Model_Ums.entity.module.Module>";
            xml += "\n<id class=\"Easysys_Model_Ums.entity.basic.IdentityLong\">";
            xml+="\n<value>111</value>";
            xml+="\n</id>";
            xml += "\n</Easysys_Model_Ums.entity.module.Module></list>";
            initObject(xml);
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值