unity C# xml 根据对象属性值xml文件数据读写

描述:根据object的属性值将数据写入到xml中,读取xml内数据根据属性值。节点名称为类名称、属性名称

1.xml文件读取和写入脚本

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using UnityEngine;

public class XmlManager : Singleton<XmlManager>
{
    private XmlManager() { }

    public static Dictionary<TableType, Dictionary<int,object>> map = null;
    /// <summary>
    /// 根路径
    /// </summary>
    public const string RootPath = "Root/";
    /// <summary>
    /// 文本路径
    /// </summary>
    string path = Application.streamingAssetsPath +"/ProjectMessage.xml";

    /// <summary>
    /// 读取xml
    /// </summary>
    public void LoadXml()
    {
        map = new Dictionary<TableType, Dictionary<int, object>>();
        //创建xml文档
        XmlDocument xml = new XmlDocument();
        xml.Load(path);
        for (int i = 0; i < (int)TableType.MaxValue; i++)
        {
            string nodeName = ((TableType)i).ToString();
            object obj = ReflectionHelper.CreateInstance(nodeName + "Model");
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            if (properties.Length <= 0) continue;

            Dictionary<int, object> datas = new Dictionary<int, object>();
            //得到objects节点下的所有子节点
            XmlNode node = xml.SelectSingleNode(RootPath + nodeName);
            Debug.Log("XmlManager::LoadXml - ProjectNodeType:" + nodeName + "-count:" + node.ChildNodes.Count);
            int id = Convert.ToInt32(node.SelectSingleNode("id").InnerText);
            for (int j = 0; j < properties.Length; j++)
            {
                string name = properties[j].Name;
                //Debug.Log(name.ToString() + "==" + properties[j].PropertyType.ToString());
                if (properties[j].PropertyType.ToString() == "System.Int32")
                {
                    properties[j].SetValue(obj, Convert.ToInt32(node.SelectSingleNode(name).InnerText), null);
                }
                else if(properties[j].PropertyType.ToString() == "System.string")
                {
                    properties[j].SetValue(obj, node.SelectSingleNode(name).InnerText, null);
                }

                Debug.Log(properties[j].PropertyType.ToString() + "=" + name + "=" + node.SelectSingleNode(name).InnerText);
            }
            datas[id] = obj;
            if (datas == null) continue;
            map.Add((TableType)i, datas);
        }
    }

    /// <summary>
    /// 获得数据
    /// </summary>
    /// <typeparam name="T">泛型类型</typeparam>
    /// <param name="type">表名称</param>
    /// <param name="id">主键id</param>
    /// <returns></returns>
    public T GetData<T>(TableType type, int id)
    {
        if(map.ContainsKey(type))
        {
            if (map[type].ContainsKey(id))
                return (T)map[type][id];
        }
        return default(T);
    }

    /// <summary>
    /// 获取表里面的数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="node"></param>
    /// <returns></returns>
    public List<object> GetTable(TableType node)
    {
        if(map.ContainsKey(node))
        {
            return new List<object>(map[node].Values);
        }
        return null;
    }

    /// <summary>
    /// 写入数据
    /// </summary>
    public void WriteXml(Dictionary<TableType, List<object>> dic)
    {
        XmlDocument xmlDocument = new XmlDocument();
        XmlElement root = xmlDocument.CreateElement(RootPath);
        foreach (var item in dic)
        {
            XmlElement tableName = xmlDocument.CreateElement(item.Key.ToString());
            for (int i = 0; i < item.Value.Count; i++)
            {
                //获取object的属性信息
                PropertyInfo[] properties = item.Value[i].GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                for (int j = 0; j < properties.Length; j++)
                {
                    XmlElement info = xmlDocument.CreateElement(properties[j].Name);

                    //获取属性的值并写进节点内
                    info.InnerText = properties[j].GetValue(item.Value[i], null).ToString();

                    tableName.AppendChild(info);
                }
            }
            root.AppendChild(tableName);
        }
        xmlDocument.AppendChild(root);
        xmlDocument.Save(path);
        Debug.Log("写入保存成功");
    }
}

/// <summary>
/// Xml节点名称 映射表名称
/// </summary>
public enum TableType
{
    /// <summary>
    /// 角色表
    /// </summary>
    Role,
    MaxValue,
}

2.单利模板

//********************************************************************
// 文件名: Singleton
// 描述: 单利模板
// 作者: 
// 创建时间: 2/15/2017 3:40:36 PM
//********************************************************************

    using UnityEngine;
    using System.Collections;
    using System.Reflection;
    using System;

public abstract class Singleton<T> where T : Singleton<T>
{
    private static T instance;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                //先获取所有非public的构造方法
                ConstructorInfo[] ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
                //从ctors中获取无参的构造方法
                ConstructorInfo ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
                if (ctor == null)
                    throw new Exception("Non-public ctor() not found!");
                // 调用构造方法
                instance = ctor.Invoke(null) as T;
            }

            return instance;
        }
    }

    public virtual void Init() { }
}

3.角色Model数据脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 角色数据
/// </summary>
public class RoleModel {
    /// <summary>
    /// id
    /// </summary>
    public int id { get; set; }
    /// <summary>
    /// 角色名称
    /// </summary>
    public string name { get; set; }
    /// <summary>
    /// 角色描述
    /// </summary>
    public string describle { get; set; }
    /// <summary>
    /// 血量
    /// </summary>
    public int blood { get; set; }
    /// <summary>
    /// 攻击值
    /// </summary>
    public int attackValue { get; set; }
}

4.生成读取的xml文件内容

<?xml version="1.0" encoding="utf-8"?>

<Root>
  <Role>
    <id>0</id>
    <name>Test</name>
    <describle>Test</describle>
    <blood>100</blood>
    <attackValue>1</attackValue>
  </Role>
</Root>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值