如何添加XML文件并将键值对读入字典?

我对编程很新。 我试图添加一个XML文件,以存储一些映射。 我想在字典中准备好这些键值对。 以下是我想的XML格式:

     

你能告诉我格式是否正确吗? 如果是,我怎么读到我的C#字典?

您可以使用LINQ to XML:

 var xdoc = XDocument.Load(path_to_xml); var map = xdoc.Root.Elements() .ToDictionary(a => (string)a.Attribute("keyword"), a => (string)a.Attribute("replaceWith")); 

一种方法:

 XDocument doc = XDocument.Load("path_to_your_xml_file.xml"); var definitions = doc.Root.Elements() .Select(x => new { Keyword = x.Attribute("keyword").Value, ReplaceWith = x.Attribute("replaceWith").Value }); foreach (var def in definitions) { Console.WriteLine("Keyword = {0}, ReplaceWith = {1}", def.Keyword, def.ReplaceWith); }