2

im trying to take substring of a element with xpath,

<table>
  <tr><td>color : blue</td></tr>
  <tr><td>color - green</td></tr>
  <tr><td>jasmine flower</td></tr>
</table>

td tag contains the color values blue and green seperated by a hyphen or a colon

i have xpath for substring-after colon //tr/td/substring-after(text(),':') which gives me output blue and for substring-after hypen //tr/td/substring-after(text(),'-') which gives me output green

but i want to merge both xpath codes into one single code

i tried the following code //tr/td/[substring-after(text(),':') or substring-after(text(),'-')] which gives me output like this

[true]
[true]
[false] 

and //tr/td/text()[substring-after(.,':') or substring-after(.,'-')] which gives output like

color : blue
color - green

what I need is

blue
green

need a single line code

note : im testing my code in http://videlibri.sourceforge.net/cgi-bin/xidelcgi

2 Answers2

0

I would suggest string-join(//td[matches(., '[:\-]')]/tokenize(., '[:\-]')[2], ' ') or perhaps string-join(//td[matches(., '[:\-]')]/tokenize(., '\s*[:\-]\s*')[2], ' ').

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • 1
    Another option would be to use the `replace` function: `//tr/td[matches(., '[:\-]')]/replace(., '^.*[:\-]\s*(.*)$', '$1')` – Conal Tuohy Aug 12 '22 at 08:18
0

As simple as:

for $t in /*/tr/td/text()[1]/translate(., '-',':')
  return substring-after($t, ':')

XSLT- based verification:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="/">
    <xsl:sequence select=
    "for $t in /*/tr/td/text()[1]/translate(., '-',':')
      return substring-after($t, ':')"/>
  </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on the provided XML document:

<table>
  <tr><td>color : blue</td></tr>
  <tr><td>color - green</td></tr>
  <tr><td>jasmine flower</td></tr>
</table>

The XPath expression is evaluated and the result of this evaluation is copied to the output:

 blue  green 
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431