本文介绍了XSLT:用 \' 替换单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 XSLT 将 XML 转换为 html/php 文件.在这个 XSLT 中,我用 php 代码替换了一些标签,现在我必须将属性值传递到该 php 代码中.我现在的问题是我必须用反斜杠转义单引号才能使其工作.这可以用 XSLT 实现吗.
I am using XSLT to transform a XML into a html/php file. In this XSLT I replace some tags by php code and now I have to pass attribute values into that php code. My problem now is that I have to escape single quotes with a backslash to get it work. Is this possible with XSLT.
示例:
<xsl:template match="foo">
<xsl:processing-instruction name="php">$this->doSomething('<xsl:value-of select="./@bar" />');</xsl:processing-instruction>
</xsl:template>
如果我现在有一个模板:
If I now had a template:
<foo bar="test'xyz"/>
这会产生:
<?php $this->doSomething('test'xyz');?>
我现在想要实现的是:
<?php $this->doSomething('test\'xyz');?>
所以我想用 \' 替换所有单引号
So I want to replace all single quotes by \'
推荐答案
使用 递归模板进行查找/替换:
Use a recursive template to do the find/replace:
<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="foo">
<xsl:processing-instruction name="php">
<xsl:text>$this->doSomething('</xsl:text>
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="./@bar"/>
<xsl:with-param name="replace" select='"'"' />
<xsl:with-param name="with" select='"\'"'/>
</xsl:call-template>
<xsl:text>');</xsl:text>
</xsl:processing-instruction>
</xsl:template>
注意:
- 使用
明确定义用于输出的文本,而不必担心该文本和模板调用之间的空白.
- 使用单引号将 replace 和 with 参数的 select 语句括起来,以便使用双引号来指示包含单个报价
- 将实体引用
'
用于单引号(又名撇号)
- The use of
<xsl:text>
to explicitly define text intended for the output, and not have to worry about whitespace between that text and template calls. - The use of single quotes to enclose the select statement for the replace and with parameters, in order to use double-quotes to indicate a text statement that contains a single quote
- The use of the entity reference
'
for the single quote (a.k.a. apostrophe)
这篇关于XSLT:用 \' 替换单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!