HOW TO:利用 LINQ to XML 使用字典
將各種資料結構轉換為 XML,以及將 XML 轉回其他資料結構通常很方便。 這個主題藉由來回轉換 Dictionary<TKey, TValue> 和 XML 來顯示這個一般方法的特定實作。
範例
這個範例的 C# 版本會使用查詢評估新 XElement 物件之功能結構的形式,並將產生的集合當做 XElement 根物件之建構函式的引數傳遞。
這個犯例的 Visual Basic 版本會在內嵌運算式中使用 XML 常值與查詢。 此查詢會評估新的 XElement 物件,然後變成 Root XElement 物件的新內容。
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 建立字典。
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