LoginSignup
3
3

More than 5 years have passed since last update.

オブジェクトのXMLシリアル化、逆シリアル化のUtilityクラス

Last updated at Posted at 2015-09-22

概要

オブジェクトを簡単にXMLファイル、XMLファイルをオブジェクトにします。

定義メソッド

 public static class XmlUtility
    {
        public static void Serialize<T>(T obj, string filePath)
        {
            using (var sw = new StreamWriter(filePath, false, new UTF8Encoding(false)))
                new System.Xml.Serialization.XmlSerializer(typeof(T)).Serialize(sw, obj);
        }

        public static T Deserialize<T>(string filePath)
        {
            var returnValue = default(T);
            using (var sr = new StreamReader(filePath, new UTF8Encoding(false)))
                returnValue = (T)new System.Xml.Serialization.XmlSerializer(typeof(T)).Deserialize(sr);
            return returnValue;
        }
    }

使用コード


class MainClass
{
    public static void Main()
    {
        var sample = new SampleClass() { Message = "test" };

        // 書き込み(シリアル化
        sample.Save();

        // 読み込み(逆シリアル化
        var sample2 = SampleClass.Load();
    }
}

public class SampleClass
{
    public int Number;
    public string Message;
    public static readonly string FilePath = @".\sampleclass.xml";

    public static SampleClass Load()
    {
        return XmlUtility.Deserialize<SampleClass>(FilePath);
    }

    public void Save()
    {
        XmlUtility.Serialize<SampleClass>(this, FilePath);
    }
}

注意

シリアル化したいオブジェクトがArrayList、Hashtable、Dictionaryなどである場合は、このままではうまく行きません。(参考 DOBON.NETより)

参考

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3