【发布时间】:2012-07-16 11:49:01
【问题描述】:
我需要在 xslt 中查找并替换一个实体。我需要在不使用模板匹配的情况下执行此操作。
假设我的 xml 是这样的,
<root>
<p>Master's</p>
<p><blockFixed type="quotation"><p>let's</p></blockFixed></p>
<p>student's<featureFixed id=1/></p>
<p><blockFixed type="quotation"><p>nurse's</p></blockFixed></p>
<p>Master's</p>
</root>
我需要将&apos; 更改为&rsquo; 所以输出应该是这样的,
<root>
<p>Master<apos>’</apos>s</p>
<p><blockFixed type="quotation"><p>let<apos>’</apos>s</p></blockFixed></p>
<p>student<apos>’</apos>s<featureFixed id=1/><\p>
<p><blockFixed type="quotation"><p>nurse<apos>’</apos>s</p></blockFixed></p>
<p>Master's</p>
</root>
我通过模板匹配p 使用替换方法,但之后我无法对blockfixed 等其他标签进行任何操作。所以请建议使用简单的 xslt 来执行此操作。
我使用了以下xslt,
<xsl:template match="p">
<xsl:copy>
<xsl:apply-templates select="current()/node()" mode="replace"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()" mode="replace">
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="."/>
<xsl:with-param name="from">'</xsl:with-param>
<xsl:with-param name="to" select="'’'"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="replace-string">
<xsl:param name="text"/>
<xsl:param name="from"/>
<xsl:param name="to"/>
<xsl:choose>
<xsl:when test="contains($text, $from)">
<xsl:variable name="before" select="substring-before($text, $from)"/>
<xsl:variable name="after" select="substring-after($text, $from)"/>
<xsl:variable name="prefix" select="concat($before, $to)"/>
<xsl:copy-of select="$before"/>
<Apos>
<xsl:copy-of select="$to"/>
</Apos>
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="$after"/>
<xsl:with-param name="from" select="$from"/>
<xsl:with-param name="to" select="$to"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
提前致谢。
【问题讨论】:
-
在没有模板匹配的 XSLT 中很少发生。为什么会有这个限制?然后,您说您正在使用模板匹配(匹配
p)。请详细说明。 -
除非您使用 DOE(禁用输出转义),否则这在 XSLT 1.0 中是不可能的——但此功能不是强制性的,并且并非所有 XSLT 1.0 处理器都实现了它。强烈推荐使用 XSLT 2.0。