Hyperlinks within XSLT Templates

2019-06-24 19:40发布

问题:

I am trying to create hyperlinks using XML information and XSLT templates. Here is the XML source.

<smartText>
Among individual stocks, the top percentage gainers in the S. and P. 500 are 
<smartTextLink smartTextRic="http://investing.domain.com/research/stocks/snapshot
/snapshot.asp?ric=HBAN.O">Huntington Bancshares Inc</smartTextLink>
and 
<smartTextLink smartTextRic="http://investing.domain.com/research/stocks/snapshot
/snapshot.asp?ric=EK">Eastman Kodak Co</smartTextLink>
.
</smartText>

I want the output to look like this, with the company names being hyperlinks based on the "smartTextLink" tags in the Xml.

Among individual stocks, the top percentage gainers in the S.&P. 500 are Eastman Kodak Co and Huntington Bancshares Inc.

Here are the templates that I am using right now. I can get the text to display, but not the hyperlinks.

<xsl:template match="smartText">
  <p class="smartText">
    <xsl:apply-templates select="child::node()" />
  </p>
</xsl:template>

<xsl:template match="smartTextLink">
  <a>
    <xsl:apply-templates select="child::node()" />
    <xsl:attribute name="href">
      <xsl:value-of select="@smartTextRic"/>
    </xsl:attribute>
  </a> 
</xsl:template>      

I have tried multiple variations to try to get the hyperlinks to work correctly. I am thinking that the template match="smartTextLink" is not being instantiated for some reason. Does anyone have any ideas on how I can make this work?

EDIT: After reviewing some of the answers, it is still not working in my overall application.

I am calling the smartText template from within my main template

using the following statement...

<xsl:value-of select="marketSummaryModuleData/smartText"/>   

Could this also be a part of the problem?

Thank you

Shane

回答1:

Either move the xsl:attribute before any children, or use an attribute value template.

<xsl:template match="smartTextLink">
    <a href="{@smartTextRic}">
        <xsl:apply-templates/>
    </a> 
</xsl:template>

From the creating attributes section of the XSLT 1 spec:

The following are all errors:

  • Adding an attribute to an element after children have been added to it; implementations may either signal the error or ignore the attribute.


回答2:

Try this - worked for me:

<xsl:template match="smartText">
    <p class="smartText">
      <xsl:apply-templates/>
    </p>
  </xsl:template>

  <xsl:template match="smartTextLink">
    <a>
      <xsl:attribute name="href">
        <xsl:value-of select="@smartTextRic"/>
      </xsl:attribute>
      <xsl:value-of select="text()"/>
    </a>
  </xsl:template>

Trick is - <xsl:attribute> first, before you do any other processing.

Marc



标签: xslt