C#中两种方式将Xml匹配为对象集合2013-11-13一、前言上一篇随笔主要将实体转换成相应的Xml或者Xml对象,未考虑到属性的Attribute特性,以后有时间再整理一下。本文中的Xml匹配涉及到类的特性和属性的特性,并且对该类的匹配进行了相应的优化,尽量将反射引起的性能问题降低最低(其实,对于对象数量不是很多的Xml匹配,性能是可以忽略不计的)。二、类图设计主要思路为:通过反射将与类名的节点匹配,然后匹配属性(属性特性名称或者属性名称)值,设计图如下所示:

类图中各个类的作用如下:PropertyAttribute、ClassAttribute、StringExtension、FuncDictionary的作用详见XmlAttribute与实体的转换和匹配方案(附源码)。AttributeUtility主要用于获取类名和属性名称。ReflectionUtility主要用于获取类型的属性对象与属性对应的特性名称的字典,为匹配进行优化处理。XmlParser主要用于匹配Xml为实体对象。三、具体实现3.1 ReflectionUtility该类主要用于获取某个类型的特性名称和相应的属性对象的字典。返回的类型为Dictionary<string, PropertyInfo>,其中Key为属性的特性名称,而非属性名称,Vaule为对应的属性对象。如此设计,主要是方便后续的操作。主要方法为:public static Dictionary<string, PropertyInfo> GetPropertyMapperDictionary<T>() where T : new(),public static Dictionary<string, PropertyInfo> GetPropertyMapperDictionary(Type type) ,代码如下:
public class ReflectionUtility{public static Dictionary<string, PropertyInfo> GetPropertyMapperDictionary<T>() where T : new(){return GetPropertyMapperDictionary(typeof(T));}public static Dictionary<string, PropertyInfo> GetPropertyMapperDictionary(Type type) {if (type == null){return null;}List<PropertyInfo> properties = type.GetProperties().ToList();var nameMapperDic = new Dictionary<string, PropertyInfo>();string propertyAttributeName = null;foreach (PropertyInfo property in properties){propertyAttributeName = AttributeUtility.GetPropertyName(property);nameMapperDic.Add(propertyAttributeName, property);}return nameMapperDic;}public static IList<string> GetPropertyNames<T>() where T : new(){List<PropertyInfo> properties = typeof(T).GetProperties().ToList();var propertyNames = new List<string>();foreach (PropertyInfo property in properties){propertyNames.Add(AttributeUtility.GetPropertyName(property));}return propertyNames;}}