Como: Trabalhar com dicionários usando LINQ para XML
É conveniente converter variedades de estruturas de dados para XML, e XML de volta para outras estruturas de dados. Este tópico mostra uma implementação específica dessa abordagem geral convertendo Dictionary a XML e verso.
Exemplo
A versão de C# este exemplo usa um formulário de compilação funcional em que uma consulta projetos novos objetos de XElement , e a coleção resultante é passada como um argumento para o construtor do objeto de XElement raiz.
A versão de Visual Basic este exemplo usa literais XML e uma consulta em uma expressão inserida. A consulta projetos novos objetos de XElement , que se tornam o novo conteúdo para o objeto de 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)
Esse código gera a seguinte saída:
<Root>
<Child1>Value1</Child1>
<Child2>Value2</Child2>
<Child3>Value3</Child3>
<Child4>Value4</Child4>
</Root>
O código a seguir cria um dicionário 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
Esse código gera a seguinte saída:
Child1:Value1
Child2:Value2
Child3:Value3
Child4:Value4