using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; using UnityEngine; public static class XmlHelper { /// /// 序列化--内存流 /// /// 对象 /// 类型 /// public static string SerializeObject(object pObject, Type t) { string XmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(t); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, pObject); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); //Debug.Log("" + XmlizedString); return XmlizedString; } /// /// 字节转string /// /// 字节数组 /// private static string UTF8ByteArrayToString(byte[] characters) { UTF8Encoding encoding = new UTF8Encoding(); string constructedString = encoding.GetString(characters); return (constructedString); } /// /// 反序列化 /// /// string内容 /// 类型 /// public static object DeserializeObject(string filePath, Type t) { FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); XmlSerializer xs = new XmlSerializer(t); //MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(fileStream)); //XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); return xs.Deserialize(fileStream); } /// /// 字符串转字节数组 /// /// 字符内容 /// private static byte[] StringToUTF8ByteArray(string pXmlString) { UTF8Encoding encoding = new UTF8Encoding(); byte[] byteArray = encoding.GetBytes(pXmlString); return byteArray; } /// /// 序列化--XML文件 /// /// 对象 /// 类型 /// 生成的xml路径 public static bool SerializeObjectXML(object pObject, Type t, string XMLPath) { XmlWriterSettings ws = new XmlWriterSettings(); ws.Encoding = Encoding.UTF8; try { XmlWriter xmTextWriter = XmlWriter.Create(XMLPath, ws); XmlSerializer xmlFormat = new XmlSerializer(t); xmlFormat.Serialize(xmTextWriter, pObject); xmTextWriter.Close(); return true; } catch (Exception e) { Debug.Log(e.Message); return false; } } }