using System;
using System.Xml.Linq;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 读取XML的方法
/// </summary>
/// <typeparam name="T">读取的XML将转换成的类型</typeparam>
public static class ReadXML<T> where T : class
{
/// XML路径
private static string path;
/// 泛型T实例
private static T target;
static ReadXML()
{
}
/// <summary>
/// 设置XML文件路径
/// </summary>
private static void SetXmlPath(string p)
{
path = p;
}
/// <summary>
/// 加载XML文件
/// </summary>
private static XElement LoadXML()
{
if (path == null)
return null;
TextAsset textAsset = (TextAsset)Resources.Load(path);
XElement xml = XElement.Parse(textAsset.text);
return xml;
}
/// <summary>
/// 生成泛型T类的一个对象
/// </summary>
private static void CreateInitiate()
{
Type t = typeof(T);
ConstructorInfo ct = t.GetConstructor(System.Type.EmptyTypes);
target = (T)ct.Invoke(null);
}
/// <summary>
/// 读取XML
/// </summary>
/// <returns>T类型的List</returns>
public static List<T> ReadElements(string path)
{
SetXmlPath(path);
List<T> ts = new List<T>();
XElement xml = LoadXML();
//XElement xml = LinqToXMLAndEncrypt.DecrtyptLoadXML();
foreach (XElement xe in xml.Elements())
{
ts.Add(ReadElement(xe));
}
return ts;
}
/// <summary>
/// 读取XML中的一个XElement元素
/// 由于反射中设置字段值的方法会涉及到赋值的目标类型和当前类型的转化,
/// 所以需要使用Convert.ChangeType进行类型转化
/// </summary>
/// <param name="xml">一个XElement元素</param>
/// <returns>T类型的一个对象</returns>
private static T ReadElement(XElement xml)
{
if (target != null)
{
target = null;
}
CreateInitiate();
Type t = target.GetType();
FieldInfo[] fields = t.GetFields();
string fieldName = string.Empty;
foreach (FieldInfo f in fields)
{
fieldName = f.Name;
if (xml.Attribute(fieldName) != null)
{
f.SetValue(target, Convert.ChangeType(xml.Attribute(fieldName).Value, f.FieldType));
}
}
return target;
}
}
public Dictionary<int, PassCheck_Reward> GetPassCheckRewardDicConfig(List<PassCheck_Reward> list)
{
Dictionary<int, PassCheck_Reward> dic = new Dictionary<int, PassCheck_Reward>();
int count = list.Count;
for (int i = 0; i < count; i++)
{
if (!dic.ContainsKey(list[i].level))
{
dic.Add(list[i].level, list[i]);
}
}
return dic;
}
/// <summary>
/// 通行证的奖励配置
/// </summary>
public Dictionary<int, PassCheck_Reward> passCheckRewardDic = new Dictionary<int, PassCheck_Reward>();
passCheckRewardDic = GetPassCheckRewardDicConfig(ReadXML<PassCheck_Reward>.ReadElements(ConstData.PassCheckDataPath));