下面的代码,我试图保存和加载一个播放器类和从xml文档。我有写部分工作,但我有一些麻烦与存储在playerElement中的数据重新填充播放器对象。我宁愿不使用xml序列化器类。
public class Player
{
public string Name { get; set; }
public int HitPoint { get; set; }
public int ManaPoint { get; set; }
}
public Player LoadPlayer(XElement playerElement)
{
Player player = new Player();
PropertyInfo[] properties = typeof(Player).GetProperties();
foreach (XAttribute attribute in playerElement.Attributes())
{
PropertyInfo property = typeof(Player).GetProperty(attribute.Name.ToString());
if (property != null)
{
object dataValue = Convert.ChangeType(attribute.Value, property.PropertyType);
property.SetValue(player, dataValue);
}
}
return player;
}
public override void Write(Player value)
{
PropertyInfo[] properties = typeof(Player).GetProperties();
XElement playerElement = new XElement(XmlChildName);
foreach (PropertyInfo property in properties)
{
playerElement.Add(new XAttribute(property.Name, property.GetValue(value, null).ToString()));
}
_doc.Root.Add(playerElement);
_doc.Save(Path);
}
我想你需要这样的东西。我将遍历反向到属性,而不是属性。如果存在带有属性名称的属性,则更改为:
PropertyInfo[] properties = typeof(Player).GetProperties();
foreach (XAttribute attribute in playerElement.Attributes())
{
PropertyInfo pi = properties.Where(x => x.Name == attribute.Name).FirstOrDefault();
if (pi != null)
{
pi.SetValue(player, attribute.Value);
}
}