Xml序列化与反序列化的一个类

直接上代码,后面是示例用法:

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

[XLua.LuaCallCSharp]
public class XMLSerializable<T>
    where T : XMLSerializable<T>, new()
{
    public void SerializeToFile(string filePath)
    {
        XmlSerializer xs = new XmlSerializer(typeof(T));
        XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
        using (XmlWriter w = XmlWriter.Create(filePath, settings))
            xs.Serialize(w, this); //Serialize
    }

    public static T DeserializeFromFile(string filePath, bool throwExceptionIfFail = false, bool returnEmptyXml = false)
    {
        try
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (Stream s = File.OpenRead(filePath))
                return (T)xs.Deserialize(s); //Deserialize
        }
        catch (Exception ex)
        {
            if (!throwExceptionIfFail)
            {
                Log.Info(ex.ToString());
                if (returnEmptyXml)
                    return new T();
                else
                    return null;
            }
            else
            {
                throw;
            }
        }
    }

    public static T DeserializeFromBytes(byte[] bytes, bool throwExceptionIfFail = false)
    {
        try
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (Stream s = new MemoryStream(bytes))
                return (T)xs.Deserialize(s); //Deserialize
        }
        catch (Exception ex)
        {
            if (!throwExceptionIfFail)
            {
                Log.Info(ex.ToString());
                return null;
            }
            else
            {
                throw;
            }
        }
    }
}

//eg:
public class MyData :
XMLSerializable<MyData>
{
  int id;
  string name;
  
  SomeState state;
}

public static class UseMyData
{
  static MyData data;
  const string fileName;
  public static void Init()
  {
    data = MyData.DeserializeFromFile(fileName)
  }
  
  public static void OnDestroy()
  {
    data.SerializeToFile(fileName);
  }
}


 

posted on 2019-03-13 10:42  tang_huipang  阅读(356)  评论(0)    收藏  举报