7

我希望我生成的输出文件包含指向相对于样式表的路径的文件路径。样式表的位置可以更改,我不想为样式表使用参数。我的解决方案是获取完整的样式表 URI:

<xsl:variable name="stylesheetURI" select="document-uri(document(''))" />

现在我只需要从$stylesheetURI. 这启发了我编写 PHP 函数basenamedirname的 XSLT 2.0 克隆:

<xsl:function name="de:basename">
    <xsl:param name="file"></xsl:param>
    <xsl:sequence select="tokenize($file, '/')[last()]" />
</xsl:function>

<xsl:function name="de:dirname">
    <xsl:param name="file"></xsl:param>
    <xsl:sequence 
        select="string-join(tokenize($file, '/')[position() != last()], '/')" />
</xsl:function>

现在我可以在我的模板中做这样的事情:

<img src="{concat(de:dirname($stylesheetURI),'/img/myimage,png')}" />

我的问题是:是否有更好/更快的方法来使用本机 XSLT 2.0 完成此任务?

4

1 回答 1

8

我测试了(不太广泛)这些功能,它们的执行速度似乎比提供的快 25%。当然,结果取决于字符串长度和限定符的数量:

  <xsl:function name="de:basename" as="xs:string">
    <xsl:param name="pfile" as="xs:string"/>
    <xsl:sequence select=
     "de:reverseStr(substring-before(de:reverseStr($pfile), '/'))
     " />
  </xsl:function>

  <xsl:function name="de:dirname" as="xs:string">
    <xsl:param name="pfile" as="xs:string"/>
    <xsl:sequence select=
     "de:reverseStr(substring-after(de:reverseStr($pfile), '/'))
     " />
  </xsl:function>

  <xsl:function name="de:reverseStr" as="xs:string">
    <xsl:param name="pStr" as="xs:string"/>

    <xsl:sequence select=
    "codepoints-to-string(reverse(string-to-codepoints($pStr)))"/>
  </xsl:function>
于 2010-06-25T13:18:04.320 回答