using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class XmlDataMgr_ 
{
    private static XmlDataMgr_ instance = new XmlDataMgr_();
    public static XmlDataMgr_ Instance => instance;
    /// <summary>
    /// 保存数据到本地xml文件中
    /// </summary>
    /// <param name="data">数据对象</param>
    /// <param name="fileName">文件名</param>
    public void SaveData(object data, string fileName)
    {
        //1、得到存储路径
        string path = Application.persistentDataPath + "/" + fileName + ".xml";
        //2、存储文件
        using (StreamWriter write=new StreamWriter(path))
        {
            //3、序列化
            XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());
            xmlSerializer.Serialize(write,data);
        }
    }
    /// <summary>
    /// 从XML文件中读取内容
    /// </summary>
    /// <param name="type">对象类型</param>
    /// <param name="fileName">文件名</param>
    public object LoadData(Type type,string fileName)
    {
        //1、判断文件是否存在
        string path = Application.persistentDataPath + "/" + fileName + ".xml";
        if (!File.Exists(path))
        {
            path = Application.streamingAssetsPath + "/" + fileName + ".xml";
            if (!File.Exists(path))
            {
                //两个路径都找过了 文件不存在 那么就直接 new 一个对象 返回出去 只是里面的值都是默认值
                return Activator.CreateInstance(type);
             }
        }
        //2、文件存在就读取
        using (StreamReader read = new StreamReader(path))
        {
            //3、反序列化 取出数据
            XmlSerializer xmlSerializer = new XmlSerializer(type);
            return xmlSerializer.Deserialize(read);
        }
    }
   
}

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐