2016-04-30 72 views
2

我有這樣的X XML識別模式替換文本節點,XSLT - 通過使用正則表達式

<doc> 
<p>ABC Number 132, Decimal 321, AAB Double 983 DEF GHI 432 JKL</p> 
</doc> 

什麼如果,「小數」,「雙師型」後面加一個空格我的目標「號」(」' )後跟一個數字,那麼中間的空格值應該被*字符替換。

所以輸出應該是,

<doc> 
    <p>ABC Number*132, Decimal*321, AAB Double*983 DEF GHI 432 JKL</p> 
</doc> 

我有以下的xsl此,

<xsl:template match="p"> 
     <xsl:analyze-string select="text()" regex="(Number/s/d)|(Decimal/s/d)|(Double/s/d)"> 
      <xsl:matching-substring> 
       <xsl:choose> 
        <xsl:when test="regex-group(1)"> 
         <xsl:value-of select="'Number*'"/> 
        </xsl:when> 
        <xsl:when test="regex-group(2)"> 
         <xsl:value-of select="'Decimal*'"/> 
        </xsl:when> 
        <xsl:when test="regex-group(3)"> 
         <xsl:value-of select="'Double*'"/> 
        </xsl:when> 
       </xsl:choose> 
      </xsl:matching-substring> 

      <xsl:non-matching-substring> 
       <xsl:value-of select="."/> 
      </xsl:non-matching-substring> 
     </xsl:analyze-string> 
    </xsl:template> 

但它不返回正確的結果..

任何建議,我怎麼能修改我的代碼以獲得正確的輸出?

+0

它返回什麼結果?總是告訴我們什麼不起作用。 「它不工作」是不夠的。 –

回答

4

你的正則表達式的主要問題是,你試圖匹配空間和數字與/s/d

它應該是\s\d

但是,即使您修復此問題,您仍然會丟失數字,因爲您沒有捕獲它。

你也失去了p元素。

我建議稍微簡單的正則表達式,並添加xsl:copy保持p ...

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output indent="yes"/> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="p"> 
    <xsl:copy> 
     <xsl:analyze-string select="." regex="(Number|Decimal|Double)\s(\d)"> 
     <xsl:matching-substring> 
      <xsl:value-of select="concat(regex-group(1),'*',regex-group(2))"/> 
     </xsl:matching-substring> 
     <xsl:non-matching-substring> 
      <xsl:value-of select="."/> 
     </xsl:non-matching-substring> 
     </xsl:analyze-string>  
    </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 

輸出

<doc> 
    <p>ABC Number*132, Decimal*321, AAB Double*983 DEF GHI 432 JKL</p> 
</doc> 
2

簡單多了和更短的

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

    <xsl:template match="node()|@*"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@*"/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="p/text()"> 
    <xsl:value-of select="replace(., '(Number|Decimal|Double) (\d+)', '$1*$2')"/> 
    </xsl:template> 
</xsl:stylesheet>