2012-03-29 51 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'))或者某些