我正在使用 XSLT 将 XML 转换为 html/php 文件。在此 XSLT 中,我用 php 代码替换了一些标签,现在我必须将属性值传递到该 php 代码中。我现在的问题是我必须用反斜杠转义单引号才能让它工作。这对 XSLT 来说可能吗?
例子:
<xsl:template match="foo">
<xsl:processing-instruction name="php">$this->doSomething('<xsl:value-of select="./@bar" />');</xsl:processing-instruction>
</xsl:template>
如果我现在有一个模板:
<foo bar="test'xyz"/>
这会产生:
<?php $this->doSomething('test'xyz');?>
我现在想要实现的是:
<?php $this->doSomething('test\'xyz');?>
所以我想用\' 替换所有单引号
最佳答案
使用 recursive template进行查找/替换:
<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>
注意:
- 使用
<xsl:text>
明确定义用于输出的文本,而不必担心该文本和模板调用之间的空格。 - 使用单引号将 replace 和 with 参数的选择语句括起来,以便使用双引号指示包含单个文本语句引用
- 实体引用的使用
'
对于单引号(又名撇号)
关于php - XSLT:用\'替换单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7711654/