利用反射让Model与Xml互转的通用方法

来源:互联网 发布:java lambda filter 编辑:程序博客网 时间:2024/05/22 07:53

Model与XML互相转换  

/// <summary>  
        /// XML转化为Model的方法  
        /// </summary>  
        /// <param name="xml">要转化的XML</param>  
        /// <param name="SampleModel">Model的实体示例,New一个出来即可</param>  
        /// <returns></returns>    
        public static object XMLToModel(string xml, object SampleModel)
        {
            if (string.IsNullOrEmpty(xml))
                return SampleModel;
            else
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xml);

                XmlNodeList attributes = xmldoc.SelectSingleNode("/NewDataSet/Table").ChildNodes;
                foreach (XmlNode node in attributes)
                {
                    foreach (PropertyInfo property in SampleModel.GetType().GetProperties())
                    {
                        if (node.Name == property.Name)
                        {
                            if (node.InnerText != "")
                            {
                                if (property.PropertyType == typeof(System.Guid))
                                    property.SetValue(SampleModel, new Guid(node.InnerText), null);
                                else
                                    property.SetValue(SampleModel, Convert.ChangeType(node.InnerText, property.PropertyType), null);
                            }
                            else
                                property.SetValue(SampleModel, null, null);
                        }
                    }
                }
                return SampleModel;
            }
        }

        /// <summary>  
        /// Model转化为XML的方法  
        /// </summary>  
        /// <param name="model">要转化的Model</param>  
        /// <returns></returns>    
        public static string ModelToXML(object model)
        {
            XmlDocument xmldoc = new XmlDocument();
            XmlElement ModelNode = xmldoc.CreateElement("Table");
            xmldoc.AppendChild(ModelNode);

            if (model != null)
            {
                foreach (PropertyInfo property in model.GetType().GetProperties())
                {
                    XmlElement attribute = xmldoc.CreateElement(property.Name);
                    if (property.GetValue(model, null) != null)
                        attribute.InnerText = property.GetValue(model, null).ToString();
                    else
                        attribute.InnerText = "";
                    ModelNode.AppendChild(attribute);
                }
            }

            return xmldoc.OuterXml;
        }

 

http://blog.csdn.net/baple/article/details/7263651

0 0
原创粉丝点击