Unity(四十四):XML、Yaml 读写

XML读写

在这里插入图片描述

using UnityEngine;
using System.IO;
using System.Xml;

namespace Example_01.Scripts
{
    
    
    public class CreateXMLFile : MonoBehaviour
    {
    
    
        private void Create()
        {
    
    
            string path = Path.Combine(Application.dataPath, "test.xml");

            // 创建XmlDocument
            XmlDocument xmlDoc = new XmlDocument();

            // 创建XML声明
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(xmlDeclaration);

            // 在节点中写入数据
            XmlElement root = xmlDoc.CreateElement("XmlRoot");
            xmlDoc.AppendChild(root);
            XmlElement group = xmlDoc.CreateElement("Group");
            group.SetAttribute("nick-name", "ProsperLee");
            group.SetAttribute("age", "25");
            group.SetAttribute("height", "1.71");
            root.AppendChild(group);

            // 保存成XML文件
            xmlDoc.Save(path);
        }

        private void Read()
        {
    
    
            string path = Path.Combine(Application.dataPath, "test.xml");

            // 文件不存在return出去
            if (!File.Exists(path)) return;

            // 创建XmlDocument
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(path); // 字符串读取使用 xmlDoc.LoadXml(xmlStr);
            

            // 读取节点并输出XML字符串
            using StringWriter stringWriter = new StringWriter();
            using XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
            xmlDoc.WriteTo(xmlTextWriter);
            xmlTextWriter.Flush();
            Debug.Log(stringWriter.ToString());

            // 遍历节点
            XmlNode nodes = xmlDoc.SelectSingleNode("XmlRoot");
            foreach (XmlNode node in nodes.ChildNodes)
            {
    
    
                Debug.Log(node.Attributes["nick-name"].Value); // ProsperLee
                Debug.Log(node.Attributes["age"].Value); // 25
                Debug.Log(node.Attributes["height"].Value); // 1.71
            }
        }

        private void Modify()
        {
    
    
            string path = Path.Combine(Application.dataPath, "test.xml");

            // 文件不存在return出去
            if (!File.Exists(path)) return;

            // 创建XmlDocument
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(path);

            // 遍历节点
            XmlNode nodes = xmlDoc.SelectSingleNode("XmlRoot");
            foreach (XmlNode node in nodes.ChildNodes)
            {
    
    
                node.Attributes["nick-name"].Value = "Lee";
            }

            // 保存成XML文件
            xmlDoc.Save(path);
        }

        private void OnGUI()
        {
    
    
            if (GUILayout.Button("创建XML文件")) Create();
            if (GUILayout.Button("读取XML文件")) Read();
            if (GUILayout.Button("修改XML文件")) Modify();
        }
    }
}

Yaml读写

导入 YamlDotNet for Unity
在这里插入图片描述

在这里插入图片描述

using System.Collections.Generic;
using System.IO;
using UnityEngine;
using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization;

namespace Example_01.Scripts
{
    
    
    public class CreateYamlFile : MonoBehaviour
    {
    
    
        private class PersonInfo
        {
    
    
            public string NickName {
    
     get; set; }
            public int Age {
    
     get; set; }
            public float Height {
    
     get; set; }
            public List<string> Hobbies {
    
     get; set; }
        }

        private PersonInfo _personInfo;

        private string _path;

        private IDictionary<YamlNode, YamlNode> _yn;

        private void Start()
        {
    
    
            _path = Path.Combine(Application.streamingAssetsPath, "yaml.txt");
            
            _personInfo = new PersonInfo
            {
    
    
                NickName = "ProsperLee",
                Age = 25,
                Height = 1.71f,
                Hobbies = new List<string> {
    
     "Coding", "美女", "钱" }
            };
        }

        private void OnGUI()
        {
    
    
            if (GUILayout.Button("序列化yaml字符串 并 存储"))
            {
    
    
                // 序列化yaml字符串
                Serializer serializer = new Serializer();
                string yaml = serializer.Serialize(_personInfo);
                Debug.Log(yaml);
                
                // 写入文件
                File.WriteAllText(_path, yaml);
            }

            if (GUILayout.Button("反序列化成类对象"))
            {
    
    
                string yaml = File.ReadAllText(_path);

                // 反序列化成类对象
                Deserializer deserializer = new Deserializer();
                PersonInfo data = deserializer.Deserialize<PersonInfo>(yaml);
                Debug.Log($"{
      
      data.NickName} --- {
      
      data.Age} --- {
      
      data.Height} --- {
      
      string.Join(",", data.Hobbies.ToArray())}");
            }

            if (GUILayout.Button("读取配置"))
            {
    
    
                string yaml = File.ReadAllText(_path);
                
                StringReader sr = new StringReader(yaml);
                YamlStream ys = new YamlStream();
                ys.Load(sr);
                
                // 读取root节点
                YamlMappingNode yamlMappingNode = (YamlMappingNode)ys.Documents[0].RootNode;
                _yn = yamlMappingNode.Children;
                Debug.Log($"{
      
      _yn["NickName"]} --- {
      
      _yn["Age"]} --- {
      
      _yn["Height"]} --- {
      
      _yn["Hobbies"]}");
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43526371/article/details/123951160