3

I am fairly new to programming. I am trying to add an XML file in order to store some mappings. I want to ready these key value pairs in a dictionary. Following is the format of the XML I am thinking:

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

Can you please tell me if the format is correct? If it is, how would I read it into my C# dictionary?

K S
  • 301
  • 1
  • 4
  • 16

2 Answers2

7

You can use 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"));
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

One way of doing it:

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);
}
Learner
  • 3,904
  • 6
  • 29
  • 44