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