Stefan Taseski
Stefan Taseski

Reputation: 232

XSL - append value to existing attribute in XML node (HTML)

I want to append value to some attribute in given node that matches a xsl-template

Here is my code. Can someone tell me why is's not working? :)

    <xsl:template match="//*[contains(@class,'right-aligned') and @style]">
       <xsl:variable name="currentAttributeValue" select="@style"/>
       <xsl:attribute name="style">
          <xsl:value-of select="concat($currentAttributeValue, 'text-align: right !important;')"  />
       </xsl:attribute>
    </xsl:template>

I've also tried with calling a "helper" template with parameters:

    <xsl:template match="//*[contains(@class,'full-width') and @style]">
       <xsl:variable name="currentAttributeValue" select="@style"/>
       <xsl:call-template name="concat">
          <xsl:with-param name="first" select="$currentAttributeValue"/>
          <xsl:with-param name="second">width: 100% !important; display: inline-block;</xsl:with-param>
       </xsl:call-template>
    </xsl:template>

and here is the helper:

    <xsl:template name="concat">
       <xsl:param name="first" />
       <xsl:param name="second" />
       <xsl:attribute name="style">
          <xsl:value-of select="$first" />
           <xsl:value-of select="$second" />
       </xsl:attribute>
    </xsl:template>

But this is not working either ... Any suggestions?

Upvotes: 2

Views: 2587

Answers (2)

Andrew
Andrew

Reputation: 1

From here: https://www.sitepoint.com/community/t/xslt-appending-to-a-attribute/1669

The recommendation is:

<xsl:attribute name="attr">

    <!-- copy the current value of attr -->
    <xsl:value-of select="@attr" />

    <!-- add more to attr here -->
    blahblah

</xsl:attribute>

For more on the @: https://www.w3schools.com/xml/xpath_syntax.asp

@ Selects attributes

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167506

I would suggest to write a template for the attribute e.g. http://xsltransform.net/jxDigUy which does

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[contains(@class,'full-width')]/@style">
        <xsl:attribute name="style" select="concat(., 'text-align: right !important;')"/>
    </xsl:template>
</xsl:transform>

With XSLT 1.0 you don't have the select attribute for xsl:attribute and therefore need to implement that template as

    <xsl:template match="*[contains(@class,'full-width')]/@style">
        <xsl:attribute name="style">
          <xsl:value-of select="concat(., 'text-align: right !important;')"/>
        </xsl:attribute>
    </xsl:template>

Upvotes: 2

Related Questions