Monday account
Monday account

Reputation: 1

XPath for <td> element

I have a line "line1, line2, line3" in the td tag. However i am interested in getting the line2 as the output using XPath expression.

<table class = "class1">
<tbody>
   <tr>
     <td>
          line 1, line 2, line 3
    </td>
   </tr>
 </tbody>
 </table>

Any input on this will be helpful

Upvotes: 0

Views: 417

Answers (1)

Mathias M&#252;ller
Mathias M&#252;ller

Reputation: 22647

This returns "line 2":

/table/tbody/tr/td/normalize-space(tokenize(.,',')[2])

What it does, in plain English:

Look for td inside a tr element, which is in turn inside a tbody element which is inside table. Tokenize this td, taking a comma as the delimiter of separate tokens. Return the second item in the resulting list. Strip any trailing whitespace with normalize-space().

The expression only works if you can rely on the string parts being delimited by something like a comma.

This makes use of functions that are only available in XPath 2.0. If you tagged this question with xpath-2.0 by accident, the answer will not help much.

XSLT Stylesheet for illustration

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="text"/>

    <xsl:template match="/">
      <xsl:value-of select="/table/tbody/tr/td/normalize-space(tokenize(.,',')[2])"/>
    </xsl:template>

</xsl:transform>

Text Output

line 2

Upvotes: 1

Related Questions