如何使用 LINQ to XML 利用字典

將各種資料結構轉換成 XML,然後從 XML 轉換成其他資料結構通常是件很方便的事。 本文示範如何將 Dictionary<TKey,TValue> 轉換成 XML,以及將 XML 轉換回 Dictionary<TKey,TValue>

範例:建立字典並將其內容轉換成 XML

第一個範例會建立 Dictionary<TKey,TValue>,然後將它轉換成 XML。

這個範例的 C# 版本會使用查詢評估新 XElement 物件之功能結構的形式,並將產生的集合當做根 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

另請參閱