incircuitous
incircuitous

Reputation: 141

Can xpath select from one element to a different type of element?

brand new to xpath, so maybe just don't know the terminology to search properly.

I want to grab from the start of a div with a certain id, to the end of a paragraph with a certain id. Note that I only want to select part of the div.

<body>
<div id="meaninglessPreamble">Do not get this data.</div>
<div id="wrapper">
<div id="grabThis">good stuff</div>
<p id="grabThisToo">more good stuff</p>
<p id="endHere"/>
<p id="leaveMeOutOfThis">Unwanted Junk</p>
</div>
</body>

Upvotes: 2

Views: 205

Answers (2)

har07
har07

Reputation: 89295

More general approach, you can try using following-sibling and preceding-sibling to select a range of elements by id attribute.

/body/div[@id='wrapper']/*
        [
            (preceding-sibling::*[@id='grabThis'] or @id='grabThis')
                and
            (following-sibling::*[@id='endHere'] or @id='endHere')
        ]

Above example demonstrates selecting all child elements of <div id="wrapper">, starting from element with id="grabThis" to element with id="endHere" inclusively. If you want it to select exclusively (exclude the limiting elements), simply remove the or @id='...' part.

Upvotes: 2

Mads Hansen
Mads Hansen

Reputation: 66723

One way to select those two elements, by selecting the children of the div who's @id is equal to "wrapper" and their following-sibling is a p element that has an @id equal to "endHere":

/body/div[@id='wrapper']/*[following-sibling::p[@id='endHere']]

Upvotes: 0

Related Questions