从XSL文件中获取样式表目录 - 用于可配置的xml位置

时间:2010-02-27 20:26:00

标签: xslt xslt-2.0

我有一个xml的xsl文件。 xml文件的位置应该是可配置的(通过在xml中配置样式表的href路径来完成)但是xsl正在使用一些图像和一些其他javaScript文件,并且需要有它们的路径。路径就在样式表文件附近,所以一旦我可以获得xsl目录,我就可以了解它们。 例如: 在我的xml中我有:?xml-stylesheet type =“text / xsl”href =“。\ Files \ Style \ test.xsl”> 我希望从xsl中指向图像位置的“。\ Files \ Style” 锄头我能做到吗

1 个答案:

答案 0 :(得分:1)

这是一个XSLT 1.0解决方案(XSLT 2.0具有更强大的字符串处理功能,例如正则表达式):

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

 <xsl:template match="processing-instruction()">
   <xsl:variable name="vpostHref"
    select="substring-after(., 'href=')"/>

   <xsl:variable name="vhrefData1"
    select="substring($vpostHref,2)"/>

   <xsl:variable name="vhrefData2"
    select="substring($vhrefData1, 1,
                      string-length($vhrefData1)-1
                      )"/>

   <xsl:call-template name="stripBackwards">
    <xsl:with-param name="pText"
      select="$vhrefData2"/>
    <xsl:with-param name="pTextLength"
     select="string-length($vhrefData2)"/>
   </xsl:call-template>
 </xsl:template>

 <xsl:template name="stripBackwards">
  <xsl:param name="pText"/>
  <xsl:param name="pStopChar" select="'\'"/>
  <xsl:param name="pTextLength"/>

  <xsl:choose>
   <xsl:when test="not(contains($pText, $pStopChar))">
     <xsl:value-of select="$pText"/>
   </xsl:when>
   <xsl:otherwise>
     <xsl:variable name="vLastChar"
       select="substring($pText,$pTextLength,1)"/>
     <xsl:choose>
       <xsl:when test="$vLastChar = $pStopChar">
        <xsl:value-of select="substring($pText,1,$pTextLength -1)"/>
       </xsl:when>
       <xsl:otherwise>
        <xsl:call-template name="stripBackwards">
          <xsl:with-param name="pText"
           select="substring($pText,1,$pTextLength -1)"/>
          <xsl:with-param name="pTextLength" select="$pTextLength -1"/>
          <xsl:with-param name="pStopChar" select="$pStopChar"/>
        </xsl:call-template>
       </xsl:otherwise>
     </xsl:choose>
   </xsl:otherwise>
  </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

将此转换应用于以下XML文档

<?xml-stylesheet type="text/xsl" href=".\Files\Style\test.xsl"?>
<t/>

产生了正确的结果

.\Files\Style