码迷,mamicode.com
首页 > Windows程序 > 详细

C#XML与二进制相互转换

时间:2016-01-20 22:55:47      阅读:366      评论:0      收藏:0      [点我收藏+]

标签: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都可以.结果:

技术分享

看结果,中文的话都改变了,英文还隐隐约约看得到配置信息.目前就这样了,毕竟中国游戏配置一大片都是中文的.另外还要感谢万能的技术论坛,一部分代码是看来自:http://www.cnblogs.com/jesszhu/archive/2013/08/22/3276556.html

如果读者有更好的方法,请不灵赐教.

本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1736885

C#XML与二进制相互转换

标签:c# xml 二进制

原文地址:http://aonaufly.blog.51cto.com/3554853/1736885

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!