更新:November 2007
通常需要将各种数据结构转换为 XML 和将 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 创建一个字典。
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