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>
2
  • <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> Commented Apr 4, 2012 at 11:19
  • Possible duplicate: stackoverflow.com/questions/670563/linq-to-read-xml Commented Apr 4, 2012 at 11:25

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

You know there is a XDocument.Parse(string xml) method saves you having to create a StringReader().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.