Let's say that you have an XmlNode instance called node
to start with. Then the following code will give you the last child of the last child of the first child of the great grand parent of that node:
XmlNode wantedNode = node.ParentNode.ParentNode.ParentNode.FirstChild.LastChild.LastChild;
Note that there are so many things that can go wrong with this code. If any of the referenced nodes happen to be null, you have a NullReferenceException coming. So you will want to make a null check at each level:
XmlNode wantedNode;
if (node.ParentNode != null && node.ParentNode.ParentNode != null /* and so on through the full path */)
{
wantedNode = node.ParentNode.ParentNode.ParentNode.FirstChild.LastChild.LastChild;
}
Let's examine this with a more concrete example. Assume we have the following Xml document:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<greatgrandparent>
<grandparent>
<parent id="1">
<child somevalue="3"></child>
</parent>
<parent id="2">
<child somevalue="4"></child>
<child somevalue="5"></child>
</parent>
</grandparent>
</greatgrandparent>
</root>
If I understand your question right, if we start from the node <child somevalue="3"></child>
we want to navigate to <child somevalue="5"></child>
. The code sample above will do that. However, as mentioned, it is prone to giving exceptions if not all expected nodes are present.
Even though you said that you want c# code rather than XPath, in this case I feel that XPath is the way to go. There are a number of ways to solve this. For instance, if the nodes have different tag names (as in my sample document), you can instead do like this:
XmlNode wantedNode = node.SelectSingleNode("ancestor::greatgrandparent/grandparent[position()=1]/parent[position()=last()]/child[position()=last()]");
if (wantedNode != null)
{
// the path was found
}
This is of course assuming that node
is not null, but a valid XmlNode instance.
Breakdown of the XPath expression:
- ancestor::greatgrandparent -> this will locate any node named "greatgrandparent" that is located anywhere upwards in the hierarchy (so any parent, grand parent and so on)
- /grandparent[position()=1] -> the first child node named "grandparent"
- /parent[position()=last()] -> the last child node named "parent"
- /child[position()=last()] -> the last child node named "child"
If you want to read some about how XPath axes work, there is some information on w3schools.com.