Apr 23, 2010

LINQ to XML メモ







  1. <version="1.0" encoding="utf-8"?>
  2. <game_consoles>
  3.   <ip_address_map>
  4.      <name="Xbox 360">192.168.11.2>
  5.      <name="PlayStation 3">192.168.11.3>
  6.      <name="Wii">192.168.11.4>
  7.      <name="3DO Real">192.168.11.5>
  8.      <name="DreamCast">192.168.11.6>
  9.   </ip_address_map>
  10. <game_consoles>
というXMLファイル・config.xml があるとき、「targetタグ」から「nameに3を含む」項目に次のようにしてアクセスできる:
  1. using System;
  2. using System.Linq;
  3. using System.Xml.Linq;
  4. // ...
  5.    XDocument config_xml = XDocument.Load(@".\config.xml");


  6.    var query = from c in config_xml.Descendants("target")
  7.                 where c.Attribute("name").Value.Contains("3")
  8.                 select c.Attribute("name").Value + " " + c.Value;
  9.     foreach (var q in query)
  10.     {
  11.         Console.WriteLine("{0}", q);
  12.     }


from/where/selectのあたりが LINQ (Language INtegrated Query) to XML と呼ばる仕組みを使っている部分。C# 3.0 (.NET Framework 3.5 以降) で利用可能。

ハッシュテーブルなど、別なデータ構造に入れる場合の例はこんな感じでいける:

 
  1. var platform_map = new Dictionary<string, string>();
  2. XDocument config_xml = XDocument.Load(@".\config.xml");
  3. var query = from c in config_xml.Descendants("target")
  4.                  where c.Attribute("name").Value.Contains("3")
  5.                  select new KeyValuePair<string, string>(c.Attribute("name").Value, c.Value);
  6.      foreach (var q in query)
  7.      {
  8.          platform_map[q.Key] = q.Value;
  9.      }
最初に登場した config.xml は、System.Xml.Linq 以下の XDocument などを使い次のようにして作成されたもの:





  1.     XDocument doc = new XDocument(
  2.         new XElement("game_consoles",
  3.            new XElement("ip_address_map",
  4.                 new XElement("target", new XAttribute("name", "Xbox 360"), "192.168.11.2"),
  5.                 new XElement("target", new XAttribute("name", "PlayStation 3"), "192.168.11.3"),
  6.                 new XElement("target", new XAttribute("name", "Wii"), "192.168.11.4"),
  7.                 new XElement("target", new XAttribute("name", "3DO Real"), "192.168.11.5"),
  8.                 new XElement("target", new XAttribute("name", "DreamCast"), "192.168.11.6")
  9.                 )
  10.             )
  11.         );
  12.     doc.Save(@".\config.xml");
XmlReader/XmlWriterを利用したコードに比べると格段に楽ですね。

No comments:

Post a Comment