Anu
Anu

Reputation: 753

how to parse xml like this using linq to a object

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>

Upvotes: 1

Views: 224

Answers (2)

Taher
Taher

Reputation: 752

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

Upvotes: 1

DaveShaw
DaveShaw

Reputation: 52788

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

Upvotes: 4

Related Questions