How to use XSL to create HTML attributes?

Your original xsl is not well formed as you can't have the xsl tag inside another node.

I think you need to use xsl:attribute as follows:

<li>
  <xsl:attribute name="style">
     width:<xsl:value-of select="width"/>px;
  </xsl:attribute>
</li>

Why can't I do this?

<li style="width:<xsl:value-of select="width"/>px">

Because XSL is XML itself. And this is anything… but not XML.

You mean an Attribute Value Template:

<li style="width:{width}px">

or the explicit form, for more complex expressions:

<li>
  <xsl:attribute name="style">
    <xsl:choose>
      <xsl:when test="some[condition = 'is met']">thisValue</xsl:when>
      <xsl:otherwise>thatValue</xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
</li>

or dynamic attribute names (note that attribute value template in the name):

<li>
  <xsl:attribute name="{$attrName}">someValue</xsl:attribute>
</li>

Additional note: Attributes must be created before all other child nodes. In other words, keep <xsl:attribute> at the top.

Tags:

Html

Xml

Xslt