LINQ: How to return all child elements?

rangedshock

New Member
For an application I am working on, I have to display data from an XML File. There's a few transformations being done, but eventually the end result will be displayed in a treeview. When a user then clicks on a node, I want to pop up the details in a listview.When no node has been selected, I basically use LINQ to grab the details of the first item I encounter.Here's a simplified version of my XML\[code\]<root> <parent label="parent1"> <child label="child1"> <element1>data</element1> <element2>data</element2> ... </child> <child label="child2"> <element1>data</element1> <element2>data</element2> ... </child> </parent></root>\[/code\]And here's the code used to grab it (After selecting the parent-node that the treeview has been set to by means of an XPAthSelectStatement):\[code\]protected void listsSource_Selecting(object sender, LinqDataSourceSelectEventArgs e){ XElement rootElement = XElement.Load(MapPath(TreeSource.DataFile)); rootElement = rootElement.XPathSelectElement("//parent[@label='parent1']"); XElement parentElement; parentElement = rootElement; var query = (from itemElement in parentElement.Descendants("child") select new { varElement1 = itemElement.Element("element1").Value, varElement2 = itemElement.Element("element2").Value, ... }).Take(1); e.result = Query;}\[/code\]This works a treat, and I can read out the \[code\]varElement1\[/code\] and \[code\]varElement2\[/code\] values from there. However, when I try and implement a similar mechanism for when the user actually did select a node, I seem to run into a wall.My approach was to use another \[code\]XPatchSelectStatement\[/code\] to get to the actual node:\[code\]parentElement = rootElement.XPathSelectElement("//child[@label='" + tvwChildren.SelectedNode.Text + "']");\[/code\]But I am kind of stumped on how to now get a proper LINQ query built up to read in all elements nested under the child node. I tried using \[code\]parentElement.Elements()\[/code\], but that was yielding an error. I also looked at using \[code\]Nodes()\[/code\], but with similar results. I suppose I could use a foreach loop to access the nodes, but then I'm not sure how to get the results into a LINQ query so I can return the same \[code\]e.Result = query\[/code\] back.I'm fairly new to LINQ, as you might have guessed, so any hints would be very much appreciated.
 
Back
Top