3

i have an xml file similar to this:

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <resource key="123">foo</resource>
    <resource key="456">bar</resource>
    <resource key="789">bar</resource>

</data>

i want to put this into a Dictionary (sorted) as key value pairs. i.e: 123:foo, 456:bar...etc

the keys are unknown.

how can i do this?

raklos
  • 28,027
  • 60
  • 183
  • 301

5 Answers5

8

This looks like a job for Linq to Xml

    static void Main(string[] args)
    {            
        XDocument yourDoc = XDocument.Load("the.xml");
        var q = from c in yourDoc.Descendants("resource")
                orderby (int) c.Attribute("key")
                select c.Attribute("key").Value + ":" + c.Value;

        foreach (string s in q)
            Console.WriteLine(s);                            
        Console.ReadLine();
    }
Johnno Nolan
  • 29,228
  • 19
  • 111
  • 160
6

Try this,

string s = "<data><resource key=\"123\">foo</resource><resource key=\"456\">bar</resource><resource key=\"789\">bar</resource></data>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(s);
XmlNodeList resources = xml.SelectNodes("data/resource");
SortedDictionary<string,string> dictionary = new SortedDictionary<string,string>();
foreach (XmlNode node in resources){
   dictionary.Add(node.Attributes["key"].Value, node.InnerText);
}
Liam
  • 27,717
  • 28
  • 128
  • 190
gk.
  • 1,252
  • 3
  • 14
  • 23
6

This is actually easier without using Linq and just using an XmlDocument:

SortedDictionary<string, string> myDict = new SortedDictionary<string, string>();
foreach (XmlElement e in myXmlDocument.SelectNodes("/data/resource"))
{
   myDict.Add(e.GetAttribute("key"), e.Value);
}
Community
  • 1
  • 1
Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
2

Use LINQ:

Load the document XDocument.Load or XDocument.Parse:

var xml = XDocument.Load(...);

Iterate through the ordered sequence:

var sequence = from e in xml.Root.Elements() 
               let key = (string)e.Attribute("key")
               order by key
               select new { 
                 Key = key, 
                 Value = (string)e 
               };
Michael Damatov
  • 15,253
  • 10
  • 46
  • 71
0

I would do this with XSLT transformation. Do you need to do the job with C#? If not you can simply make a XSLT document which parses through all resource tags and outputs key:value sorted out for you. Very easy accomplished. Is this a solution you want?

Chris Dale
  • 2,222
  • 2
  • 26
  • 39