Cuder
Cuder

Reputation: 163

How can I optimize an XPath expression?

Is there any way I can shorten the following condition used in an XPath expression?

(../parent::td or ../parent::ol or ../parent::ul)

The version of XPath is 1.0.

Upvotes: 2

Views: 1202

Answers (3)

Michael Kay
Michael Kay

Reputation: 163282

The shortest is probably

../..[self::td|self::ol|self::ul]

Whether there is a performance difference between "|" and "or" will depend on the processor, but I suspect that in most cases it won't be noticeable. For performance, the important thing is to put the conditions in the right order (the one most likely to return true should come first). Factoring out the navigation to the grandparent should almost certainly help performance, with the caveats (a) your XPath engine may do this optimization automatically, and (b) the difference will probably be so tiny you will have trouble measuring it.

Upvotes: 2

Daniel Haley
Daniel Haley

Reputation: 52858

Slightly shorter:

../..[self::td or self::ol or self::ul]

Example usage:

//p[../..[self::td or self::ol or self::ul]]

Upvotes: 0

Prashanth Tilleti
Prashanth Tilleti

Reputation: 111

use the '|' operator. (../parent::td|../parent::ol|../parent::ul)

Upvotes: 1

Related Questions