R. Zhu
R. Zhu

Reputation: 415

Select nodes that 1) precede a given node but 2) are also descendants of another given node

Say I have the following XML:

<body>
    <div id="global-header">
        header
    </div>

    <div class="a">
        <h3>some title</h3>
        
        <p>text 1</p>
        
        <p>text 2</p>
        
        <p>text 3</p>
    </div>

</body>

I want to

  1. find any <p> node whose value is "text 2", and then
  2. find all the nodes that precede this particular <p> but are also descendants of the <div class='a'> node.

The desired output should look like:

<h3>some title</h3>

<p>text 1</p>

The caveat is that the preceding nodes may contain arbitrary node type, not only <h3> and <p>, as in the above case.

My first try:

.//p[text()="text 2"]/preceding::*

Unfortunately, this will also select <div id="global-header">, which is not desired.

Upvotes: 1

Views: 32

Answers (1)

JaSON
JaSON

Reputation: 4869

You need to use preceding-sibling to select nodes that are children of the same parent instead of preceding:

.//p[text()="text 2"]/preceding-sibling::*

Upvotes: 2

Related Questions