How to use the "translate" Xpath function on a node-set

I know I can find-replace a single item using this xpath

/xmldoc/items/item[1]/translate(text(),'-','')

Which will return

"abc"

however, how do I do this for the entire set?

This cannot be done with a single XPath 1.0 expression.

Use the following XPath 2.0 expression to produce a sequence of strings, each being the result of the application of the translate() function on the string value of the corresponding node:

/xmlDoc/items/item/translate(.,'-', '')

The translate function accepts in input a string and not a node-set. This means that writing something like:

"translate(/xmlDoc/items/item/text(),'-','')"

or

"translate(/xmlDoc/items/item,'-','')"

will result in a function call on the first node only (item[1]).

In XPath 1.0 I think you have no other chances than doing something ugly like:

"concat(translate(/xmlDoc/items/item,'-',''),
 translate(/xmlDoc/items/item[2],'-',''))"

Which is privative for a huge list of items and returns just a string.


In XPath 2.0 this can be solved nicely using for expressions:

  "for $item in /xmlDoc/items/item  
    return replace($item,'-','')"

Which returns a sequence type:

abc cde

PS Do no confuse function calls with location paths. They are different kind of expressions, and in XPath 1.0 can not be mixed.

Tags:

Xpath