0

I have this xml format.i want to form dictionary using c#

<?xml version="1.0" encoding="utf-8"?>
<root>
  <key value="22.wav">
    <Index>1</Index>
  </key>
  <key value="22.wav">
    <Index>0</Index>
  </key>
  <key value="22.wav">
    <Index>7</Index>
  </key>
  <key value="22.wav">
    <Index>13</Index>
  </key>
</root>

How do i form?.Please Help me.Here Key is ex:value=22.wav and value=1 when i try to form dictionary It shows error same key with value already added

leppie
  • 115,091
  • 17
  • 196
  • 297
munisamy
  • 17
  • 2
  • 7

4 Answers4

1

You can create a Dictionary using Linq and XLinq:

using System.Xml.Linq;

string xml = @"<?xml version='1.0' encoding='utf-8'?>
<root>
  <key value='22.wav'>
    <Index>1</Index>
  </key>
  <key value='22.wav'>
    <Index>0</Index>
  </key>
  <key value='22.wav'>
    <Index>7</Index>
  </key>
  <key value='22.wav'>
    <Index>13</Index>
  </key>
</root>";

// Convert the string to XLinq
var xe = XElement.Parse(xml);

// Create a dictionary with Linq extension
// Use int ("Index") as the key
// Use string (key[@value]) as the value
var dict = xe.Descendants("Index")
             .ToDictionary(k => int.Parse(k.Value),
                           v => v.Parent.Attribute("value").Value);

// Results --
// Key    Value
// ------ ----------
// 1      22.wav
// 0      22.wav
// 7      22.wav
// 13     22.wav
Ryan
  • 7,835
  • 2
  • 29
  • 36
0

According to your query below is answer but it will throw error as we must have unique Key in dictionary.

  XDocument po = XDocument.Load(@"XMLFile1.xml");
            var data = po.Descendants("key")
       .ToDictionary(
           el => (string)el.Element("value"),
           el => (int)el.Attribute("Index"));

and if u take index as key and value as value then go for below code

XDocument po = XDocument.Load(@"XMLFile1.xml");
                var data = po.Descendants("key")
           .ToDictionary(
               el => (int)el.Element("Index"),
               el => (string)el.Attribute("value"));

but for your query u can use

var disc = Dictionary<string, IList<int>>();
Neel
  • 11,625
  • 3
  • 43
  • 61
0

Do this:

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();

each key will have a list of values. This might not be the best solution though, but it will fit your requirement.

alsafoo
  • 778
  • 4
  • 18
0

You can try this way to generate Dictionary<int,List<string>> from that XML :

var doc = XDocument.Load("path_to_xml_file.xml");
var result = doc.Root.Elements("key")
                   .GroupBy(k => (string)k.Attribute("value"))
                   .ToDictionary(o => int.Parse(o.Key), 
                                 p => p.Select(q => (string)q.Element("Index")).ToList());
har07
  • 88,338
  • 12
  • 84
  • 137