XPath to select multiple tags

nickf picture nickf · Apr 6, 2009 · Viewed 137.5k times · Source

Given this simplified data format:

<a>
    <b>
        <c>C1</c>
        <d>D1</d>
        <e>E1</e>
        <f>don't select this one</f>
    </b>
    <b>
        <c>C2</c>
        <d>D2</d>
        <e>E1</e>
        <g>don't select me</g>
    </b>
    <c>not this one</c>
    <d>nor this one</d>
    <e>definitely not this one</e>
</a>

How would you select all the Cs, Ds and Es that are children of B elements?

Basically, something like:

a/b/(c|d|e)

In my own situation, instead of just a/b/, the query leading up to selecting those C, D, E nodes is actually quite complex so I'd like to avoid doing this:

a/b/c|a/b/d|a/b/e

Is this possible?

Answer

Dimitre Novatchev picture Dimitre Novatchev · Apr 6, 2009

One correct answer is:

/a/b/*[self::c or self::d or self::e]

Do note that this

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

is both too-long and incorrect. This XPath expression will select nodes like:

OhMy:c

NotWanted:d 

QuiteDifferent:e