/ / Gerar XML do dicionário - c #, xml, dicionário, linq-to-xml

Gerar XML do Dicionário - c #, xml, dicionário, linq-to-xml

Eu tenho um dicionário com par de valores-chave. Eu quero escrevê-lo para XML usando LINQ.

Eu sou capaz de criar o documento XML usando o LINQ, mas não sei como ler os valores do dicionário e escrever no XML.

A seguir está o exemplo com valores de código de barras para gerar XML, quero preparar o dicionário em vez de valores de código de barras

XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "true"),
new XElement("countrylist",
new XElement("country",
new XAttribute("id", "EMP001"),
new XAttribute("name", "EMP001")
),
new XElement("country",
new XAttribute("id", "EMP001"),
new XAttribute("name", "EMP001")
)
)
);

Respostas:

0 para resposta № 1

Supondo que você tenha um Country classe com um Id e um Name e os países são armazenados como valores em seu dicionário paises, com o id sendo a chave:

XDocument xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"));
var xCountryList = new XElement("countrylist");
foreach(var kvp in countries)
xCountryList.Add(new XElement("country",
new XAttribute("id", kvp.Key),
new XAttribute("name", kvp.Value.Name)));

5 para resposta № 2

Se o atributo id for armazenado como chave do dicionário e o nome como valor, você poderá usar o seguinte

XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "true"),
new XElement("countrylist",
dict.Select(d => new XElement("country",
new XAttribute("id", d.Key),
new XAttribute("name", d.Value))))
);

0 para resposta № 3

Aqui cara com o dicionário

        Dictionary<int, string> fooDictionary = new Dictionary<int, string>();
fooDictionary.Add(1, "foo");
fooDictionary.Add(2, "bar");

XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "true"),
new XElement("countrylist")
);

var countryList = doc.Descendants("countrylist").Single(); // Get Country List Element

foreach (var bar in fooDictionary) {
// Add values per item
countryList.Add(new XElement("country",
new XAttribute("id", bar.Key),
new XAttribute("name", bar.Value)));
}