Matt
Matt

Reputation: 82

Select only the second preceding tag if there is one, or then just the first one

I have this HTML:

<h4>block 1</h4>
<p>paragraph 1</p>
<p>paragraph 2</p>
<table></table>

<h4>block 2</h4>
<p>paragraph 1</p>
<table></table>

As you can see, the first block contains two <p></p> tags, while the second block only has one.

I am currently using this XPath: //table/preceding::p[1], which returns:

1. <p>paragraph 2</p>
2. <p>paragraph 1</p>

However, this is what I'd like to have:

1. <p>paragraph 1</p>
2. <p>paragraph 1</p>

So basically the farest "preceding" table p tag, as explained in my question title.

I want to keep using //table/preceding, as this is very important in my case.

I already tried //table/preceding::p[1 or 2], but that selects both. I also tried //table/preceding::p[2] but that will select both paragraphs from the first block, and none from the second one.

As you can probably notice, I'm pretty new to XPath. How can I achieve the desired result?

Upvotes: 1

Views: 54

Answers (1)

DonnyFlaw
DonnyFlaw

Reputation: 690

Try this one to get select desired paragraphs

//table/preceding-sibling::h4[1]/following-sibling::p[1]

Upvotes: 1

Related Questions