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

时间:2013-08-15 21:10:54

标签: c# xml

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

<?xml version="1.0" encoding="utf-8" ?>
<Map>
  <add keyword="keyword1" replaceWith="replaceMe1"/>
  <add keyword="keyword2" replaceWith="replaceMe2"/>  
</Map>

请告诉我格式是否正确?如果是,我怎么把它读到我的C#字典?

2 个答案:

答案 0 :(得分:7)

您可以使用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"));

答案 1 :(得分:0)

一种方法:

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);
}
相关问题