C#XML與二進位相互轉換

來源:互聯網
上載者:User

標籤:c# xml 二進位

關於為什麼需要轉換:本人步入Game行業已經4年了,但是設定檔要麽是原生的XML檔案,要麽是別人的二進位檔案.關於設定檔為啥要轉換成二進位檔案:主要是為了保密,其次才是節省空間的.但是話又說回來了,使用二進位檔案的時候,擷取資訊,需要多一步轉化過程.

再者,在一個Game項目中可能有多個設定檔,本人目前在開發的有100多個,那麼打包成ini二進位是很有必要的.

來個例子:

XMLToBin : XML 與 二進位檔案的相互轉換

family.xml : XML檔案


XMLToBin:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO;using System.Xml.Serialization;using System.Runtime.Serialization.Formatters.Binary;namespace XmlToByte.ainy{    /// <summary>    /// XML的格式轉換    /// </summary>    public class XMLToBin    {        //public string a = "a";        private static XMLToBin instance;        public static XMLToBin Instance        {            get {                if (XMLToBin.instance == null) {                    XMLToBin.instance = new XMLToBin();                }                return XMLToBin.instance;             }            set { XMLToBin.instance = value; }        }        public XMLToBin()        {            if (XMLToBin.instance != null)            {                InstanceNoInstantiationException exp =  new InstanceNoInstantiationException(typeof(XMLToBin));                Console.WriteLine( exp.Message);                throw exp;            }            else            {                XMLToBin.instance = this;            }        }        /// <summary>        /// Object to XML        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="obj"></param>        /// <param name="path"></param>        /// <returns></returns>        public bool Serializer<T>(object obj, string path)        {            FileStream xmlfile = new FileStream(path, FileMode.OpenOrCreate);            //建立序列化對象             XmlSerializer xml = new XmlSerializer(typeof(T));            try            {    //序列化對象                xml.Serialize(xmlfile, obj);                xmlfile.Close();            }            catch (InvalidOperationException)            {                throw;            }            return true;        }        /// <summary>        /// XML to Object        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="path"></param>        /// <returns></returns>        public static T Deserializer<T>(string path)        {            try            {                FileStream xmlfile = new FileStream(path, FileMode.Open);                XmlSerializer xml = new XmlSerializer(typeof(T));                T t = (T)xml.Deserialize(xmlfile);                xmlfile.Close();                return t;            }            catch (InvalidOperationException)            {                throw;            }            catch (FileNotFoundException)            { throw; }            finally            {            }        }        /// <summary>        /// Object to Bin        /// </summary>        /// <param name="obj"></param>        /// <param name="path"></param>        /// <returns></returns>        public bool BinarySerializer(object obj, string path)        {            FileStream Stream = new FileStream(path, FileMode.OpenOrCreate);            //建立序列化對象             BinaryFormatter bin = new BinaryFormatter();            try            {    //序列化對象                bin.Serialize(Stream, obj);                Stream.Close();            }            catch (InvalidOperationException)            {                throw;            }            return true;        }        /// <summary>        /// Bin to Object        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="path"></param>        /// <returns></returns>        public T BinaryDeserializer<T>(string path)        {            try            {                FileStream binfile = new FileStream(path, FileMode.Open);                BinaryFormatter bin = new BinaryFormatter();                //序列化對象                //xmlfile.Close();                T t = (T)bin.Deserialize(binfile);                binfile.Close();                return t;            }            catch (InvalidOperationException)            {                throw;            }            catch (FileNotFoundException)            { throw; }            finally            {            }        }        /// <summary>        /// 讀取文本        /// </summary>        /// <param name="targetPath"></param>        /// <returns></returns>        public string ReadCommon(string targetPath)        {            if (File.Exists(targetPath))            {                //using (StreamReader sr = File.OpenText(targetPath)) // 讀中文將亂碼                string bcStr = "";                using (StreamReader sr = new StreamReader(targetPath, UnicodeEncoding.GetEncoding("GB2312"))) // 解決中文亂碼問題                {                    string readStr;                    while ((readStr = sr.ReadLine()) != null)                    {                        bcStr = bcStr + readStr;                    }                    sr.Close();                }                return bcStr;            }            else            {                Console.WriteLine("Message , 沒有找到檔案{0}", targetPath);                return string.Empty;            }        }    }}

family.xml:

<?xml version="1.0" encoding="utf-8" ?><people>  <husband>    <attribute name ="胡Ainy" age ="26" ></attribute>  </husband>  <wife>    <attribute name ="snow" age="24"></attribute>  </wife>  <daughter>    <attribute name ="ms" age="1"></attribute>  </daughter></people>

測試:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using XmlToByte.ainy;namespace XmlToByte{    class Program    {        static void Main(string[] args)        {            string xml = XMLToBin.Instance.ReadCommon("../../res/family.xml");            Console.WriteLine("family.xml : {0}", xml);            Console.WriteLine("Message -- 轉換成二進位檔案成功:{0}", XMLToBin.Instance.BinarySerializer(xml, "../../res/family.ini"));            //string json = "{peopel={ [ husband={ name=\"ainy\" , age = \"26\" }, wife={ name=\"snow\" , age = \"24\" } ] }}";            //Console.WriteLine("Message -- 轉換成二進位檔案成功:{0}", XMLToBin.Instance.BinarySerializer(json, "../../res/familyJson.ini"));            Console.WriteLine("family.ini : {0}", XMLToBin.Instance.ReadCommon("../../res/family.ini"));            string aXml = XMLToBin.Instance.BinaryDeserializer<string>("../../res/family.ini");            Console.WriteLine("Message -- 轉換成文字檔成功:{0}",aXml );            Console.ReadKey();        }    }}

注意到:其實Json和XML都可以.結果:

650) this.width=650;" src="http://s4.51cto.com/wyfs02/M01/79/F7/wKioL1afS5vTZAGnAACIXoDzvqI820.png" title="QQA1.png" alt="wKioL1afS5vTZAGnAACIXoDzvqI820.png" />

看結果,中文的話都改變了,英文還隱隱約約看得到配置資訊.目前就這樣了,畢竟中國遊戲配置一大片都是中文的.另外還要感謝萬能的技術論壇,一部分代碼是看來自:http://www.cnblogs.com/jesszhu/archive/2013/08/22/3276556.html

如果讀者有更好的方法,請不靈賜教.

本文出自 “Better_Power_Wisdom” 部落格,請務必保留此出處http://aonaufly.blog.51cto.com/3554853/1736885

C#XML與二進位相互轉換

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.