我正在尝试编写一个使用反射的方法,以便在遍历 XElement 时获取属性并设置它们的值:
假设我有一个像这样的类,它只为我提供要解析的 XML 值:
class XMLController
{
public string XML
{
get{
return @"<FieldGroup name='People' count='20'>
<Fields>
<Field Name='Jon' LastName='McFly'/>
<Field Name='Michael' LastName='Jackson'/>
</Fields>
</FieldGroup>";
}
}
}
这就是我的对象的样子:
class FieldGroup
{
public string Name {get;set;}
public string Count {get;set;}
public IEnumerable<Field> Fields {get;set;}
}
class Field
{
public string Name {get;set;}
public string LastName {get;set;}
}
映射器方法遍历XElement
并且由于节点名称与对象名称匹配,我认为这有助于更多,但我还没有想出真正有用的东西。我不想传递类型,而是该方法适用于几乎所有以相同格式传入的 XML。
它只知道 XML 节点和属性是匹配名称这一事实。
这是我所做的,但并没有真正奏效:
class XMLObjectMapper
{
public T Map<T>(XElement element) where T: class, new()
{
T entity = (T) Activator.CreateInstance(typeof(T));
if(element.HasAttributes)
{
MapXMLAttributesToObject<T>(element,entity);
}
if(element.HasElements)
{
foreach (var childElement in element.Elements())
{
//if the child element has child elements as well, we know this is a collection.
if(childElement.HasElements)
{
var property = GetProperty<T>(childElement.Name.LocalName);
property.SetValue(entity,new List<property.PropertyType>());
Map<T>(childElement);
}
else
{
var property = GetProperty<T>(childElement.Name.LocalName);
var type = Activator.CreateInstance(property.PropertyType);
type.Dump();
}
}
}
return entity;
}
private void MapXMLAttributesToObject<T>(XElement element, T entity)
{
foreach(XAttribute attribute in element.Attributes())
{
var property = GetProperty<T>(attribute.Name.LocalName);
property.SetValue(entity,attribute.Value);
}
}
private PropertyInfo GetProperty<T>(string propertyName)
{
return typeof(T).GetProperty(propertyName,BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
}
}