如何使用XSL 1.0拆分文件路径并提取指定组件
在XSL 1.0中从可变前缀文件路径提取指定组件
因为你只能用XSL 1.0,且路径前缀长度可变但末尾固定为\part\rev\testname.seq结构,可以通过从后往前提取路径段的方式实现需求。核心思路是利用递归模板获取路径中的最后一段,依次提取testname、rev、part。
完整实现代码
<!-- 定义递归模板:获取字符串按指定分隔符分割后的最后一段 --> <xsl:template name="get-last-path-segment"> <xsl:param name="input-string"/> <xsl:param name="delimiter" select="'\'" /> <xsl:choose> <!-- 如果字符串还包含分隔符,继续截取后面的部分 --> <xsl:when test="contains($input-string, $delimiter)"> <xsl:call-template name="get-last-path-segment"> <xsl:with-param name="input-string" select="substring-after($input-string, $delimiter)"/> </xsl:call-template> </xsl:when> <!-- 没有分隔符时,当前字符串就是最后一段 --> <xsl:otherwise> <xsl:value-of select="$input-string"/> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- 主处理逻辑 --> <xsl:variable name="original-path" select="@name"/> <!-- 第一步:移除.seq扩展名 --> <xsl:variable name="path-without-ext" select="substring-before($original-path, '.seq')"/> <!-- 提取testname:路径去掉扩展名后的最后一段 --> <xsl:variable name="testname"> <xsl:call-template name="get-last-path-segment"> <xsl:with-param name="input-string" select="$path-without-ext"/> </xsl:call-template> </xsl:variable> <!-- 提取rev:去掉testname后的路径的最后一段 --> <xsl:variable name="path-up-to-rev" select="substring-before($path-without-ext, concat('\', $testname))"/> <xsl:variable name="rev"> <xsl:call-template name="get-last-path-segment"> <xsl:with-param name="input-string" select="$path-up-to-rev"/> </xsl:call-template> </xsl:variable> <!-- 提取part:去掉rev后的路径的最后一段 --> <xsl:variable name="path-up-to-part" select="substring-before($path-up-to-rev, concat('\', $rev))"/> <xsl:variable name="part"> <xsl:call-template name="get-last-path-segment"> <xsl:with-param name="input-string" select="$path-up-to-part"/> </xsl:call-template> </xsl:variable> <!-- 输出指定格式的内容 --> TestName: <xsl:value-of select="$testname"/> Part:<xsl:value-of select="$part"/> Rev: <xsl:value-of select="$rev"/>
逻辑说明
- 递归模板
get-last-path-segment:反复截取字符串中分隔符(\)后面的部分,直到没有分隔符,返回最后一段路径。 - 移除扩展名:用
substring-before去掉.seq后缀,得到纯路径字符串。 - 依次提取组件:
- 先取去掉扩展名后的路径最后一段,得到
testname; - 截取掉
testname的路径,再取最后一段得到rev; - 截取掉
rev的路径,最后取最后一段得到part。
- 先取去掉扩展名后的路径最后一段,得到
这种方法完全兼容XSL 1.0,且不受前缀路径长度变化的影响。
内容的提问来源于stack exchange,提问作者Somin
相关产品推荐
相关产品推荐

