[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,target);
            xWrite.Close();
        }
    }
}
原文链接:https://www.f2er.com/xml/297957.html

猜你在找的XML相关文章