Xpath To Select All Elements Between Two Headings?
Headline 1
some text
some more text
- list item 1
- list item 2
Solution 1:
This XPath,
//*[ preceding-sibling::h2[. = 'Headline 1'] andfollowing-sibling::h2[. = 'Headline 2']]
will select all elements between h2
s with string values of 'Headline 1'
and 'Headline 2'
:
<p>some text</p>
<p>some more text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<p>more text</p>
Andersson points out in the comments that OP wants the first h2
included in the selection.
Andersson's initial thought would work:
//h2[. = 'Headline 1'] |//*[ preceding-sibling::h2[. = 'Headline 1'] andfollowing-sibling::h2[. = 'Headline 2']]
Here's another way:
//*[self::h2[. = 'Headline 1']or ( preceding-sibling::h2[. = 'Headline 1']
and following-sibling::h2[. = 'Headline 2']]
Or, probably the ideal way:
//h2[. = 'Headline 2']
/preceding-sibling::*[not(following-sibling::h2[. = 'Heading 1'])]
because it avoids having to specify 'Heading 1'
twice.
Solution 2:
What if try something like
//*[text()="Headline 1"]/following-sibling::*
Solution 3:
//h2[contains(.,'Headline 1')]//*
Will return every element below the header. You could further narrow it down with
//h2[contains(.,'Headline 1')]//p
for paragraph text, but that would not include the li elements.
Post a Comment for "Xpath To Select All Elements Between Two Headings?"