技術をかじる猫

適当に気になった技術や言語、思ったこと考えた事など。

XMLとオブジェクトでマッピングを試みる

C#には XmlSerializer なるクラスが存在してて、このクラスは Stream に、オブジェクトシリアライズして書き込む。または、デシリアライズするという機能を持っている。
で、属性割り当てとか、要素名指定とか色々できる。

以下サンプル。

// .NET 2.0(?)以降でつかえるっぽい
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace XmlSerializerTest
{
    class Program
    {
        static void Main(string[] args)
        {
            SerializeTarget target = new SerializeTarget();
            target.Attribute1 = "sampleAttribute";
            target.innnerTarget = new InnerTarget();
            target.innnerTarget.InnerText = "InnnerElement string";
            target.MyName = "white-azalea";

            XmlSerializer serializer = new XmlSerializer(typeof(SerializeTarget));
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            System.IO.FileStream fs = new System.IO.FileStream("sample.xml",
                System.IO.FileMode.Create);
            serializer.Serialize(fs, target, namespaces);
        }
    }

    [System.Xml.Serialization.XmlRoot("SimpleSirialized")]
    public class SerializeTarget
    {
        [System.Xml.Serialization.XmlAttribute(AttributeName="test")]
        public string Attribute1;
        [System.Xml.Serialization.XmlAttribute(AttributeName = "sample")]
        public string Attribute2;

        public string MyName;

        [System.Xml.Serialization.XmlElement("InnerTarget")]
        public InnerTarget innnerTarget;
    }

    public class InnerTarget
    {
        public string InnerText;
    }
}