XSLT - 是否有一种方法来追加添加了<xsl:attribute>的属性?

7

简单示例:

<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>

第二个计算值能否以某种方式将其附加到结果节点中相同的myattr属性?

如果目标属性在源xml中,可以使用属性值模板,但我是否可以引用先前附加到结果节点的属性值?

提前致谢!

4个回答

4
您可以采用的一种方法是在您的帮助程序模板中添加一个参数,然后将其附加到属性值中。
<xsl:template name="helper">
  <xsl:param name="extra" />
  <xsl:attribute name="myattr">first calculated value<xsl:value-of select="$extra" /></xsl:attribute>
</xsl:template>

然后,您只需将第二个计算值作为参数粘贴即可。
<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>

不过,您并不需要在每次调用时都设置参数。如果您不想添加任何内容,请调用没有参数的helper模板,并且不会在第一个计算值后追加任何内容。


好主意!不过我还有一个问题:我可以给“helper”模板添加更多参数,然后在调用中使用更多的xsl:with-param元素吗? - Theodore Lytras
(回答我的问题:)是的,可以使用更多的参数。 - Theodore Lytras

3
最简单的方法是稍微改变嵌套结构——让helper只生成文本节点,将<xsl:attribute>放在调用模板中:
<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>

这将设置myattr值为"第一个计算的值第二个计算的值",如果你想在"value"和"second"之间加一个空格,那么你必须把它放在<xsl:text>元素中的其中一个内部。
      <xsl:text> second calculated value</xsl:text>

这是一个很好的答案,尽管在实际情况中,“helper”模板添加了更多属性,并且在“<myelem>”节点中可能会根据某些计算修改“myattr”。因此,这是一个不错的想法,但在我的情况下并不方便。 - Theodore Lytras

0

虽然它们基本上是相同的,但我更喜欢更简洁的创建变量的方式,而不是使用帮助器模板。请注意,在更复杂的情况下,您仍然可以从xsl:variable中调用模板。

<xsl:template match="/">
  <myelem>
    <xsl:variable name="first">first calculated value </xsl:variable >
    <xsl:attribute name="myattr">
       <xsl:value-of select="concat($first, 'second calculated value')"/>
    </xsl:attribute>
  </myelem>
</xsl:template>

0

试试这个:

  <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:variable name="temp" select="@myattr"/>
      <xsl:attribute name="myattr">
        <xsl:value-of select="concat($temp, 'second calculated value')"  />
      </xsl:attribute>
    </myelem>
  </xsl:template>

3
这样做行不通 - select="@myattr" 会在输入树的上下文节点中查找,而不是输出树。 在这种情况下,该节点是文档根节点(/),它永远不可能有任何属性。 - Ian Roberts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接