XPath - select one element or another

2020-03-01 09:56发布

问题:

I'm using XPath to get exactly one element from a HTML document. The element must have a specific id, or if the id does not exist, then get an element that is guaranteed to exist (such as the body element).

To get an element by its id I use:

css=#may-not-exist

and to get the fall-back element (say, the body) I use:

css=body

How do I combine these two expressions above into a single expression (get #may-not-exist else get body)?

回答1:

Using body as the default is possible. It will come first from the expression, because it starts before anything else (unless you are searching for something in the head.

(//*[@id="xxx"] | //body)[last()]

Explanation:

The ( ... | ... ) part returns a union of its subparts. These are *[@id="xxx"] -- any element whose attribute id has the value of xxx -- and //body, i.e. the body. From this union, [last()] selects the last one. The returned nodes are ordered the same way as in the original document, so body comes first (at least before anything from inside of body). If an element with the id existed, it would come after body and would be returned. If not, body would be returned as the only (first and last) node returned from the union.



标签: xpath