2014-01-25 43 views
0

我有一个包含多个元素的XML文件。我正在使用XSLT将每个转换为一个唯一的XML文件。每个人都有一个id属性,我想在文件名中使用,我试图清理属性值。 id全部以capi_开头,有些以_output结尾,因此格式为capi_xxx_yyy_output或capi_xxx_yyy。使用Xpath提取字符串的中间部分

我可以提取capi_后的字符串:

<xsl:for-each select="//section"> 
     <xsl:variable name="cleanId" select="substring-after(@id, '_')" /> 

从这个新的字符串,我怎么抢_output前的字符串?我试过但它没有工作:

<xsl:for-each select="//section"> 
     <xsl:variable name="cleanId" select="substring-before(substring-after(@id, '_'), '_output')" /> 

在此先感谢。

+0

因此,对于您的cleanId变量,您是否希望它最终保留值xxx_yyy? –

+0

是的,对不起,应该指定那个。 – bonehelmet

回答

1

我试过,但没有奏效:

<xsl:for-each select="//section"> <xsl:variable name="cleanId" select="substring-before(substring-after(@id, '_'), '_output')" />

当ID以 “_output” 结束它的工作原理;它不会停止工作。因此,只要确保它总是这样:

<xsl:variable name="cleanId" select="substring-before(substring-after(concat(@id, '_output'), '_'), '_output')" /> 
0

你的语法看起来不错,你可能只需要实现一个<xsl:choose>

<xsl:variable name="cleanId"> 
    <xsl:for-each select="//section"> 
     <xsl:choose> 
     <xsl:when test="contains(@id,'_output')"> 
      <xsl:value-of select="substring-before(substring-after(@id, '_'), '_output')" /> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:value-of select="substring-after(@id, '_')" /> 
     </xsl:otherwise> 
     </xsl:choose> 
    </xsl:for-each> 
</xsl:variable> 
+0

这个答案对我很有意义,但是当我用部分替换我的行时,我在每个变量行上都得到一个错误:W [Saxon-B 9.1.0.7]没有以下兄弟指令的变量没有效果 – bonehelmet

+0

另外,I在稍后的一行中出现错误:变量$ cleanId没有被声明。另一个答案有用,但我想我会报告我的结果。 – bonehelmet

+0

对不起,我没有包含适当的变量范围。变量必须围绕'for-each',以便它的范围适当,并且可以在循环之外使用。 –