1

I have following xml as a response to a service not i want to parse this to a key value properties object. but it is not working. response - I want object with name as Key prop and value as value prop of object.

<lst name="industry">
  <int name="Accounting">3</int> 
  <int name="Engineering">0</int> 
  <int name="Human Resources and Adminstration">0</int> 
  <int name="Software/IT">0</int>
sll
  • 61,540
  • 22
  • 104
  • 156
Anu
  • 753
  • 2
  • 13
  • 22

2 Answers2

4

You can do it using Linq-Xml to select the int elements and Linq-Objects' ToDictionary() extension method to select the attribute as the key and the element's value as the value in your dictionary:

var xml = @"<lst name=""industry"">
  <int name=""Accounting"">3</int>
  <int name=""Engineering"">0</int>
  <int name=""Human Resources and Adminstration"">0</int>
  <int name=""Software/IT"">0</int>
  </lst>";

var dict =
    XDocument.Parse(xml)
    .Root
    .Elements("int")
    .ToDictionary(xe => xe.Attribute("name").Value, xe => int.Parse(xe.Value));
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
1

Your XML is not properly formatted. I believe this is how your XML looks?

<lst name="industry">
 <int name="Accounting">3</int> 
 <int name="Engineering">0</int> 
 <int name="Human Resources and Adminstration">0</int> 
 <int name="Software/IT">0</int> 
</lst>

For that case, you can do..

XDocument result = XDocument.Load(new StringReader("<lst name=\"industry\">" + 
                                                           "<int name=\"Accounting\">3</int>" + 
                                                           "<int name=\"Engineering\">0</int>" +
                                                           "<int name=\"Human Resources and Adminstration\">0</int>" +
                                                           "<int name=\"Software/IT\">0</int>" + 
                                                           "</lst>"));            


        var tmpTable = (from i in result.Descendants("int")
                        select new
                        {
                            Key = i.Attribute("name"),
                            Value = i.Value
                        }).ToDictionary(t => t.Key, t => t.Value);
Taher
  • 732
  • 1
  • 9
  • 26
  • 2
    You know there is a `XDocument.Parse(string xml)` method saves you having to create a `StringReader()`. – DaveShaw Apr 04 '12 at 11:38