i have this problem to find a particular xml node l have post this problem on stackoverflow and some nice fellows suggested xpath.
I am an xml newbie . please I need an c# code to find the parent , parent, parent as (great grand parent) then the first child ,lastchild , lastchild . the code have to iterate up the tree and down again. Be looking at a lot of xpath tutorials online.
I discovered that the path tend to be specific to a particular node already existing . The program that I need will not get no particular named node because at each pass a new node will be add to the xml tree. The long and short of it all is that I need find the node base on it’s position away from the current node
i meant finding the parent parent parent of a currentnode (great grand parentnode )then find the first child then find the lastchild lastchild
keepkind of currentnode.parentnode.parentnode.parentnode.firstchild.lastchild.lastchild;
using xpath C#
Let’s say that you have an XmlNode instance called
nodeto 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: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:
Let’s examine this with a more concrete example. Assume we have the following Xml document:
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:
This is of course assuming that
nodeis not null, but a valid XmlNode instance.Breakdown of the XPath expression:
If you want to read some about how XPath axes work, there is some information on w3schools.com.