Search code examples
xmlxpathxpath-2.0

Select nearest ancestor called "BATCH" in XPATH


I'm trying to select the first ancestor called "BATCH" going up in the XML Tree.

I've tried: ancestor::BATCH and ancestor::BATCH[1] but it's not working.

[XPATH 2.0]


Solution

  • What do you mean by first ancestor?

    If you have an XML:

    <!-- second ancestor -->
    <BATCH>
        <a>
           <!-- first ancestor -->
           <BATCH>
               <b></b>
           </BATCH>
        </a>
    </BATCH>
    

    Assuming your context node is <b> you would use ancestor::BATCH[1] to select what I described as first ancestor

    If however by first ancestor you mean the outermost ancestor, which I defined here as second ancestor you'd have to use ancestor::BATCH[not(ancestor::BATCH)] to select the ancestor BATCH that doesn't have an ancestor BATCH.


    If you have a namespace problem like @keshlam mentioned in his comment you can use

    ancestor::*[local-name()='BATCH'][1]
    

    To select it ignoring its namespace.