views:

384

answers:

2

I'm trying to format a table from XML. Lets say I have this line in the XML

<country>Dominican Republic</country>

I would like to get my table to look like this

<td class="country DominicanRepublic">Dominican Republic</td>

I've tried this:

<td class="country {country}"><xsl:value-of select="country"/></td>

then this:

<xsl:element name="td">
 <xsl:attribute name="class">
  <xsl:text>country </xsl:text>
  <xsl:value-of select="normalize-space(country)"/>
 </xsl:attribute>
<xsl:value-of select="country"/>
</xsl:element>

The normalize-space() doesn't remove the space between the two parts of the name and I can't use <xsl:strip-space elements="country"/> because I need the space when I display the name inside the table cell.

How can I strip the space from the value inside the class, but not the text in the cell?

+1  A: 

You will need to split your string by whitespaces recursively, have a look at this topic: http://stackoverflow.com/questions/136500/does-xslt-have-a-split-function

Or you can try this replace function implementation: http://geekswithblogs.net/Erik/archive/2008/04/01/120915.aspx

Andrew Bezzub
+2  A: 

Use the translate() function to replace spaces ' ' with nothing '':

<xsl:element name="td">
    <xsl:attribute name="class">
        <xsl:text>country </xsl:text>
        <xsl:value-of select="translate(country,' ','')"/>
        </xsl:attribute>
    <xsl:value-of select="country"/>
</xsl:element>

You can use normalize-space(), which will remove any leading and trailing white space and convert multiple spaces between characters into a single space. Then, send the results through translate() to replace any remaining spaces:

<xsl:element name="td">
   <xsl:attribute name="class">
    <xsl:text>country </xsl:text>
    <xsl:value-of select="translate(normalize-space(country),' ','')"/>
    </xsl:attribute>
    <xsl:value-of select="normalize-space(country)"/>
</xsl:element>
Mads Hansen
Thanks that worked! I'm still learning XSL, so thanks for the help :)
fudgey
Actually the XML is a feed from another site, and there is white space in front of the text. The translate function doesn't remove that, any solution for that? I'm not sure how to stack up functions, like using normalize on country after the translate.
fudgey
If you use translate to remove spaces it should do so for all spaces. Are you sure it isn't tab, carriage return, or other white space? You could use `normalize-space()` and send the results to `translate()`. I'll update the answer with an example.
Mads Hansen
@Mads that was perfect! Thanks again!
fudgey