让XML与实体类一一对应,这样,如果把一个实体转换成XML写入数据库,就不用一一地加节点,反过来,读出数据库的XML,也不用一一地赋值给Model。
把实体转化为XML时,可以使用反射,读出所有属性,再对属性一一给XML的对应节点赋值。反过来,把XML转化为实体时,也使用反射,对XML的固定节点下的所有节点遍历,一一与实体属性比较赋值。以下是互相转化的代码.由于Null比较特殊,所以用[Null]代替,那么,实体中就不能用[Null]这个值了
- #region Model与XML互相转换
- /// <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("Model");
- 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 = "[Null]";
- ModelNode.AppendChild(attribute);
- }
- }
- return xmldoc.OuterXml;
- }
- /// <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("Model").ChildNodes;
- foreach (XmlNode node in attributes)
- {
- foreach (PropertyInfo property in SampleModel.GetType().GetProperties())
- {
- if (node.Name == property.Name)
- {
- if (node.InnerText != "[Null]")
- {
- 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;
- }
- }
- #endregion
为什么说这个方法很通用呢?在设计数据库的时候,很多人都会发现总有字段设计不全的,或者说,当时设计好了,后来要改动。比如说描述计算机的属性表,开始只考虑台式机,后来要加上笔记本,而笔记本有个属性“重量”是必须的,而台式机有没有则没有关系,这时候改变数据库会很麻烦。而利用这个方法可以把一些无关重要的属性放在一个字段中,采用XML或NVARCHAR或NTEXT保存,程序中写个实体类,保存时,转化为XML保存,读出时,把XML转化为Model,这样只要改动实体类,就可以加减属性,并且会把原有数据相同的属性值保留,而不会出错。