WPFでXML出力をする必要があったので。
classをシリアライズでXML化
1.適当なクラスを作成
public class Person { public string name { get; set; } public int age { get; set; } }
public class Office { public string name; public ObservableCollection<Person> persons; }
適当に初期化する
private Office office; private void init() { office = new Office(); office.name = "オフィス"; office.persons = new ObservableCollection<Person>(); office.persons.Add(new Person { name = "001", age = 11 }); office.persons.Add(new Person { name = "002", age = 22 }); office.persons.Add(new Person { name = "003", age = 33 }); }
※ ObservableCollectionを使っているのはXAML用に
2.XML出力
XmlSerializer serializer = new XmlSerializer(office.GetType()); using (FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\" + "office.xml", FileMode.Create)) serializer.Serialize(fs, office);
出力内容
<?xml version="1.0"?> <Office xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <name>オフィス</name> <persons> <Person> <name>001</name> <age>11</age> </Person> <Person> <name>002</name> <age>22</age> </Person> <Person> <name>003</name> <age>33</age> </Person> </persons> </Office>
3.XML読込
XmlSerializer serializer = new XmlSerializer(office.GetType()); using (FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\" + "office.xml", FileMode.Open)) office = (Office)serializer.Deserialize(fs);
これで取り込める
4.出力するタグ名を変更など
public class Person { public string name { get; set; } [System.Xml.Serialization.XmlIgnoreAttribute] public int age { get; set; } }
・System.Xml.Serialization.XmlIgnoreAttribute XML出力しない
[System.Xml.Serialization.XmlRoot("root")] public class Office { public string name; [System.Xml.Serialization.XmlElement("members")] public ObservableCollection<Person> persons; }
・System.Xml.Serialization.XmlRoot ルート名変更
・System.Xml.Serialization.XmlElement タグ名変更
上記を適用して出力すると、
<?xml version="1.0"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <name>オフィス</name> <members> <name>001</name> </members> <members> <name>002</name> </members> <members> <name>003</name> </members> </root>