新建2个脚本
脚本2个代码如下:
// 脚本1 TestSertial using System.Collections.Generic; using System.Xml.Serialization; [System.Serializable] public class TestSertial { [XmlAttribute("ID")] public int ID { get; set; } [XmlAttribute("Name")] public string Name { get; set; } //[XmlAnyAttribute] //public int Age { get; set; } [XmlElement("_list")] public List<int> _list{get;set;} } //脚本2 SerializeDemo using System.Collections.Generic; using System.IO; using System.Xml.Serialization; using UnityEngine; public class SerializeDemo : MonoBehaviour { // Start is called before the first frame update void Start() { SerializeTestIt(); } void SerializeTestIt() { TestSertial testSertial = new TestSertial(); testSertial.ID = 1; testSertial.Name = "测试"; //testSertial.Age = 18; testSertial._list = new List<int>(); testSertial._list.Add(2); testSertial._list.Add(111); XmlSerializeTo(testSertial); } void XmlSerializeTo(TestSertial testSertial) { //string filePath = Application.dataPath + @"demo.xml"; string filePath = Application.dataPath + "/demo.xml"; FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); StreamWriter sw = new StreamWriter(fileStream, System.Text.Encoding.UTF8); XmlSerializer xml = new XmlSerializer(testSertial.GetType()); xml.Serialize(sw, testSertial); sw.Close(); fileStream.Close(); } }挂载 SerializeDemo脚本到空物体就生成了demo.xml文件