Search code examples
xmlxpathxpath-2.0

XPATH to select NEAREST preceding node


How can I select the nearest preceding node called BName that DOES NOT have a parent called "Test" in Xpath 2.0?

Expression I'm thinking of is something like:

preceding::BName[1](not[@parent::Test])

Solution

  • Try

    preceding::BName[not(parent::Test)][1]
    

    Explanation

    preceding::BName
    

    selects all preceding nodes with name BName in reverse document order.

    preceding::BName[not(parent::Test)]
    

    only keeps the nodes which don't have a parent with name Test, i.e. removes all nodes with a Test parent.

    preceding::BName[not(parent::Test)][1]
    

    selects the first node. Since the node set is in reverse document order, this is the node nearest to the context node.

    Example

    Given the document

    <Document>
        <Container>
            <BName id="1"/>
        </Container>
        <Container>
            <BName id="2"/>
        </Container>
        <Test>
            <BName id="3"/>
            <Context/>
        </Test>
    </Document>
    

    the expression

    //Context/preceding::BName[not(parent::Test)][1]
    

    selects the node

    <BName id="2"/>