如何使用xslt将xml转换为xsl-fo时创建超链接?

时间:2009-12-14 02:13:18

标签: java xml xslt xalan

我想将随机文本中任何基于http / s的网址转换为xsl-fo自动标记,其中随机文本可能包含一个或多个基于http / s的网址。

因此,http / s url不是属性的一部分,也不是节点的唯一内容,而是节点中文本的一部分。

例如:来源

<misc>
  <comment>Yada..yada..yadda, see http://www.abc.com. 
           Bla..bla..bla.. http://www.xyz.com</comment>
</misc>

将转变为:

<fo:block>
  Yada..yada..yadda, see <fo:basic-link external-destination="http://www.abc.com">http://www.abc.com</fo:basic-link>.
  Bla..bla..bla.. <fo:basic-link external-destination="http://www.xyz.com">http://www.xyz.com</fo:basic-link>
<fo:/block>

我们使用的库是Apache FOP和Xalan-J。

2 个答案:

答案 0 :(得分:2)

如果必须使用纯XSLT方法,可以使用:

<xsl:template match="comment">
  <fo:block>
    <xsl:call-template name="dig-links">
      <xsl:with-param name="content" select="."/>
    </xsl:call-template>
  </fo:block>
</xsl:template>
<xsl:template name="dig-links">
  <xsl:param name="content" />
  <xsl:choose>
    <xsl:when test="contains($content, 'http://')">
      <xsl:value-of select="substring-before($content, 'http://')"/>
      <xsl:variable name="url" select="concat('http://', substring-before(substring-after(concat($content, ' '), 'http://'), ' '))"/>
      <fo:basic-link>
        <xsl:attribute name="external-destination">
          <xsl:choose>
            <xsl:when test="substring($url, string-length($url), 1) = '.'">
              <xsl:value-of select="substring($url, 1, string-length($url)-1)"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$url"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:attribute>
        <xsl:value-of select="$url"/>
      </fo:basic-link>
      <xsl:call-template name="dig-links">
        <xsl:with-param name="content" select="substring-after($content, $url)"/>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$content"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

然而,这不是一个完美的解决方案,因此如果您在网址末尾有两个点的拼写错误,则外部目标属性将获得一个。

答案 1 :(得分:0)

我不知道xsl:fo是什么意思,但是如果你有权访问实际进行转换的xslt文件,你可以使用提到here的xml字符串函数自己转换它。如果您只能访问转换后的输出,那么仍然可以

  • 应用另一个符合您要求的xslt或
  • 使用SAX并使用java正则表达式函数
  • 自行转换
相关问题