XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition (447 page)

BOOK: XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition
12.97Mb size Format: txt, pdf, ePub

Here are some other examples of simple mapping expressions at work:

Expression
Description
sum(order/(@price*@quantity))
Returns the result of calculating
@price
times
@quantity
for each child

and summing the results.
string-join(ancestor::*/name(), ‘/’)
Returns a string such as
book/chapter/section/para
giving the names of the ancestors of the context node, separated by
/
characters.
avg(product/number(substring-after(@price, ‘$’)))
Returns the result of taking the
@price
attributes of all the child

elements, stripping off the leading
$
sign, converting to a number, and then averaging.

In most cases the system will be able to distinguish a path expression from a simple mapping expression by the way it is written. In some cases, however—for example, if the expression calls a user-written function whose return type is not declared—the two cases can't be distinguished until runtime. The initial processing in both cases is the same: for each item in the sequence returned by the first expression, evaluate the second expression and concatenate the results. The rule is then:

  • If all the items in the result are nodes, we have a path expression. Duplicate nodes are eliminated, and those that remain are sorted into document order.
  • If all the items in the result are atomic values, we have a simple mapping expression, and we are done.
  • If there's a mixture of nodes and atomic values, an error is reported.

A simple mapping expression always maps from nodes to atomic values. You can't have atomic values on the left-hand side of the
/
operator. For example, you can't write
avg(*/name()/string-length())
to get the average length of the names of the child elements. Only the last step in the path can return atomic values, so you have to write this as
avg(*/string-length(name()))
. Why the restriction? Possibly because some people didn't like the consequence that the value of
1/10
would be 10.

Other books

Intimate Portraits by Dale, Cheryl B.
A Seduction at Christmas by Cathy Maxwell
Witch House by Dana Donovan
Death in the Secret Garden by Forrest, Richard;
Song of the Spirits by Sarah Lark
Voyage of the Snake Lady by Theresa Tomlinson
Rebel Baron by Henke, Shirl
Becoming Madame Mao by Anchee Min
The Cloaca by Andrew Hood