예제 #1
0
        /// <summary>
        /// 反序列化操作
        /// </summary>
        public object Deserialize()
        {
            if (null == XmlDoc.DocumentElement)
            {
                throw new InvalidDataException(string.Format("{0}, 没有加载XML内容", MethodBase.GetCurrentMethod().Name));
            } // 验证XML内容是否被成功加载

            //XmlRootAttribute attr = SerializeObjectType.GetCustomAttributes(true)?.First(ca => "XmlRootAttribute" == ca.GetType().Name) as XmlRootAttribute;
            var customAttrs       = SerializeObjectType.GetCustomAttributes(true);
            XmlRootAttribute attr = (null != customAttrs) ? customAttrs.First(ca => "XmlRootAttribute" == ca.GetType().Name) as XmlRootAttribute : null;

            if (null == attr)
            {
                throw new XmlException(string.Format("{0}, 待反序列化的数据类型({1})不包含可序列化的XmlRoot属性", MethodBase.GetCurrentMethod().Name, SerializeObjectType));
            }

            if (NodeNameMatch(XmlDoc.DocumentElement, attr.ElementName))
            {
                try
                {
                    _serializeObj = SerializeObjectType.Assembly.CreateInstance(SerializeObjectType.FullName);

                    // 获取序列化实体的成员变量和属性
                    List <MemberInfo> miList = new List <MemberInfo>(1);
                    miList.AddRange(SerializeObj.GetType().GetFields());
                    miList.AddRange(SerializeObj.GetType().GetProperties());

                    // 解析所有子节点
                    ParseNodes(XmlDoc.DocumentElement.ChildNodes, ref _serializeObj, miList);
                }
                catch (Exception ex)
                {
                    MyLog.Instance.Error(ex, "在{0}中,反序列化{1}实体异常。", MethodBase.GetCurrentMethod().Name, SerializeObjectType);
                }
            }
            else
            {
                throw new XmlException(string.Format("{0}, 待反序列化的数据类型({1})与XML内容不匹配", MethodBase.GetCurrentMethod().Name, SerializeObjectType));
            } // if (NodeNameMatch(XmlDoc.DocumentElement, attr.ElementName)) else

            return(SerializeObj);
        }