在XSLT中将xsl:value-of设置为href属性和链接的文本字段

41

我该如何在XSLT转换中设置既是链接又包含链接文本的a href?这是我目前的代码,但会报错"xsl:value-of不能成为xsl:text元素的子元素":

<xsl:element name="a">
   <xsl:attribute name="href">
      <xsl:value-of select="actionUrl"/>
   </xsl:attribute>
   <xsl:text><xsl:value-of select="actionUrl"/></xsl:text> 
</xsl:element>
4个回答

50

<xsl:text>定义了XSL文档中的文本部分。这里只能放置真正的纯文本,而不能是XML节点。你只需要<xsl:value-of select="actionUrl"/>,它会打印出纯文本。

<xsl:element name="a">
    <xsl:attribute name="href">
        <xsl:value-of select="actionUrl"/>
    </xsl:attribute>
    <xsl:value-of select="actionUrl"/>
</xsl:element>

1
仅供参考,首先提名href,其次是显示文本,就像您所做的那样似乎很重要。我将它反过来,但未能显示。 - Des Horsley
这段代码冗长且难以阅读,请查看 lexicore 的回答 - TWiStErRob

31

你也可以这样做:

<a href="{actionUrl}"><xsl:value-of select="actionUrl"/></a>

谢谢,Dimitre,是打错了。最近EL用太多了。 - lexicore
1
实际上,actionurl 不是一个变量,只是一个元素名称。因此,在名称开头不应该有 "$" 符号。 - Dimitre Novatchev

6

您不需要使用xsl:text元素:

<xsl:element name="a">
  <xsl:attribute name="href">
    <xsl:value-of select="actionUrl"/>
  </xsl:attribute>
  <xsl:value-of select="actionUrl"/>
</xsl:element>

0
我想使用.xsl文件来确保在将多个XML提取格式化为.html报告时,超链接的一致性。每个记录都有一个名为ID的主键 - 一个自动递增的数字 - 它作为参数传递给各种报告,但从未显示为这些报告中的列。以下是我的做法。
<?xml version="1.0"?>

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

<xsl:template match="/">
    <html>
        <body>
            <table>
                <xsl:for-each select="table/row">
                    <tr>
                        <xsl:apply-templates>
                            <!-- id is primary key and is passed as a parameter to all the templates whether they need it or not -->
                            <xsl:with-param name="id"><xsl:value-of select="id"/></xsl:with-param>
                        </xsl:apply-templates>
                    </tr>
                </xsl:for-each>
            </table>
        </body>
    </html>
</xsl:template>

<xsl:template match="id">
    <!-- id is primary key and is never shown -->
</xsl:template>

<xsl:template match="employee_number">
    <!-- employee_number field always links to the attendance report -->
    <xsl:param name="id"/>
    <xsl:variable name="name"><xsl:value-of select="name(.)"/></xsl:variable>
    <td id="{$name}"><a href="attendance?id={$id}"><xsl:value-of select="."/></a></td>
</xsl:template>

<!-- other templates redacted for clarity/brevity -->

<xsl:template match="*">
    <!-- any field without a dedicated template is just a cell in the table -->
    <xsl:variable name="name" select="name(.)"/>
    <td id="{$name}"><xsl:value-of select="."/></td>
</xsl:template>

</xsl:stylesheet>

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