Edited at

XMLファイルの操作

下記の3つの方法がある。


Linq to XML


XMLに保存

var option = new XElement("option");

option.SetElementValue("enabled", true);
var root = new XElement("settings", option);
root.Save("settings.xml");


XMLの読込

var xdoc = XDocument.Load("item.xml");

var xelements = xdoc.Root.Elements();
foreach(var item in xelements)
{
XElement xname = item.Element("name");
System.Diagnostics.Debug.WriteLine(xname.Value);
}


名前空間がついている場合

xdoc.Root.Name.Namespaceで名前空間を取得し、要素取得時に指定する。

http://neareal.net/index.php?Programming%2F.NetFramework%2FLINQ%2FLinqAndXmlNamespace


コレクションをXMLに保存

var items = new List<Item>()

{
new Item()
{
Id = 1,
Name = "テレビ"
},
new Item()
{
Id = 2,
Name = "ラジオ"
}
};

var elements = items.Select(x =>
new XElement("item",
new XElement("id", x.Id),
new XElement("name", x.Name)));
var root = new XElement("items", elements);
var xdoc = new XDocument(root);

xdoc.Save("item.xml");


DataContractSerializer


XMLに保存

var item = new Item()

{
Id = 3,
Name = "PC"
};
var settings = new XmlWriterSettings()
{
Encoding = new UTF8Encoding(false),
Indent = true,
IndentChars = " "
};

using (var writer = XmlWriter.Create("item.xml", settings))
{
var serializer = new DataContractSerializer(item.GetType());
serializer.WriteObject(writer, item);
}


XMLの読込

using (var reader = XmlReader.Create("item.xml"))

{
var serializer = new DataContractSerializer(typeof(Item));
var item = serializer.ReadObject(reader) as Item;
System.Diagnostics.Debug.WriteLine(item.Name);
}


XmlSerializer


XMLに保存

var item = new Item()

{
Id = 4,
Name = "スマホ"
};

using (var writer = XmlWriter.Create("item.xml"))
{
var serializer = new XmlSerializer(item.GetType());
serializer.Serialize(writer, item);
}


XMLの読込

using (var reader = XmlReader.Create("item.xml"))

{
var serializer = new XmlSerializer(typeof(Item));
var item = serializer.Deserialize(reader) as Item;
System.Diagnostics.Debug.WriteLine(item.Name);
}