parsing multiple elements from a node without knowing their names

This is certainly a very simple question, but I've already searched through 2 pages of Google results and still haven't found an answer.

So basically, I have an XML like this:

<section name="section1">
     <set name="set1">value1</set>
     <set name="set2">value2</set>
     <set name="set3">value3</set>
<section>

There are multiple sections of this structure.

What I want to do is parse this into a dictionary without knowing the names of those "sets" exactly. So, after parsing this should look like this:

section1[set1]  <--- should contain "value1"

The same for set2 and so on.

How can I achieve this using LINQ to XML?

Answers


var xdoc = XDocument.Load(path_to_xml);
var section1 = xdoc.Descendants("set") // or xdoc.Root.Elements()
                   .ToDictionary(s => (string)s.Attribute("name"),
                                 s => (string)s);

var set2 = section1["set2"]; // "value2"

here how you can find an element with a specific section

TextReader txtReader  = new StringReader(xml);
XDocument xDoc = XDocument.Load(txtReader);
var section1 = xDoc.Descendants("section").Where(elt=>elt.Attribute("name").ToString()=="section1").Descendants("set") 
       .ToDictionary(s => (string)s.Attribute("name"),
                     s => (string)s);

Need Your Help

GET and handle data from DB with node.js express

javascript jquery json node.js express

I'm creating a jQuery mobile app and I've a linux server with node.js and express. I think the authentification works fine and the database connection with another db-server, too.

adding a list view Item from another activity

android android-listview listactivity

I am a beginner in android development, I am trying to add an list item value from a different activity, i wrote a code where I am able to add an list item from within the activity, but not from ou...