Search code examples
cssxsltattributesstylesheetparent-child

Using XSLT/XML to generate styles for HTML tags? (xsl:attribute-set)


Okay, it's been a tough hour or so... I'm having difficulties generating table cells with different widths. I'm using XML/XSLT to spit out my HTML, so basically the widths are stored in XML format:

<size>
<width1>5</width1>
<width2>4</width2>
<width3>7</width3>
</size>

Using XSLT's attribute-set I should have a table row and cells with 5px, 4px, 7px widths respectively. However, the trouble with this is that attribute-set needs to be a child of <xsl:stylesheet> for it to work. I CAN'T do this: (forgive the missing px)

<tr>
    <td>
        <xsl:attribute-set name="style">
            <xsl:attribute name="width"><xsl:value-of select="size/width1"/></xsl:attribute>
        </xsl:attribute-set>
    </td>
    <td>
        <xsl:attribute-set name="style">
            <xsl:attribute name="width"><xsl:value-of select="size/width2"/></xsl:attribute>
        </xsl:attribute-set>
    </td>
    <td>
        <xsl:attribute-set name="style">
            <xsl:attribute name="width"><xsl:value-of select="size/width3"/></xsl:attribute>
        </xsl:attribute-set>
    </td>
</tr>

Is there any way to generate html tag using XML data to style them?


Solution

  • Instead of xsl:attribute-set you need to add an xsl:attribute inside your <td> element:

    <xsl:template match="size">
        <tr>
            <td>
                <xsl:attribute name="width">
                    <xsl:value-of select="./width1"/>
                </xsl:attribute>
            </td>
    
            <td>
                <xsl:attribute name="width">
                    <xsl:value-of select="./width2"/>
                </xsl:attribute>
            </td>
    
            <td>
                <xsl:attribute name="width">
                    <xsl:value-of select="./width3"/>
                </xsl:attribute>
            </td>
        </tr>
    </xsl:template>