XPath to get one level of childnodes

Greg picture Greg · Jan 1, 2010 · Viewed 11.7k times · Source

Using DOMXPath::query is it possible to get just one level deep of childNodes?

For example if I had a document like:

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

I would want the NodeList to contain just the spans and not the cites.

Should also mention that it won't always be the same elements (divs, spans, etc). I would need it to work with any type of element.

This is what I tried and it didn't seem to work:

//*[not(ancestor::div)]

Answer

Gaim picture Gaim · Jan 1, 2010

If you use

/div/*

then you get a list of all direct children in this element but these children contain their children. I think that you can't remove children of child

There is used default axis, it is called child::. This axis returns only elements in 1 level under the current node

* matches all elements but neither attributes nor text()

You have to specify path to your node and be careful about //node because it means descendant::node and it returns all nodes of this name in this tree