2016-05-15 109 views
1

我想用xslt 1.0實現查找和替換字符串。 問題是,我不得不更換不同值的多個字符串。例如,我輸入的XML是如下XSLT字符串替換,多個字符串

<process xmlns:client="http://xmlns.oracle.com/ErrorHandler" xmlns="http://xmlns.oracle.com/ErrorHandler"> 
    <client:result>The city name is $key1$ and Country name is $key2$ </client:result> 
</process> 

結果應該是從

<process xmlns:client="http://xmlns.oracle.com/ErrorHandler" xmlns="http://xmlns.oracle.com/ErrorHandler"> 
    <client:result>The city name is London and Country name is England </client:result> 
</process> 

$ key1的$ $和$ KEY2輸入的字符串應該被倫敦和英格蘭取代。 我發現了很多例子來查找和替換單個字符串,但我不知道如何替換具有不同值的多個字符串。 任何建議嗎?

在此先感謝

+1

在這裏看到一個可能的方法:http://stackoverflow.com/questions/33527077/change-html-dynamically-thru-xsl/33529970#33529970 –

回答

1

這將是容易得多,如果你可以使用XSLT 2.0或更高版本。這可能是這麼簡單:

replace(replace(., '\$key1\$', 'London'), '\$key2\$', 'England') 

但是,如果你被卡住XSLT 1.0,你可以use a recursive template to perform the replace,並調用它的每個要替換(使用以前調用作爲輸入的產品的令牌到下一個):

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:client="http://xmlns.oracle.com/ErrorHandler" 
    version="1.0"> 

    <xsl:template name="replace-string"> 
     <xsl:param name="text"/> 
     <xsl:param name="replace"/> 
     <xsl:param name="with"/> 
     <xsl:choose> 
      <xsl:when test="contains($text,$replace)"> 
       <xsl:value-of select="substring-before($text,$replace)"/> 
       <xsl:value-of select="$with"/> 
       <xsl:call-template name="replace-string"> 
        <xsl:with-param name="text" 
         select="substring-after($text,$replace)"/> 
        <xsl:with-param name="replace" select="$replace"/> 
        <xsl:with-param name="with" select="$with"/> 
       </xsl:call-template> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:value-of select="$text"/> 
      </xsl:otherwise> 
     </xsl:choose> 
    </xsl:template> 

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

    <xsl:template match="client:result"> 
     <xsl:variable name="orig" select="string(.)"/> 
     <xsl:variable name="key1"> 
      <xsl:call-template name="replace-string"> 
       <xsl:with-param name="text" select="$orig"/> 
       <xsl:with-param name="replace" select="'$key1$'"/> 
       <xsl:with-param name="with" select="'London'"/> 
      </xsl:call-template> 
     </xsl:variable> 
     <xsl:variable name="key2"> 
      <xsl:call-template name="replace-string"> 
       <xsl:with-param name="text" select="$key1"/> 
       <xsl:with-param name="replace" select="'$key2$'"/> 
       <xsl:with-param name="with" select="'England'"/> 
      </xsl:call-template> 
     </xsl:variable> 

     <xsl:copy> 
      <xsl:value-of select="$key2"/> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 
+0

非常感謝你 –