convert xml to sorted dictionary

10,771

Solution 1

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);
}

Solution 2

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();
    }

Solution 3

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);
}

Solution 4

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 
               };
Share:
10,771
torylor
Author by

torylor

Updated on June 23, 2022

Comments

  • torylor
    torylor over 1 year

    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?