php - XSLT:用\'替换单引号

标签 php xslt

我正在使用 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='"&apos;"' />
            <xsl:with-param name="with" select='"\&apos;"'/>
        </xsl:call-template>
        <xsl:text>');</xsl:text>
    </xsl:processing-instruction>
</xsl:template>

注意:

  1. 使用<xsl:text>明确定义用于输出的文本,而不必担心该文本和模板调用之间的空格。
  2. 使用单引号将 replacewith 参数的选择语句括起来,以便使用双引号指示包含单个文本语句引用
  3. 实体引用的使用&apos;对于单引号(又名撇号)

关于php - XSLT:用\'替换单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7711654/

相关文章:

xml - 为什么 XML 不显示在浏览器中,但在 XML Notepad 2007 (Microsoft) 中正确显示?

javascript - 当我处于 td 级别时,如何从 xsl html 表格行中提取数据?

xslt - XSL(T) 和 XPath 前同级不起作用

asp.net - 已编译的 XSLT 如何在 IIS 上工作?

php - 运行高负载 php 文件而不损害服务器性能

php - 带进度条的文件 uploader ?

php - WHILE 中的 IF 语句不起作用

java - Android:使用 xslt 转换 xml

javascript - PHP:在网络浏览器中输出 system/Shell_exec 命令输出

php - 如何实现富文本编辑器,并在文本内的任意位置添加可上传的图像