map expression expression
NOTE: THE SEMANTICS OF COMMAND HAS CHANGED IN 2.1.0
This command provides an easy way to transform node's data (content) using arbitrary expression. It takes two arguments: a mapping expression and a node-list.
First the second argument is evaluated to a node-list.
For each of the nodes,
the mapping expression is evaluated
and the result is used to replace the original content
of the node.
The node is made the context node for the time
of evaluation of the mapping expression.
Moreover, if the expression is a Perl code,
it gets the original text content in
the variable $_
.
Note that if the processed node is an element than the mapping expression may even produce nodes which are then copied into the element discarding any previous content of the element.
If the mapping expression returns an undefined value for a node, then its content is kept untouched.
--in-place
(:i
) flag:
if the expression is a Perl code, then
it is sometimes convenient to change the value
in place. In that case use this flag to indicate that the result
should to be taken from the $_
variable
rather than from the value of the expression itself.
Without this flag, $_
is read-only.
--reverse
(:r
) flag
instruct the map to process the nodelist
in reversed order.
Example 39. Changes Goblins to Orcs in all hobbit tales (\b matches word boundary).
map :i { s/\bgoblin\b/orc/gi } //hobbit/tale/text();
Example 40. Recompute column sums in the last row of row-oriented table
map sum(/table/row[position()<last()]/ cell[count(xsh:current()/preceding-sibling::cell)+1]) /table/row[last()]/cell;
Example 41. The following commands do all about the same:
wrap --inner Z //*; map --reverse xsh:parse(concat("<Z>",xsh:serialize(node()),"</Z>")) //*; map xsh:parse(concat("<Z>",xsh:serialize(node()),"</Z>")) { reverse xpath('//*') };
Note that in the last example we use
:r
(or Perl reverse
function) to reverse the node list order so that child
nodes get processed before their parents. Otherwise, the child
nodes would be replaced by parent's new content before the
processing could reach them.