tags:

views:

395

answers:

3

My XML:

<root>
  <child>
     <childOfChild>
        <anotherLostChild>
           <currentSelectedNode>
              SOME TEXT
           </currentSelectedNode>
        </anotherLostChild>
     </childOfChild>
  </child>
</root>

I selected the node currentSelectedNode using:

xpath.SelectSingleNode("//currentSelectedNode")

But How can I back to select the first chilfOfChild parent node (considering that the context is currentSelectedNode?

xpath.SelectSingleNode("//currentSelectedNode")...???
+1  A: 

Your question is really confusingly written but it sounds like you'd want the ancestor axis, something like:

//currentSelectedNode/ancestor::chilfOfChild[1]

(pure xpath solution)

annakata
tactical downvote or is there an actual reason?
annakata
Not only there is a typo and the XPath expression doesn't select anything, but generally it is wrong.//currentSelectedNodeis not the same as xpath.SelectSingleNode("//currentSelectedNode")The former may select many nodes (depending on the XML file, while the latter (which the OP uses) selects just the first of them in document order.FAIL!
Dimitre Novatchev
@annakata: I believe you can find yourself an XPath expression that is really equivalent to what the OP is doing via DOM :)
Dimitre Novatchev
Grow the hell up Dimitre. The "typo" is because the OP has been edited since this answer and the //currentSelectedNode is because that's the root query the OP uses. Further the expression does select exactly what is required given the input doc and indeed is the accepted answer. It is not I who have failed.
annakata
@annakata: Why grow the hell? I am simply expecting that you will provide the corect XPath expression that does the same as the OP's used DOM method SelectSingleNode() with the argument value "//currentSelectedNode."I deeply believe you can construct this expression. Nobody would persuade me you would fail to do this.
Dimitre Novatchev
+1  A: 

xpath.SelectSingleNode("//currentSelectedNode/../..")

this will select the parent's parent.

T

Thomas
A: 

In Linq-To-XML you would need only to use the Ancestor method:

To get the immediate ancestor:

xElement.Ancestor();

To specify which ancestor:

xElement.Ancestor("NameOfTheAncestorNode");
Jader Dias