Introduction to XPath Functions
A function in XPath, as in most programming languages, is a built-in software routine that performs some operation and returns some value. The returned value effectively replaces the reference (or call) to the function which appears at a given point in the code.
A reference to a function takes the form:
functionname(arg1...)
where:
- functionname is the name of the function;
- the parentheses are required; and
- arg1... is a comma-separated list of values, called arguments, which are used by the function to perform its work. (Note that not all functions take arguments, and in some cases arguments may or may not be required, depending on the circumstances.)
As an example, the XPath specification defines the contains()
function. This function takes two arguments, both of them string values. If the first string contains the second string, the function returns the value True; otherwise, it returns False. For more information about contains()
, see Processing Text Strings by Using String Functions.
Consider the following XML fragment:
<book> <chapter><heading>Help for Lost XPathians</heading></chapter> <chapter><heading>Searching and Sorting</heading></chapter> <chapter><heading>Where to Find Help</heading></chapter> </book>
and the following XPath location path:
//chapter[heading][contains(., "Help")
]
This location path selects all <chapter>
elements with a <heading>
child which contains the string "Help"
—that is, it selects the first and third <chapter>
elements. The function call, contains(., "Help")
, is replaced by the value True for <chapter>
elements which contain the desired text string, and by False for all others.
Note The "." in the call to the contains()
function here forces the context node to be converted to its string value.