2016-09-22 35 views
0

我想要替換包含混合元素的元素中的字符串,但作爲XSLT新手,我不知道如何去做。我需要使用XSLT 1.0,並且不確定在XSLT 1.0中用包含混合元素的元素值替換字符串是否可能或合法。我沒有包含實際的xml和xslt文件,因爲它們太大而無法發佈,所以我想出了一些我正在嘗試完成的示例。XSLT 1.0:搜索和替換混合內容

這裏是我試圖改變一個示例XML文件:

<?xml version="1.0"?> 
<test> 
    <testing>The author named "<sub name="bob"/>" who wrote 
      <book name="Over the river" /> is STATUS. 
    </testing> 
</test> 

這裏是我的例子XSLT文件:

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xhtml="http://www.w3.org/1999/xhtml" > 

<xsl:template name="find-and-replace"> 
    <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="find-and-replace"> 
     <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="testing"> 
    <xsl:element name="testing"> 
    <xsl:call-template name="find-and-replace"> 
     <xsl:with-param name="text" select="."/> 
     <xsl:with-param name="replace" select="'STATUS'"/> 
     <xsl:with-param name="with" select="'LIVING'"/> 
    </xsl:call-template> 
    </xsl:element> 
</xsl:template> 

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

</xsl:stylesheet> 

轉化的示例XML文件是這樣的:

<?xml version="1.0"?> 
<test> 
    <testing>The author named "" who wrote is LIVING. 
    </testing> 
</test> 

有意義select="."不輸出subbook節點像普通文本。我想對於轉換示例XML文件看起來像這樣:

<?xml version="1.0"?> 
<test> 
    <testing>The author named "<sub name="bob"/>" who wrote <book name="Over the river" /> is LIVING. 
    </testing> 
</test> 

這甚至可能與XSLT 1.0?如果是這樣,我該如何做到這一點?

謝謝你的理解和你的提示!

回答

0

變化

<xsl:template match="testing"> 
    <xsl:element name="testing"> 
    <xsl:call-template name="find-and-replace"> 
     <xsl:with-param name="text" select="."/> 
     <xsl:with-param name="replace" select="'STATUS'"/> 
     <xsl:with-param name="with" select="'LIVING'"/> 
    </xsl:call-template> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="testing/text()"> 
     <xsl:call-template name="find-and-replace"> 
      <xsl:with-param name="text" select="."/> 
      <xsl:with-param name="replace" select="'STATUS'"/> 
      <xsl:with-param name="with" select="'LIVING'"/> 
     </xsl:call-template> 
</xsl:template> 
+0

,完美的工作!謝謝! – User12