Unity Xml的简易序列化和反序列化

本文介绍了一个实用的工具类XmlUtility,它提供了类与XML文件之间的相互转换功能。包括从XML文件加载类实例、将类实例保存为XML文件等方法,并支持异常处理确保操作的健壮性。

仿照UnityEngine.JsonUtility,进行简单的类转Xml文件,Xml文件转类封装。

namespace Frameworks
{
    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;

    public static class XmlUtility
    {
        public const string PATH_CONFIG = "/Config/GlobalConfig.xml";

        public static T FromXmlFile<T>(string path) where T : new()
        {
            try
            {
                if (string.IsNullOrEmpty(path))
                    throw new ArgumentNullException(path);

                if (!File.Exists(path))
                    throw new FileNotFoundException(path);

                return (T)FromXmlFile(path, typeof(T), Encoding.UTF8);
            }
            catch (Exception) { return default(T); }
        }

        public static T FromXml<T>(string xml) where T : new()
        {
            return (T)FromXml(xml, typeof(T), Encoding.UTF8);
        }

        public static object FromXml(string xml, Type type, Encoding encoding)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(encoding.GetBytes(xml)))
                {
                    using (StreamReader sr = new StreamReader(ms, encoding))
                    {
                        XmlSerializer xmldes = new XmlSerializer(type);
                        return xmldes.Deserialize(sr);
                    }
                }
            }
            catch (Exception) { return null; }
        }

        public static object FromXmlFile(string path, Type type, Encoding encoding)
        {
            try
            {
                using (StreamReader sr = new StreamReader(path, encoding))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);
                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception) { return null; }
        }

        public static void SaveToXml(object obj, string path)
        {
            try
            {
                if (obj == null)
                    throw new ArgumentNullException("obj");

                if (string.IsNullOrEmpty(path))
                    throw new ArgumentNullException(path);

                string xmlStr = ToXml(obj);

                int filePathLength = path.LastIndexOf('/');
                string filePath = path.Remove(filePathLength, path.Length - filePathLength);
                if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); }

                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.Write(xmlStr);
                    }
                }
            }
            catch (Exception ex) { throw ex; }
        }

        public static string ToXml(object obj)
        {
            return ToXml(obj.GetType(), obj, Encoding.UTF8);
        }

        public static string ToXml(Type type, object obj, Encoding encoding)
        {
            Console.WriteLine(type);
            try
            {
                if (obj == null)
                    throw new ArgumentNullException("obj");

                XmlSerializer ser = new XmlSerializer(type);
                using (MemoryStream stream = new MemoryStream())
                {
                    using (XmlTextWriter writer = new XmlTextWriter(stream, encoding))
                    {
                        writer.Formatting = Formatting.Indented;
                        ser.Serialize(writer, obj);
                    }
                    string xml = encoding.GetString(stream.ToArray());
                    xml = xml.Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
                    return xml;
                }
            }
            catch (Exception ex) { throw ex; }
        }
    }
}
using System; //需要用到MemoryStream using System.IO; using UnityEngine; //引入ProtoBuf命名空间 using ProtoBuf; /// /// 测试类 /// public class TestProtobuf : MonoBehaviour { /// /// 用于测试的数据类 /// [ProtoContract] //声明这个类能被序列化 public class UserData { //声明每一个需要被序列化的成员,编号从1开始 [ProtoMember(1)] public int id; [ProtoMember(2)] public string name; [ProtoMember(3)] public int level; } //测试代码 void Start() { //将要被序列化的UserData示例 UserData user1 = new UserData (); user1.id = 1; user1.name = "User1"; user1.level = 10; //打印user1 Debug.Log (string.Format ("user1-> id:{0}, name:{1}, level:{2}", user1.id, user1.name, user1.level)); //序列化 byte[] buff = null; using (MemoryStream ms = new MemoryStream ()) { Serializer.Serialize (ms, user1); ms.Position = 0; int length = (int)ms.Length; buff = new byte[length]; ms.Read (buff, 0, length); } //输出字节数组 Debug.Log (string.Format("Serialized data-> {0}", BitConverter.ToString(buff))); //反序列化 UserData user2 = default(UserData); using (MemoryStream ms = new MemoryStream (buff)) { user2 = Serializer.Deserialize (ms); } //打印反序列化生成的user2 Debug.Log (string.Format ("user2-> id:{0}, name:{1}, level:{2}", user2.id, user2.name, user2.level)); } } 作者:qufangliu 链接:https://www.jianshu.com/p/d9be1b3d2446 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值