首页 > 代码库 > [Unity 笔记] unity中如何将Object序列化成xml字符串并保存

[Unity 笔记] unity中如何将Object序列化成xml字符串并保存


需要使用到以下这几个c#内置的命名空间。

using System.Xml;
using System.IO;
using System.Xml.Serialization;


序列化并存储xml文件

            XmlTextWriter xWrite = new XmlTextWriter(filename, null);
            XmlSerializer sl = new XmlSerializer(type);
            sl.Serialize(xWrite, target);
            xWrite.Close();


读取xml文件并反序列化

            XmlReader xRead = new XmlTextReader(filename);
            XmlSerializer sl = new XmlSerializer(type);
            object obj = sl.Deserialize(xRead);
            xRead.Close();
            return obj;


完整源码如下:

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

namespace CharacterBase
{
    public class XmlIO
    {
        public static object LoadFromXml(System.Type type, string filename)
        {
            XmlReader xRead = new XmlTextReader(filename);
            XmlSerializer sl = new XmlSerializer(type);
            object obj = sl.Deserialize(xRead);
            xRead.Close();
            return obj;
        }

        public static void SaveToXml(string filename, System.Type type, object target)
        {
            XmlTextWriter xWrite = new XmlTextWriter(filename, null);
            XmlSerializer sl = new XmlSerializer(type);
            sl.Serialize(xWrite, target);
            xWrite.Close();
        }
    }
}



[Unity 笔记] unity中如何将Object序列化成xml字符串并保存