Unity中将类对象保存到XML中

前端之家收集整理的这篇文章主要介绍了Unity中将类对象保存到XML中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码包含两个功能

(1)在Unity中在本地创建XML文件,将类对象转换为字符串保存到XML文件

(2)将存入的XML文件读取出来转换为相应的 类对象


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

public class AAA
{
    public int num;
    public BBB bbb;
    public AAA()
    {
        num = 0;
        bbb = new BBB();
    }
}

public class BBB
{
    string name;
    public BBB()
    {
        name = "aaaaa";
    }
}

// 将类对象保存为 XML, 将XML读取为类对象
public class WriteReadTxt : MonoBehavIoUr {

    string path = "";

    void Start()
    {
        path = Application.dataPath + "StreamingAssets/AAA/1.xml";
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))  //  保存对象
        {
            AAA aaa = new AAA();
            CreateWriteXML<AAA>( path,aaa,true);  // 将类直接保存为 XML文件
        }

        if (Input.GetKeyDown(KeyCode.D))   // 读取对象
        {
            AAA aaa = new AAA();
            aaa = ReadXmlFile<AAA>(path);  // 将读取的XML文件转换为类
        }
    }

    // 创建写入文件 , 参数1 文件路径, 参数 2 写入信息,参数3 是否删除之前的重新创建
    public void CreateWriteFile(string path,string info,bool isRelace) 
    {
        StreamWriter sw;
        FileInfo t = new FileInfo( path); //获取路径下文件信息

		if (t.Exists && isRelace)  //如果存在则删除
		{
			File.Delete(path);
		}
		
        if (!t.Exists)        //如果文件不存在则创建一个
        {
			sw = t.CreateText();
        }
        else 
        {
            sw = t.AppendText();
        }
        sw.WriteLine( info);   //写入信息
        sw.Close();
        sw.Dispose();
    }
    //读取文件, 参数1 文件路径, 参数2 保存路径的集合
    public List<string> ReadTxtFile(string path,List<string> saveList) 
    {
        FileInfo info = new FileInfo(path);  //获取路径下文件信息
        if (!info.Exists)   //如果不存在返回
        {
			Debug.Log("!exist    " + path);
            return saveList;
        }

        StreamReader sr = null;
        sr = File.OpenText(path);  //存在则打开文件

        string line;
        while ((line = sr.ReadLine()) != null)  // 一行一行读取文件
        {
            saveList.Add(line);    //向保存文件集合添加 路径字符串
        }

        sr.Close();
        sr.Dispose();

        return saveList;
    }
    // 参数1 路径,参数2 需要保存的类,参数3 是否需要替换
    public void CreateWriteXML<T>( string path,T t,bool isRelace) 
    {
        string data = SerializeObject<T>(t);  // 将类对象转换为 字符串
        CreateWriteFile(path,data,isRelace);
    }

    public T ReadXmlFile<T>(string path)
    {
        List<string> dataList = new List<string>();
        string data = "";
        dataList = ReadTxtFile(path,dataList);

        foreach (string str in dataList)
        {
            data += str;
        }

        T t = (T)DeserializeObject<T>(data);

        return t;
    }

    private string UTF8ByteArrayToString(byte[] characters)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        string constructedString = encoding.GetString(characters);
        return (constructedString);
    }

    private byte[] StringToUTF8ByteArray(string pXmlString)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] byteArray = encoding.GetBytes(pXmlString);
        return byteArray;
    }
    // 保存xml 前先将 类对象转换为 字符串
    private string SerializeObject<T>(object pObject) 
    {
        string XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        //XmlSerializer xs = new XmlSerializer(typeof(UserData));
        XmlSerializer xs = new XmlSerializer(typeof(T));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream,Encoding.UTF8);
        xs.Serialize(xmlTextWriter,pObject);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString;
    }
    // 将读取的xml字符串转换为 类对象
    private object DeserializeObject<T>(string pXmlizedString)  
    {
        //XmlSerializer xs = new XmlSerializer(typeof(UserData));
        XmlSerializer xs = new XmlSerializer(typeof(T));
        MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream,Encoding.UTF8);
        return xs.Deserialize(memoryStream);
    }
}

猜你在找的XML相关文章