XmlSerializationの例

2711 ワード

1.シーケンス化するオブジェクトの準備
[Serializable()]

public class SerializableType

{

    public string StringValue { get; set; }

    public bool BoolValue { get; set; }

    public int IntValue { get; set; }

    public AnotherType AnotherTypeValue { get; set; }

    public List<string> ListValue { get; set; }



    [NonSerialized()]

    private int ignoredField = 1;



    public SerializableType()

    {

        ListValue = new List<string>();

        AnotherTypeValue = new AnotherType();

    }

};



[Serializable()]

public class AnotherType

{

    public string StringValue { get; set; }

    public int IntValue { get; set; }

};




 
2.シーケンス化
 
    static void Serialize(SerializableType instance)

    {

        XmlSerializer serializer = new XmlSerializer(typeof(SerializableType));



        using (StreamWriter streamWriter = File.CreateText("CSXmlSerialization.xml")) {

            serializer.Serialize(streamWriter, instance);

        }

    }




 
 
3.デシーケンス化
 
    static SerializableType Deserialize()

    {

        var deserializedInstance = new SerializableType();

        var serializer = new XmlSerializer(typeof(SerializableType));



        using (StreamReader streamReader = File.OpenText("CSXmlSerialization.xml")) {

            deserializedInstance = serializer.Deserialize(streamReader) as SerializableType;

        }

        return deserializedInstance;

    }




 
 
4.テストコード
 
    static void Main(string[] args)

    {

        SerializableType st = new SerializableType();

        st.BoolValue = true;

        st.IntValue = 1;

        st.StringValue = "Test String";

        st.ListValue.Add("List Item 1");

        st.ListValue.Add("List Item 2");

        st.ListValue.Add("List Item 3");

        st.AnotherTypeValue.IntValue = 2;

        st.AnotherTypeValue.StringValue = "Inner Test String";



        Serialize(st);



        var dt = Deserialize();



        Console.WriteLine("BoolValue: {0}", dt.BoolValue);

        Console.WriteLine("IntValue: {0}", dt.IntValue);

        Console.WriteLine("StringValue: {0}", dt.StringValue);

        Console.WriteLine("AnotherTypeValue.IntValue: {0}", dt.AnotherTypeValue.IntValue);

        Console.WriteLine("AnotherTypeValue.StringValue: {0}", dt.AnotherTypeValue.StringValue);

        Console.WriteLine("ListValue: ");



        foreach (object obj in dt.ListValue) {

            Console.WriteLine(obj.ToString());

        }

    }