LINQ to XML を使用してディクショナリを操作する方法

多くの場合、さまざまな種類のデータ構造を XML に変換した後、XML から他のデータ構造に変換すると便利です。 この記事は、Dictionary<TKey,TValue> から XML への変換と、その逆について示しています。

例: ディクショナリを作成し、その内容を XML に変換する

この最初の例では、Dictionary<TKey,TValue> を作成し、それを XML に変換します。

この C# バージョンの例では、クエリによって新しい XElement オブジェクトが射影され、関数型構築の形式を使用します。結果のコレクションは、引数として Root XElement オブジェクトのコンストラクターに渡されます。

Visual Basic バージョンでは、XML リテラルと組み込み式内のクエリが使用されます。 このクエリによって、新しい XElement オブジェクトが射影されます。その後、これは RootXElement オブジェクトの新しいコンテンツになります。

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Child1", "Value1");
dict.Add("Child2", "Value2");
dict.Add("Child3", "Value3");
dict.Add("Child4", "Value4");
XElement root = new XElement("Root",
    from keyValue in dict
    select new XElement(keyValue.Key, keyValue.Value)
);
Console.WriteLine(root);
Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)()
dict.Add("Child1", "Value1")
dict.Add("Child2", "Value2")
dict.Add("Child3", "Value3")
dict.Add("Child4", "Value4")
Dim root As XElement = _
    <Root>
        <%= From keyValue In dict _
            Select New XElement(keyValue.Key, keyValue.Value) %>
    </Root>
Console.WriteLine(root)

この例を実行すると、次の出力が生成されます。

<Root>
  <Child1>Value1</Child1>
  <Child2>Value2</Child2>
  <Child3>Value3</Child3>
  <Child4>Value4</Child4>
</Root>

例: ディクショナリを作成し、XML データから読み込む

次の例では、ディクショナリを作成して XML データから読み込みます。

XElement root = new XElement("Root",
    new XElement("Child1", "Value1"),
    new XElement("Child2", "Value2"),
    new XElement("Child3", "Value3"),
    new XElement("Child4", "Value4")
);

Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (XElement el in root.Elements())
    dict.Add(el.Name.LocalName, el.Value);
foreach (string str in dict.Keys)
    Console.WriteLine("{0}:{1}", str, dict[str]);
Dim root As XElement = _
        <Root>
            <Child1>Value1</Child1>
            <Child2>Value2</Child2>
            <Child3>Value3</Child3>
            <Child4>Value4</Child4>
        </Root>

Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)
For Each el As XElement In root.Elements
    dict.Add(el.Name.LocalName, el.Value)
Next
For Each str As String In dict.Keys
    Console.WriteLine("{0}:{1}", str, dict(str))
Next

この例を実行すると、次の出力が生成されます。

Child1:Value1
Child2:Value2
Child3:Value3
Child4:Value4

関連項目