2017-05-05 77 views
0

我有一個HTML文件,我想用XSLT 1.0 文件的格式爲<file name="/var/application-data/..../application/controllers/cgu.php" />XSL解析文件名文件夾

解析,我想這是 <file filename="cgu.php" folderName="controller/"/>

我管理這個使用<xsl:value-of select="substring-before(substring(@name, 85), '/')"/>做 ,但我希望它適用於所有長度的路徑。 是否可以計算「/」的出現次數來檢索路徑的最後部分?

我用遞歸模板只檢索文件名,但我需要的文件夾名稱也

<xsl:template name="substring-after-last"> 
     <xsl:param name="string"/> 
     <xsl:choose> 
      <xsl:when test="contains($string, '/')"> 
       <xsl:call-template name="substring-after-last"> 
        <xsl:with-param name="string" select="substring-after($string, '/')"/> 
       </xsl:call-template> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:value-of select="$string"/> 
      </xsl:otherwise> 
     </xsl:choose> 
    </xsl:template> 
+0

參見:http://stackoverflow.com/questions/38848374/how-to-find-最後的預覽工作和存儲到我的領域在xslt/38848925#38848925和http://stackoverflow.com/questions/41624974/xsl-display-attribute-after-a-certain-字符/ 41625340#41625340 –

回答

0

一種方式做到這一點,是存儲第一次調用的結果(獲取文件名)在一個變量中,並且第二次調用模板,但name屬性被文件名的長度截斷(所以文件夾名稱現在是最後一項)。

<xsl:template match="file"> 
    <xsl:variable name="fileName"> 
     <xsl:call-template name="substring-after-last"> 
      <xsl:with-param name="string" select="@name" /> 
     </xsl:call-template> 
    </xsl:variable> 
    <xsl:variable name="folderName"> 
     <xsl:call-template name="substring-after-last"> 
      <xsl:with-param name="string" select="substring(@name, 1, string-length(@name) - string-length($fileName) - 1)" /> 
     </xsl:call-template> 
    </xsl:variable> 
    <file filename="{$fileName}" folderName="{$folderName}/"/> 
</xsl:template> 

另外,如果你的程序支持的話,你可以到別的EXSLT的tokenize功能

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" 
    xmlns:str="http://exslt.org/strings" 
    extension-element-prefixes="str"> 
    <xsl:output method="xml" indent="yes" /> 

    <xsl:template match="file"> 
     <xsl:variable name="parts" select="str:tokenize(@name, '/')" /> 
     <file filename="{$parts[last()]}" folderName="{$parts[last() - 1]}/"/> 
    </xsl:template> 
</xsl:stylesheet>