views:

135

answers:

2

Is there a way to limit the depth DOMXPath::query will look at?

Consider the following document:

<div>
    <span>
        <div>
        </div>
    </span>
</div>

How could I limit the query

//div

So it only matches the first level and not the descendants?

+2  A: 

Try to describe the path from the root (single /):

/path/to/first/level/div

Or try this:

//div[not(parent::div)]
Gumbo
Apologies, it wasn't clear from my question that the parent element of the 2nd level or 3rd level is not necessarily a div, it could be any element.
Andrei Serdeliuc
@Aprikot: Then what is a first level `div`?
Gumbo
+4  A: 

This will select the div elements that are not inside of any other div elements (similar to Gumbo's answer, but will check all levels, not just direct parent)

//div[not(ancestor::div)]
Mads Hansen
Excellent! You just saved me a recursive function. Thanks a lot!
Andrei Serdeliuc