variablesxslt

Can't figure out how to use XSL variables


I'm using xmlstarlet and have spent hours reading without success. I have this in my XML:

<person pcode="sherry-smith">Sherry Smith</person>
<day>14</day>

I want the XSL to produce this line of HTML:

<span id="sherry-smith-14" onClick="getFile('sherry-smith','sherry-smith-14')">Sherry Smith</span>

I've tried many ways of doing this, all ending up with errors. Here's an example of what I've tried:

  <xsl:for-each select="person">
         <xsl:variable name="pc"> <xsl:value-of select="@pcode">-<xsl:value-of select="day">
           <span id="{$pc}"><xsl:value-of select="."/></span>
       </xsl:variable>
    </xsl:for-each>

Help, please.


Solution

  • Assuming that the context is the parent element where the person and day elements live, you could do something like this:

    <xsl:variable name="pc" select="concat(person/@pcode, '-', day)"/>
    <span id="{$pc}" onclick="getFile('{person/@pcode}', '{$pc}')">
      <xsl:value-of select="person"/>
    </span>
    

    Where you declare the variable $pc with the value of person/@pcode, -, and day and then (outside of the variable) construct the span element and use the $pc variable in the two places.

    Note the use of the curly braces (attribute value templates) in order to reference the variables inside of the literal attribute declaration.