XPath: How to select the first given parent node?

My XML:

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

      

I selected node currentSelectedNode using:

xpath.SelectSingleNode("//currentSelectedNode")

      

But how do I go back to select the first chilfOfChild parent node (given that the context is currentSelectedNode ?

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

      

+2


source to share


4 answers


Your question is really vaguely written, but it looks like you want an ancestor axis , something like:

//currentSelectedNode/ancestor::childOfChild[1]

      



(pure xpath solution)

+13


source


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

      



this will select the parent parent

+3


source


In Linq-To-XML, you will need to use the Ancestor method:

To get an immediate ancestor:

xElement.Ancestor();

      

To indicate which of the ancestors:

xElement.Ancestor("NameOfTheAncestorNode");

      

0


source


By using XElement xElem

, you can use xElem.Parent

to get the immediate parent.

https://msdn.microsoft.com/en-us/library/system.xml.linq.xobject.parent(v=vs.110).aspx

To select specific ancestor nodes, you can use

xElem.Ancestors("currentSelectedNode"); 

      

to get all ancestors with that specific node name.

https://msdn.microsoft.com/en-us/library/bb348268(v=vs.110).aspx

0


source







All Articles