Unity 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; }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值