Cómo trabajar con diccionarios usando LINQ to XML

A menudo resulta cómodo convertir variedades de estructuras de datos a XML y de XML a otras estructuras de datos.Este tema muestra una implementación específica de este enfoque general convirtiendo un Dictionary<TKey, TValue> a XML y de XML.

Ejemplo

La versión de C# de este ejemplo usa una forma de construcción funcional en la que una consulta proyecta nuevos objetos XElement y la recopilación resultante se pasa como argumento al constructor del objeto raíz XElement.

La versión de Visual Basic de este ejemplo usa literales de XML y una consulta en una expresión incrustada.La consulta proyecta nuevos objetos XElement, que se convierten en el contenido nuevo para el objeto 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)

Este código genera el siguiente resultado:

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

El siguiente código genera un diccionario de 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

Este código genera el siguiente resultado:

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

Vea también

Conceptos

Proyecciones y transformaciones (LINQ to XML)