0

In my WPF project, i need to have a xml file similiar to app.config file. So I added a xml file (Picture.xml) in my project and whose content is shown below :

  <?xml version="1.0" encoding="utf-8" ?>
  <Map>
     <add filenumber="1" value="1.png"/>
     <add filenumber="2" value="2.png"/>
     <add filenumber="3" value="3.png"/>
     <add filenumber="4" value="4.png"/>
 </Map>

I have tried to get the value of a particular filenumber by doing as shown below.

 XDocument doc = XDocument.Load("Picture.xml");           
 var keys = doc.Descendants("add").Select(x => 
            x.Attribute("filenumber").Value);

But it is not getting the value for a particular filenumber. Is there any way to get the value of a particular key as like in the app.config. If we are using App.Config, then we can get the value of key by using the code

      ConfigurationManager.AppSetting["key"] 

something like this.

Is there any similar way to get the value like this from the Picture.xml file ?

If i supply 4 as the filenumber (key), then i should get "4.png" (value).

sherin
  • 5
  • 4
  • What is the value of `keys`? What do you expect it to be? – mason Oct 17 '19 at 16:42
  • Possible duplicate of [Query an XDocument for elements by name at any depth](https://stackoverflow.com/questions/566167/query-an-xdocument-for-elements-by-name-at-any-depth) – devlin carnate Oct 17 '19 at 16:47
  • @devlincarnate it is not the duplicate of what you have specified above. Read my problem first. It is not reading to any extend. It is just to get the value of a particular key. – sherin Oct 17 '19 at 16:55

1 Answers1

1

Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<int, string> dict = doc.Descendants("add")
                .GroupBy(x => (int)x.Attribute("filenumber"), y => (string)y.Attribute("value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }

}
jdweng
  • 33,250
  • 2
  • 15
  • 20