- 追加された行はこの色です。
- 削除された行はこの色です。
&tag(LINQtoXML);
*目次 [#ybc772be]
#contents
*参考情報 [#vb58063a]
-[[困ったときにそのまま使える LINQ to XML コードサンプル 18 パターン [1/2] - Web/DB プログラミング徹底解説:http://keicode.com/dotnet/linq-to-xml-101.php]]
-[[困ったときにそのまま使える LINQ to XML コードサンプル 18 パターン [2/2] - Web/DB プログラミング徹底解説:http://keicode.com/dotnet/linq-to-xml-101-2.php]]
-[[LINQ to XML 備忘録2 X* クラスの使用方法について - ComponentGeek Article:http://handcraft.blogsite.org/ComponentGeek/ShowArticle/72.aspx]]
*読み込み [#e9a01a49]
**サンプルXML [#ad6214ad]
-次の内容のファイルをpersons.xmlとして保存する。
#pre{{
<?xml version="1.0" encoding="utf-8" ?>
<PersonList>
<Persons id="soccer">
<Person>
<Name>中田英寿</Name>
<Age>34</Age>
</Person>
<Person>
<Name>中村俊輔</Name>
<Age>33</Age>
</Person>
</Persons>
<Persons id="baseball">
<Person>
<Name>ダルビッシュ</Name>
<Age>25</Age>
</Person>
<Person>
<Name>イチロー</Name>
<Age>36</Age>
</Person>
</Persons>
</PersonList>
}}
**ファイルから読み込む [#y4e70a9c]
-XDocument.Load(XMLファイル名)を使用する
var xdoc = XDocument.Load("../../persons.xml");
*要素の選択 [#ibca1b47]
**子孫の要素を選択する [#j9bff8df]
-Descendants(要素名)を使用すると階層深くにある要素も一気に選択できる。
#pre{{
var persons = xdoc.Descendants("Person");
foreach (var person in persons)
{
Debug.WriteLine("##### start #####");
Debug.WriteLine(person.ToString());
Debug.WriteLine("");
}
}}
-出力結果
#pre{{
##### start #####
<Person>
<Name>中田英寿</Name>
<Age>34</Age>
</Person>
##### start #####
<Person>
<Name>中村俊輔</Name>
<Age>33</Age>
</Person>
##### start #####
<Person>
<Name>ダルビッシュ</Name>
<Age>25</Age>
</Person>
##### start #####
<Person>
<Name>イチロー</Name>
<Age>36</Age>
</Person>
}}
**属性で選択する [#a9f2c176]
-Attribute("属性")を使って要素を選択することができる。サッカー選手のリストを取得する場合次のようになる。
#pre{{
var personsCollection = (
from p in xdoc.Descendants("Persons")
where p.Attribute("id").Value == "soccer"
select p);
foreach (var persons in personsCollection)
{
Debug.WriteLine(persons.ToString());
}
}}
-出力結果
#pre{{
##### start #####
<Persons id="soccer">
<Person>
<Name>中田英寿</Name>
<Age>34</Age>
</Person>
<Person>
<Name>中村俊輔</Name>
<Age>33</Age>
</Person>
</Persons>
}}