XML

一个xml示例

<?xml version="1.0" encoding="utf-8"?>
<gameSettings>
    <setting name="volume" value="80">音量</setting>
    <setting name="language"
        value="chinese" />
</gameSettings>

读取XML文件

//创建XmlDocument对象
XmlDocument xmlDocument = new XmlDocument();

//通过xml文本字符串读取
TextAsset asset = Resources.Load<TextAsset>("TestXml");
string xmlContent = asset.text;
xmlDocument.LoadXml(xmlContent);

//通过文件路径读取
xmlDocument.Load(Application.dataPath + "/Resources/TestXml.xml");

//获取单个节点
XmlNode rootNode = xmlDocument.SelectSingleNode("gameSettings");

// 将根节点转换为XmlElement以便读取属性
XmlElement xmlElement = rootNode as XmlElement;
// 遍历根节点的子节点
foreach (XmlElement rootNodeChildNode in xmlElement.ChildNodes)
{
    //获取节点属性值的三种方式
    string name = rootNodeChildNode.GetAttribute("name");
    string name1 = rootNodeChildNode.Attributes.GetNamedItem("name").Value;
    string value = rootNodeChildNode.Attributes["value"].Value;

    //获取元素信息的方式
    string innerText = rootNodeChildNode.InnerText;
}

//获取多个节点
XmlNodeList xmlNodeList = rootNode.SelectNodes("setting");
foreach (XmlElement settingNode in xmlNodeList)
{
    string name = settingNode.GetAttribute("name");
    string value = settingNode.GetAttribute("value");
}

存储XML文件

//创建XmlDocument对象
XmlDocument xmlDocument = new XmlDocument();

//创建xml固定版本信息
XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
xmlDocument.AppendChild(xmlDeclaration);

//创建根节点
XmlElement root = xmlDocument.CreateElement("gameSettings");
xmlDocument.AppendChild(root);

//创建一个节点
XmlElement element = xmlDocument.CreateElement("volume");
//设置元素内容
element.InnerText = "音量";
//设置属性
element.SetAttribute("name", "volume");
element.SetAttribute("value", "0.8");

//将节点添加到根节点
root.AppendChild(element);

xmlDocument.Save(Application.dataPath + "/Resources/TestXml1.xml");

Json

对Json数据操作的链式封装

public static class JsonExtentions
{        
		public static string ConvertToJson<T>(this T mode)
    {
        return JsonUtility.ToJson(mode);
    }

    public static T ConvertToMode<T>(this string jsonStr)
    {
        return JsonUtility.FromJson<T>(jsonStr);
    }
}

Json数据与可序列化类的互转

//自定义可序列化的类
[Serializable]
public class TestJsonData
{
    public string name = string.Empty;
    public int age = 18;
}

//将类转化为json
TestJsonData data = new TestJsonData();
data.name = "TestJson";
data.age = 20;
string jsonStr = data.ConvertToJson();

//将json转化为类
string jsonStr2 = "{\\"name\\":\\"TestJson\\",\\"age\\":20}";
TestJsonData data2 = jsonStr2.ConvertToMode<TestJsonData>();

json数据的读取

  1. 单次加载多个Json数据包

    适合于不存在类种类,需要同时将多个数据包一次性加载的情况,如:不同玩家的信息列表

//函数示例
public static IEnumerator LoadJsonDataList(string path,Action<List<string>> callback)    
{
    using (UnityWebRequest www = UnityWebRequest.Get(path))
    {
        yield return www.SendWebRequest();         
        if (www.result==UnityWebRequest.Result.ConnectionError)
        {
            Debug.LogError("www错误:" + www.error);
        }
        if (www.isDone)
        {
            DownloadHandler handler = www.downloadHandler;
            yield return new WaitForEndOfFrame();
            string jsonData = System.Text.Encoding.UTF8.GetString(handler.data, 1, handler.data.Length - 2);
            string temp = jsonData.Replace("\\r\\n", "");
            temp = temp.Replace("},", "}⊥");
            string[] spt = temp.Split('⊥');
            List<string> result=new();
            for (int i = 0; i < spt.Length; i++)
            {
                result.Add(spt[i]);
            }
            callback?.Invoke(result);
        }
    }
}

//使用方法
List<ModeName> modeList=new();//构建一个ModeName类的列表
//加载并获取json字符串
StartCoroutine(LoadJsonData(t),(jsonList)=>{
    for(int i=0;i<jsonList.Count;i++)
    {
        ModeName modeName=GetJsonToMode<ModeName>(jsonList[i]);//将每条json数据转成ModeName类并存入modeMame待用
        modeList.Add(modeName);
    }
});
  1. 单次加载单个Json数据包
public static IEnumerator LoadJsonData(string str,Action<string> callback)
{
    using (UnityWebRequest www = UnityWebRequest.Get(tpath.loadPath))
    {
        yield return www.SendWebRequest();
        if (www.result == UnityWebRequest.Result.ConnectionError)
        {
            Debug.LogError("www错误:" + www.error);
        }
        if (www.isDone)
        {
            DownloadHandler handler = www.downloadHandler;
            yield return new WaitForEndOfFrame();
            string jsonData = System.Text.Encoding.UTF8.GetString(handler.data, 0, handler.data.Length );
            string temp = jsonData.Replace("\\r\\n", "");
            callback?.Invoke(temp);
        }
    }
}

//使用方法
ModeName modeName=new();//构建一个ModeName类的列表
//加载并获取json字符串
StartCoroutine(LoadJsonData(t),(result)=>{
    modeName=GetJsonToMode<ModeName>(result);//将json数据转成ModeName类并存入modeMame待用
});

Binary

对二进制数据操作的链式封装

// 将二进制转换为可序列化类
public static T ConvertToMode<T>(this byte[] binaryData)
{
    MemoryStream ms = new MemoryStream(binaryData);
    ms.Position = 0;
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    var mode = (T)binaryFormatter.Deserialize(ms);
    ms.Close();
    return mode;
}

// 将可序列化类转换为二进制
public static byte[] ConvertToBinary<T>(this T mode)
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(ms, mode);
    var bytes = ms.GetBuffer();
    ms.Close();
    return bytes;
}

// 将二进制数据转换为字符串
public static string ConvertToString(this byte[] data)
{
    return System.Convert.ToBase64String(data);
}

// 将字符串转换为二进制数据
public static byte[] ConvertToBinary(this string str)
{
    return System.Convert.FromBase64String(str);
}