Im having some trouble with a linq query into an xml tree. Here is what the tree structure looks like:
<Student>
<ID> Hello </Hello>
<Classroom>
<Name> 1B </Name>
<Year> 1 </Year>
</Classroom>
<Classroom>
<Name> 2B </Name>
<Year> 2 </Year>
</Classroom>
<Classroom>
<Name> 3B </Name>
<Year> 3 </Year>
</Classroom>
</Student>
Now this is one student entry among 5. say i am passed an XElement Student node from another method and i want to search for a classroom given the XElement Student node and the classroom name. So i have to write a method like this:
getClassRoomNode(XElement StudentNode, string classroomName)
This is what ive tried. Please let me know where i am wrong
XElement classroom = StudentNode.Descendants("Classroom")
.Where(arg => arg.Element("Name").Value == classroomName)
.Select(arg => arg.Parent)
.First();
This returns the StudentNode back again instead of a classroom node. Can anyone please help me out with this?
You don’t need to select parent, just the get the
First(), or even betterSingle()class room.I suggest it is better to error rather than ignore subsequent matches. If the intention is to match the first of many matches then obviously,