Unity3d XML、Excel、Json文件的操作

Unity常用文件格式的操作

  1. Xml文件的操作
    Xml文件是项目中常用的配置文件,以下分别讲解创建、读取、更新的操作。
    需要引用的命名空间:
    using System.IO;
    using System.Xml;
    Xml文件创建示例代码

        string path = System.IO.Path.Combine(Application.dataPath, "data.xml");
        if (File.Exists(path))
        {
            File.Delete(path);
        }
    
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement root = xmlDoc.CreateElement("info");
    
        XmlElement element = xmlDoc.CreateElement("book");
        element.SetAttribute("id", "b1");
        element.SetAttribute("lang", "en");
        XmlElement elementChild1 = xmlDoc.CreateElement("name");
        elementChild1.InnerText = "c++";
        XmlElement elementChild2 = xmlDoc.CreateElement("price");
        elementChild2.InnerText = "570";
    
        XmlElement element1 = xmlDoc.CreateElement("book");
        element1.SetAttribute("id", "b2");
        element1.SetAttribute("lang", "en");
        XmlElement element1Child1 = xmlDoc.CreateElement("name");
        element1Child1.InnerText = "c#";
        XmlElement element1Child2 = xmlDoc.CreateElement("price");
        element1Child2.InnerText = "110";
    
    
        element.AppendChild(elementChild1);
        element.AppendChild(elementChild2);
        element1.AppendChild(element1Child1);
        element1.AppendChild(element1Child2);
        root.AppendChild(element);
        root.AppendChild(element1);
        xmlDoc.AppendChild(root);
    
        xmlDoc.Save(path);
    

    创建的XML文件

    <info>
      <book id="b11" lang="en">
        <name>c++</name>
        <price>570</price>
      </book>
      <book id="b2" lang="en">
        <name>c#</name>
        <price>110</price>
      </book>
    </info>
    

    Xml文件读取示例代码

        string path = System.IO.Path.Combine(Application.dataPath, "data.xml");
        if (!File.Exists(path))
        {
            return;
        }
    
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(path);
    
        XmlNodeList nodeList = xmlDoc.SelectSingleNode("info").ChildNodes;
        foreach(XmlElement node in nodeList)
        {
            //string id = node.GetAttribute("id");
            //string lang = node.GetAttribute("lang");
            Debug.Log("id " + node.GetAttribute("id") + " lang " + node.GetAttribute("lang"));
            foreach (XmlElement e1 in node.ChildNodes)
            {
                Debug.Log(e1.Name + " " + e1.InnerText);
            }
        }
    

    Xml文件更新示例代码

        string path = System.IO.Path.Combine(Application.dataPath, "data.xml");
        if (!File.Exists(path))
        {
            return;
        }
    
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(path);
    
        XmlNodeList nodeList = xmlDoc.SelectSingleNode("info").ChildNodes;
        foreach (XmlElement node in nodeList)
        {
            if (node.GetAttribute("id") == "b1")
                node.SetAttribute("id", "b11");
        }
    
        xmlDoc.Save(path);
    
  2. Excel文件读取需要导入第三方库 EPPlus.dll、Excel.dll、LitJson.dll,可在本文最下面下载Demo
    Excel文件的创建示例代码

        string path = System.IO.Path.Combine(Application.dataPath, "data.xlsx");
        string sheetName = "学生表";
    
        FileInfo excelName = new FileInfo(path);
        if (excelName.Exists)
        {
            excelName.Delete();
            excelName = new FileInfo(path);
        }
    
        //通过ExcelPackage打开文件
        using (ExcelPackage package = new ExcelPackage(excelName))
        {
            //在 excel 空文件添加新 sheet,并设置名称。
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName);
    
            //添加列名
            worksheet.Cells[1, 1].Value = "学号";
            worksheet.Cells[1, 2].Value = "姓名";
            worksheet.Cells[1, 3].Value = "性别";
    
            //添加一行数据
            worksheet.Cells[2, 1].Value = 100001;
            worksheet.Cells[2, 2].Value = "张三";
            worksheet.Cells[2, 3].Value = "男";
    
            //添加一行数据
            worksheet.Cells[3, 1].Value = 100002;
            worksheet.Cells[3, 2].Value = "李四";
            worksheet.Cells[3, 3].Value = "女";
    
            //添加一行数据
            worksheet.Cells[4, 1].Value = 100003;
            worksheet.Cells[4, 2].Value = "王五";
            worksheet.Cells[4, 3].Value = "男";
    
            //添加一行数据
            worksheet.Cells[5, 1].Value = 100004;
            worksheet.Cells[5, 2].Value = "赵六";
            worksheet.Cells[5, 3].Value = "女";
    
            //保存excel
            package.Save();
        }
    

    Excel文件的读取示例代码,注意区分Excel的版本

    	FileStream stream = File.Open(System.IO.Path.Combine(Application.dataPath, "data.xlsx"), FileMode.Open, FileAccess.Read, FileShare.Read);
        //IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);//读取 Excel 1997-2003版本
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);//读取 2007及以后的版本
        DataSet result = excelReader.AsDataSet();
        DataRowCollection dataRowCollection = result.Tables[“学生表”].Rows;
        for (int i = 1; i < dataRowCollection.Count; i++)
        {
            Debug.Log("学号:" + dataRowCollection[i][0] + "--" + "姓名:" + dataRowCollection[i][1] + "--" + "性别:" + dataRowCollection[i][2]);
        }
    
  3. Json 格式的使用
    Unity3d Json有两种方式:LitJson和Newtonsoft.Json,下面分别介绍:
    示例类

    class Student
    {
        public string name;
        public int age;
    }
    

    LitJson的序列化和反序列化代码

    	Student student = new Student();
        student.name = "李四";
        student.age = 20;
        
    	//Json数据序列化
        string jsonStr = JsonMapper.ToJson(student);		
        UnityEngine.Debug.Log(jsonStr);
        
    	//Json数据反序列化的两种方式
        JsonData jd = JsonMapper.ToObject(jsonStr);
        UnityEngine.Debug.Log("name  " + jd["name"].ToString() + " age  " + jd["age"]);
    
        Student stu1 = JsonMapper.ToObject<Student>(jsonStr);
        UnityEngine.Debug.Log("name  " + stu1.name + " age " + stu1.age);
    

    Newtonsoft.Json的序列化和反序列化代码

      	Student student = new Student();
        student.name = "张三";
        student.age = 19;
        
    	//Json数据序列化
        string jsonStr = JsonConvert.SerializeObject(student);
        UnityEngine.Debug.Log(jsonStr);
    	
    	//Json数据反序列化的两种方式
        JObject jd = (JObject)JsonConvert.DeserializeObject(jsonStr);
        UnityEngine.Debug.Log("name  " + jd["name"].ToString() + " age  " + jd["age"]);
        if (jd.Property("name") != null)
            UnityEngine.Debug.Log("Students have schools");
    
        Student stu1 = JsonConvert.DeserializeObject<Student>(jsonStr);
        UnityEngine.Debug.Log("name  " + stu1.name + " age " + stu1.age);
    

    两种方式的时间消耗对比在下面Demo中有所比较,供大家参考:https://download.csdn.net/download/wangningzk123/12566745

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值