Take the tour ×  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:   and to get the fall-back element (say, the body) I use:
How do I combine these two expressions above into a single
expression (get #may-not-exist else get body)?  share|improve
this question add comment  1 Answer  up vote 1 down vote
accepted  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()]   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