XML序列化

public class Test
{
    public int testpublic = 10;
    private int testPrivate = 11;
    protected int testProtected = 12;
    internal int testInternal = 13;
    public string testPublicStr = "1";
    public int testPro { get; set; }
    public Test2 testClass = new Test2();
}
public class Test2
{
    public int test1 = 1;
    public float test2 = 2.2f;
    public bool test3 = true;
}
public class L3 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //序列化:把对象转化为可传输的字节序列的过程(把想要存储的内容转化为字节序列用于存储或传递)
        //反序列化:把字节序列还原为对象的过程(把存储或收到的字节序列信息还原为存储内容使用)

        //xml序列化
        //XmlSerializer 把对象序列化为xml
        //StreamWriter 存储文件
        //using 流对象释放和销毁
        //1.准备一个数据结构类
        Test t = new Test();
        //确定存储路径
        string path = Application.persistentDataPath + "/Test.xml";
        //结合using 和 StreamWriter来写入文件
        //括号内的代码:写入一个文件流,如果有该文件就直接打开并修改,如果没有该文件就直接新建一个文件
        //using的新用法,括号中包裹的声明的对象会在大括号语句块结束后会自动释放
        //using在大括号中的语句块结束后会自动调用对象的Dispose方法让其进行销毁
        //using一般都是配合内存占用较高或者有读写操作时进行使用的
        using(StreamWriter sw = new StreamWriter(path))
        {
            //2.进行序列化
            XmlSerializer serializer = new XmlSerializer(typeof(Test));
            //通过序列化对象对类对象进行翻译,将其翻译成xml文件写入对应文件中
            //第一个参数:文件流对象
            //第二个参数:想要被翻译的对象
            //serialize的类型必须和传入对象类型一致
            serializer.Serialize(sw, t);
        }
        //该方法只能存储数据结构类中的public对象,且不支持字典

        //通过特性设置属性
        //[XmlAttribute()]
        //通过特性设置属性并修改名字
        //[XmlAttribute("TestName")]
        //通过特性修改元素名字
        //[XmlElement("TestName")]
        //通过特性修改一个数组或者List
        //[XmlArray()]
        //通过特性修改一个数组或者List下面所有同名子对象
        //[XmlArrayItem("TestName")]
    }
}
posted @ 2025-03-24 17:28  cannedmint  阅读(2)  评论(0)    收藏  举报