アトリビュートを指定してXMLのシリアライズに対応したクラスを作成する。(XmlRootAttribute, XmlAttributeAttribute, XmlElementAttribute)

XMLシリアライズ可能なクラスを定義する場合は、クラスとメンバにそれぞれXMLのタグを示すアトリビュートを設定します。

以下の3つのアトリビュートが基本となります。

■ [System.Xml.Serialization.XmlRootAttribute("Company")]
XMLのルートノードに対応したクラスに指定します。引数で指定した文字列がXMLのタグ名となります。

■ [System.Xml.Serialization.XmlAttributeAttribute("Name")]
XMLのノード・要素に対応したメンバ・プロパティに指定します。引数で指定した文字列がXMLのタグ名となります。

■ [System.Xml.Serialization.XmlElementAttribute("Member")]
XMLの属性に対応したメンバ・プロパティに指定します。引数で指定した文字列がXMLの属性名となります。

参考:以下のXMLを出力する場合。



tekk
System Engineer


tekk sister
teacher



[System.Xml.Serialization.XmlRootAttribute("Company")]
public class Company
{

[System.Xml.Serialization.XmlAttributeAttribute("Name")]
public String Name = String.Empty;

[System.Xml.Serialization.XmlElementAttribute("Member")]
public List Members = null;

public class Member
{

[System.Xml.Serialization.XmlElementAttribute("Name")]
public String Name = String.Empty;

[System.Xml.Serialization.XmlElementAttribute("Job")]
public String Job = String.Empty;
}

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace XMLAttributeTest
{
class Program
{
static void Main(string[] args)
{

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

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(String.Empty, String.Empty);

Company item = null;

StreamReader sr = new StreamReader("Company.xml", Encoding.UTF8);
item = (Company)serializer.Deserialize(sr);
sr.Close();

StreamWriter sw = new StreamWriter("Company-Out.xml", false, Encoding.UTF8);
serializer.Serialize(sw, item, ns);
sw.Close();

Console.WriteLine("Hello World");
Console.Read();
}
}

[System.Xml.Serialization.XmlRootAttribute("Company")]
public class Company
{

[System.Xml.Serialization.XmlAttributeAttribute("Name")]
public String Name = String.Empty;

[System.Xml.Serialization.XmlElementAttribute("Member")]
public List Members = null;

public class Member
{

[System.Xml.Serialization.XmlElementAttribute("Name")]
public String Name = String.Empty;

[System.Xml.Serialization.XmlElementAttribute("Job")]
public String Job = String.Empty;
}

}

}