- <version="1.0" encoding="utf-8"?>
<game_consoles> - <ip_address_map>
<name="Xbox 360">192.168.11.2> <name="PlayStation 3">192.168.11.3> <name="Wii">192.168.11.4> <name="3DO Real">192.168.11.5> <name="DreamCast">192.168.11.6> - </ip_address_map>
- <game_consoles>
- using System;
- using System.Linq;
- using System.Xml.Linq;
- // ...
- XDocument config_xml = XDocument.Load(@".\config.xml");
-
var query = from c in config_xml.Descendants("target") - where c.Attribute("name").Value.Contains("3")
- select c.Attribute("name").Value + " " + c.Value;
- foreach (var q in query)
- {
- Console.WriteLine("{0}", q);
- }
from/where/selectのあたりが LINQ (Language INtegrated Query) to XML と呼ばる仕組みを使っている部分。C# 3.0 (.NET Framework 3.5 以降) で利用可能。
ハッシュテーブルなど、別なデータ構造に入れる場合の例はこんな感じでいける:
- var platform_map = new Dictionary<string, string>();
- XDocument config_xml = XDocument.Load(@".\config.xml");
- var query = from c in config_xml.Descendants("target")
- where c.Attribute("name").Value.Contains("3")
- select new KeyValuePair<string, string>(c.Attribute("name").Value, c.Value);
- foreach (var q in query)
- {
- platform_map[q.Key] = q.Value;
- }
- XDocument doc = new XDocument(
- new XElement("game_consoles",
- new XElement("ip_address_map",
- new XElement("target", new XAttribute("name", "Xbox 360"), "192.168.11.2"),
- new XElement("target", new XAttribute("name", "PlayStation 3"), "192.168.11.3"),
- new XElement("target", new XAttribute("name", "Wii"), "192.168.11.4"),
- new XElement("target", new XAttribute("name", "3DO Real"), "192.168.11.5"),
- new XElement("target", new XAttribute("name", "DreamCast"), "192.168.11.6")
- )
- )
- );
- doc.Save(@".\config.xml");
No comments:
Post a Comment