2012-03-29 55 views
2

我有,我必须找到模式,并把周围的匹配特定模式的“标记的XML文件XSLT的xsl:分析字符串和正则表达式

<xml> 
<foo> 
    <id>1</id> 
    <description>This is section 1, this is section 1 or 2, this is section 1 and 2</description> 
</foo> 
</xml> 

现在文件我必须找到一个模式“第1节”,“第1节或第2节”和“第1节和第2节”,并在匹配单词周围加上“标记。

我写了XSLT是这样的:

<xsl:template match="text()"> 

<xsl:analyze-string select="." regex="section\s\d+|section\s\d+\s+or\s+\d|section\s\d+\s+and\s+\d"> 
    <xsl:matching-substring> 
    <xsl:if test="matches(.,'section\s\d+')" > 
     <xsl:text>"</xsl:text> 
     <xsl:value-of select="."/>  
     <xsl:text>"</xsl:text>  
    </xsl:if> 
    <xsl:if test="matches(.,'section\s\d+\s+or\s+\d')" > 
     <xsl:text>"</xsl:text> 
     <xsl:value-of select="."/>  
     <xsl:text>"</xsl:text>  
    </xsl:if> 
    <xsl:if test="matches(.,'section\s\d+\s+and\s+\d')" > 
     <xsl:text>"</xsl:text> 
     <xsl:value-of select="."/>  
     <xsl:text>"</xsl:text>  
    </xsl:if> 
    </xsl:matching-substring> 
    <xsl:non-matching-substring> 
    <xsl:value-of select="current()"/> 
    </xsl:non-matching-substring> 
</xsl:analyze-string> 
</xsl:template> 

我这里面临的问题是,模式“部分1”中的所有其他模式相匹配,以及,所以我没有得到期望的结果

上述变换结果是

<xml> 
    <foo> 
     <id>1</id> 
     <description>This is "section 1", this is "section 1" or 2, this is "section 1" and 2</description> 
    </foo> 
</xml> 

其中,因为我想此输出。

<xml> 
    <foo> 
    <id>1</id> 
    <description>This is "section 1", this is "section 1 or 2", this is "section 1 and 2"</description> 
    </foo> 
</xml> 

任何想法如何实现它...并获得渴望的结果。

谢谢。

回答

3

这似乎在你输入的工作:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:template match="*"> 
    <xsl:copy> 
    <xsl:apply-templates/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="text()"> 
    <xsl:analyze-string select="." regex="section\s+\d+(\s+(or|and)\s+\d+)?"> 
    <xsl:matching-substring> 
    <xsl:text>"</xsl:text> 
    <xsl:value-of select="."/>  
    <xsl:text>"</xsl:text>  
    </xsl:matching-substring> 
    <xsl:non-matching-substring> 
    <xsl:value-of select="current()"/> 
    </xsl:non-matching-substring> 
    </xsl:analyze-string> 
</xsl:template> 

</xsl:stylesheet> 

但如果你只是产生一个字符串不是元素,xsl:anayze-string比你更需要的,这将产生相同的结果:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:template match="*"> 
    <xsl:copy> 
    <xsl:apply-templates/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="text()"> 
    <xsl:value-of select="replace(.,'section\s+\d+(\s+(or|and)\s+\d+)?','&quot;$0&quot;')"/> 
</xsl:template> 

</xsl:stylesheet> 
+1

感谢大卫,它完美运作。只是想知道currenlty它仅限于“第1或第2节”,是否可以使它成为通用的,例如它应该选择“第1节或第2节或第3节”等。 – atif 2012-03-29 21:16:05

+1

是的,只是改变?到一个*,也许改变(或|和)到(或|和|,),所以1,2或3应该工作以及(如果它可以接受和upvote你知道:-) – 2012-03-29 21:31:02

-1

一个快速但不雅的答案是让测试匹配(。,'section \ s \ d +')而不是(匹配(。,'section \ s \ d + \ s +或\ s + \ d'))或者某些