XSLT 1.0:搜索并替换混合内容

时间:2016-09-22 03:38:07

标签: xslt-1.0

我正在尝试替换包含混合元素的元素中的字符串,但作为XSLT新手,我不知道该怎么做。我需要使用XSLT 1.0,并且不确定在XSLT 1.0中使用包含混合元素的元素值替换字符串是否可行或合法。我没有包含实际的xml和xslt文件,因为它们太大而无法发布,所以我想出了一些我想要完成的例子。

以下是我尝试转换的示例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甚至可以实现这一点吗?如果是这样,我怎么能做到这一点?

感谢您的理解和提示!

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>