Created
April 30, 2012 23:44
-
-
Save rabitarochan/2563704 to your computer and use it in GitHub Desktop.
任意のオブジェクトをXMLファイルにシリアライズするクラス
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Linq; | |
using System.Xml.Serialization; | |
using System.Reflection; | |
namespace Rabitarochan.Serializer | |
{ | |
/// <summary> | |
/// オブジェクトをXMLファイルにシリアライズ/デシリアライズするクラス | |
/// </summary> | |
public static class XmlFileSerializer | |
{ | |
public static void Serialize<T>(T obj, string filePath) | |
{ | |
Serialize(obj, filePath, new Type[]{}); | |
} | |
public static void Serialize<T>(T obj, string filePath, Type baseType) | |
{ | |
var assembly = Assembly.GetAssembly(baseType); | |
var types = assembly.GetTypes().Where(t => t.BaseType == baseType).ToArray(); | |
Serialize(obj, filePath, types); | |
} | |
public static void Serialize<T>(T obj, string filePath, Type[] subTypes) | |
{ | |
XmlSerializer serializer; | |
if (subTypes.Length == 0) | |
{ | |
serializer = new XmlSerializer(typeof(T)); | |
} | |
else | |
{ | |
serializer = new XmlSerializer(typeof(T), subTypes); | |
} | |
using (var fs = new FileStream(filePath, FileMode.Create)) | |
{ | |
serializer.Serialize(fs, obj); | |
} | |
} | |
public static T Deserialize<T>(string filePath) | |
{ | |
return Deserialize<T>(filePath, new Type[] {}); | |
} | |
public static T Deserialize<T>(string filePath, Type baseType) | |
{ | |
var assembly = Assembly.GetAssembly(baseType); | |
var types = assembly.GetTypes().Where(t => t.BaseType == baseType).ToArray(); | |
return Deserialize<T>(filePath, types); | |
} | |
public static T Deserialize<T>(string filePath, Type[] subTypes) | |
{ | |
XmlSerializer serializer; | |
if (subTypes.Length == 0) | |
{ | |
serializer = new XmlSerializer(typeof(T)); | |
} | |
else | |
{ | |
serializer = new XmlSerializer(typeof(T), subTypes); | |
} | |
T result; | |
using (var fs = new FileStream(filePath, FileMode.Open)) | |
{ | |
result = (T)serializer.Deserialize(fs); | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment