I’m trying to add a value (in this case the string “I Added This”) to all -nodes within a specific column if the column does contain a certain value (in this case the text “I Want You”) using XSLT 2.0.
This means, if I have the following table:
<table>
<tr>
<th>header value</th>
<th>I Want You</th>
<th>header value</th>
</tr>
<tr>
<td>value 1</td>
<td>value 2</td>
<td>value 3</td>
</tr>
<tr>
<td>value 4</td>
<td>value 5</td>
<td>value 6</td>
</tr>
</table>
the output should be this after I apply the xslt script:
<table>
<tr>
<th>header value</th>
<th>I Want You</th>
<th>header value</th>
</tr>
<tr>
<td>value 1</td>
<td>I Added This value 2</td>
<td>value 3</td>
</tr>
<tr>
<td>value 4</td>
<td>I Added This value 5</td>
<td>value 6</td>
</tr>
</table>
To achieve that I wrote many different stylesheets but I didn’t even came close:
Copying the entire table:
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
This gets me the values of the column I want to change – but from there I don’t know how to prepend each td-value with the phrase “I Added This Value”
<xsl:template match="//th[contains(lower-case(.), 'I Want You')]">
<xsl:variable name="tdPos" select="count(preceding-sibling::td)+2"/>
<xsl:for-each select="current()/parent::*/following-sibling::tr">
<xsl:value-of select="./td[$tdPos]/text()"/>
</xsl:for-each>
</xsl:template>
Any hints that might point me into the right direction are greatly appreciated!
One problem worth noting is that your “contains” test is not quite right
It probably be the following
However, it might be better all round if you parameterise your search values, although you wouldn’t be able to use such parameter in the template match. Instead you would just match any cell….
Then you could test if equivalent column on a preceding row has the value you want
(lower-case() command removed for brevity)
Here $position will be a variable containing the current cell position, and $match is the variable you are looking for.
Try the following XSLT
When applied to your XML, the following is produced
And when applied to this XML
The following is output