Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT - Is there a way to append to attributes added with <xsl:attribute>?

Tags:

xml

xslt

Simplified example:

<xsl:template name="helper">
  <xsl:attribute name="myattr">first calculated value</xsl:attribute>
</xsl:template>

<xsl:template match="/>
  <myelem>
    <xsl:call-template name="helper" />
    <xsl:attribute name="myattr">second calculated value</xsl:attribute>
  </myelem>
</xsl:template>

Is there some way for the second to append the second calculated value to the same myattr attribute in the result node?

I've seen it is possible to use an attribute value template if the target attribute is in the source xml, but can I reference somehow the value of the attribute I have earlier appended to the result node?

Thanks in advance!

like image 844
Theodore Lytras Avatar asked Sep 27 '13 08:09

Theodore Lytras


2 Answers

One approach you could take is add a parameter to your helper template, which you append to the attribute value.

<xsl:template name="helper">
  <xsl:param name="extra" />
  <xsl:attribute name="myattr">first calculated value<xsl:value-of select="$extra" /></xsl:attribute>
</xsl:template>

Then you can just past in your second calculate value as the parameter

<xsl:template match="/>
  <myelem>
    <xsl:call-template name="helper">
      <xsl:with-param name="extra">second calculated value</xsl:with-param>
    </xsl:call-template>
  </myelem>
</xsl:template>

You don't have to set the param with each call though. If you don't want anything appended, just called the helper template with no parameter, and won't append anything to the first calculated value.

like image 99
Tim C Avatar answered Nov 18 '22 15:11

Tim C


The simplest approach would be to change the nesting a bit - have the helper just generate text nodes and put the <xsl:attribute> in the calling template:

<xsl:template name="helper">
  <xsl:text>first calculated value</xsl:text>
</xsl:template>

<xsl:template match="/>
  <myelem>
    <xsl:attribute name="myattr">
      <xsl:call-template name="helper" />
      <xsl:text>second calculated value</xsl:text>
    </xsl:attribute>
  </myelem>
</xsl:template>

This will set myattr to "first calculated valuesecond calculated value" - if you want a space between "value" and "second" you must include that inside one of the <xsl:text> elements

      <xsl:text> second calculated value</xsl:text>
like image 35
Ian Roberts Avatar answered Nov 18 '22 16:11

Ian Roberts