通过 LINQ to XML 使用字典

来源:互联网 发布:淘宝网商贷款 编辑:程序博客网 时间:2024/06/05 22:58
 
语言集成查询 (LINQ)
如何:通过 LINQ to XML 使用字典

通常需要将各种数据结构转换为 XML 和将 XML 转换回其他数据结构。 本主题通过Dictionary<(Of <(TKey, TValue>)>) 和 XML 的相互转换演示这一常规方法的具体实现。

示例

本示例的 C# 版本使用函数构造形式:查询投影新 XElement 对象,生成的集合作为参数传递给根XElement 对象的构造函数。

本示例的 Visual Basic 版本在嵌入式表达式中使用 XML 文本和查询。 查询投影新 XElement 对象,该对象然后成为Root XElement 对象的新内容。

  1. Dictionary<string, string> dict = new Dictionary<string, string>();
  2. dict.Add("Child1", "Value1");
  3. dict.Add("Child2", "Value2");
  4. dict.Add("Child3", "Value3");
  5. dict.Add("Child4", "Value4");
  6. XElement root = new XElement("Root",
  7. from keyValue in dict
  8. select new XElement(keyValue.Key, keyValue.Value)
  9. );
  10. 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 创建一个字典。

  1. XElement root = new XElement("Root",
  2. new XElement("Child1", "Value1"),
  3. new XElement("Child2", "Value2"),
  4. new XElement("Child3", "Value3"),
  5. new XElement("Child4", "Value4")
  6. );
  7. Dictionary<string, string> dict = new Dictionary<string, string>();
  8. foreach (XElement el in root.Elements())
  9. dict.Add(el.Name.LocalName, el.Value);
  10. foreach (string str in dict.Keys)
  11. 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)NextFor Each str As String In dict.Keys    Console.WriteLine("{0}:{1}", str, dict(str))Next

这段代码产生以下输出:

Child1:Value1Child2:Value2Child3:Value3Child4:Value4
请参见

概念

投影和转换 (LINQ to XML)
原创粉丝点击