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

I have an XML document containing dash elements that I would like to delete

eg.

<xmlDoc> <items> <item>abc</item> <item>cde</item> <items> </xmlDoc> 

I know what I can find - replace one element using this xpath

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

which will return

"a"

How to do this for the whole set?

This does not work

 /xmldoc/items/item/translate(text(),'-','') 

And this

 translate(/xmldoc/items/item/text(),'-','') 

Is there any way to achieve this?

+6
source share
2 answers

I know what I can find - replace single using this xpath

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

What will return

 "abc" 

however, how to do this for the whole set?

This cannot be done with a single XPath 1.0 expression .

Use the following XPath 2.0 expression to create a sequence of strings, each of which is the result of applying the translate() function on the string value of the corresponding node:

 /xmlDoc/items/item/translate(.,'-', '') 
+12
source

The translate function takes string input and not a node -set. This means something like:

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

or

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

will cause a function call only for the first node ( item[1] ).

In XPath 1.0, I think you have no other chance than doing something ugly:

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

Which is private for a huge list of elements, but returns only a string .


In XPath 2.0, this can be easily solved with the help of expressions :

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

Which returns the type of sequence :

 abc cde 

PS Do not confuse function calls with a location path . These are different expressions, and in XPath 1.0 you cannot mix.

+3
source

Source: https://habr.com/ru/post/891758/


All Articles