天天看點

一起談.NET技術,如何将XML與OBJECT進行互相轉換(泛型以及通用方法)

還有就是對于MVC3,Razor實在太給力了,扔掉MVC2吧,哈哈,@确實挺不錯的。

  在ORMCodeHelper中,對于配置檔案的使用的思路還是不錯的,哥學以緻用,提煉個泛型的出來(其實最主要的還是插件開發的架構)。對于XML與OBJECT的轉換來說,下面講的是一種Serialize方法。其實哥還有另外一種通過反射将XML轉換成對象的方法,不過,涉及到公司****,那種方法還是不寫了。當然,那種方法哥是可以橫着寫了(因為哥早就背在心裡了),哈哈,通用的代碼....

  先看代碼,如下:

    public static class Serializer

    {

        public static void Serialize<T>(string filePath, T[] array)  where T:new()

        {

            if (string.IsNullOrEmpty(filePath)||

                array == null||array.Length==0)

            {

                return;

            }

            try

                XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory();

                XmlSerializer xmlSerializer =

                    xmlSerializerFactory.CreateSerializer(array.GetType(), typeof(T).Name);

                Stream stream = new FileStream(filePath, FileMode.Create);

                xmlSerializer.Serialize(stream, array);

                stream.Close();

            catch

        }

        public static void Serialize(string filePath, object obj)

            if (string.IsNullOrEmpty(filePath) || obj == null)

                    xmlSerializerFactory.CreateSerializer(obj.GetType(), obj.GetType().Name);

                xmlSerializer.Serialize(stream, obj);

    }

        public static List<T> Deserialize<T>(string filePath)  where T:new()

            List<T> results=new List<T>();

            if (string.IsNullOrEmpty(filePath)||!File.Exists(filePath))

                return results;

            object obj = null;

                    xmlSerializerFactory.CreateSerializer(typeof(T[]), typeof(T).Name);

                Stream stream = new FileStream(filePath, System.IO.FileMode.Open);

                obj = xmlSerializer.Deserialize(stream);

                results.AddRange(obj as T[]);

            return results;

        public static object Deserialize(string filePath, Type targetType)

            if (string.IsNullOrEmpty(filePath)||!File.Exists(filePath)

                || targetType == null)

                return null;

                    xmlSerializerFactory.CreateSerializer(targetType, targetType.Name);

                Stream stream = new FileStream(filePath, FileMode.Open);

            return obj;

  從上面4個方法,可以看出主要是通過XmlSerializer将對象序列化為XML以及将XML反序列化為對象,這種方法比較簡單,而且易用。

  (一)Serialize<T>(string filePath, T[] array),Deserialize<T>(string filePath)

  通過單元測試來看看Serialize<T>(string filePath, T[] array)方法生成的XML内容,先注釋掉//DeleteFile(filePath);

public void SerializeTestHelper(AppSetting[] inputs)

            AppSetting[] settings = inputs;

            string filePath = @"d:\" + typeof(AppSetting).Name + ".config";

            Serializer.Serialize<AppSetting>(filePath, settings);

            List<AppSetting> results = Serializer.Deserialize<AppSetting>(filePath);

            int length = results.Count;

            Assert.IsTrue(length == settings.Length);

            for (int index = 0; index < length; index++)

                Assert.IsTrue(results[index].Value == settings[index].Value);

                Assert.IsTrue(results[index].Key == settings[index].Key);

                Assert.IsTrue(results[index].Author == settings[index].Author);

            //DeleteFile(filePath);

  生成的XML如下:

<?xml version="1.0"?>

  <AppSetting>

    <Key>key0</Key>

    <Value>value0</Value>

    <Author>author0</Author>

  </AppSetting>

    <Key>key1</Key>

    <Value>value1</Value>

    <Author>author1</Author>

    <Key>key2</Key>

    <Value>value2</Value>

    <Author>author2</Author>

</ArrayOfAppSetting>

  從上面的單元測試可以看出:通過Serialize<T>(string filePath, T[] array)方法将對象數組生成XML内容,可以通過Deserialize<T>(string filePath)将XML内容轉換成相應的對象數組,内容相一緻。

  (二)Serialize(string filePath, object obj),Deserialize(string filePath, Type targetType)

  通過單元測試來看看Serialize(string filePath, object obj)方法生成的XML内容,先注釋掉//DeleteFile(filePath);

private static void SerializeTestHelper()

            AppSetting setting = new AppSetting()

                Author = "AuthorTest",

                Key = "KeyTest",

                Value = "ValueTest"

            };

            Serializer.Serialize(filePath, setting);

            AppSetting result = Serializer.Deserialize(filePath, typeof(AppSetting)) as AppSetting;

            Assert.IsTrue(result.Value == setting.Value);

            Assert.IsTrue(result.Author == setting.Author);

            Assert.IsTrue(result.Key == setting.Key);

  <Key>KeyTest</Key>

  <Value>ValueTest</Value>

  <Author>AuthorTest</Author>

</AppSetting>

  從上面的單元測試可以看出:通過Serialize(string filePath, object obj)方法将對象生成XML内容,可以通過Deserialize(string filePath, Type targetType)将XML内容轉換成相應的對象,内容相一緻。其中,object也可以是對象數組的,這個留給讀者自己去驗證。

  測試都是可以通過的,這裡僅僅是驗證正确的功能,如下圖:

一起談.NET技術,如何将XML與OBJECT進行互相轉換(泛型以及通用方法)