My XML file consists of a structure that resembles something like the following:
<root>
<Manager name="1">
<Manager name="2">
<Employee name="3">
</Manager>
<Manager name="abe">
</Manager>
<Employee name="4">
<Employee name="5">
</Manager>
</root>
The XML feeds a treeview, and depending on where in the treeview a user clicks, I either want to retrieve the Employee clicked on (which is easy, as I can use treeview.SelectedNode), or otherwise in case the click was on the root node, or a manager node, the first employee under the manager.
I.e.
- Clicking on
rootshould show details ofEmployee 4(the first Employee record is directly underManager 1directly underroot). - Clicking on
Manager 1also should showEmployee 4. - Clicking
Manager 2should showEmployee 3. - Clicking
Manager Abeyields no results. Employee 5only shows when there is a click directly on that employee.
It could also be possible that Manager 1 does not have any direct employees under him. In that case, clicking on root should yield the first Employee under the first manager with employees. So if we assume Employee 4 and Employee 5 were not under Manager 1, clicking on root would yield Employee 3.
I tried using some different variants of Element, Elements, Descendant and Descendants, and am a bit stuck.
I suppose that I could write scenarios for every individual combination (I.e. rootClicked, managerClicked and employeeClicked), which is what I did originally, but I’m looking for something that will hopefully be easier to maintain, code-wise.
I had good hopes that using root.Element(“Employee”) would help, but that threw a Could not find an implementation of the query pattern for source type 'System.Xml.Linq.XEelement'. 'select' not found error.
Would anyone be able to supply me with that little nudge I need to solve my issue?
Using XPath:
Update:
Answer to the edited question:
Use:
This selects either:
a. The clicked node, if it is an `Employee’
Or:
b. The first child
Employeeof the first desendant-or-self of the clicked node, that is a manager and has a childEmployeeAnd, if ClickedNode is an
XElement(orXNode), then do:Finally, here is a complete C# code:
A static class named
TestLinqXpath:and extensive test:
When this test is run, the wanted, correct results are produced: