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
10.38Mb 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

His By Design by Dell, Karen Ann
Friday the Rabbi Slept Late by Harry Kemelman
Anything But Zombies by Gerald Rice
Cooking Most Deadly by Joanne Pence
3 Service for Two by Kate Kingsbury
Sex, Love, and Aliens, Volume 1 by Imogene Nix, Ashlynn Monroe, Jaye Shields, Beth D. Carter
A.I. Apocalypse by William Hertling
Forgive Me by Stacy Campbell