XSLT:用''替换单引号

sto*_*ofl 3 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>
Run Code Online (Sandbox Code Playgroud)

如果我现在有一个模板:

<foo bar="test'xyz"/>
Run Code Online (Sandbox Code Playgroud)

这会产生:

<?php $this->doSomething('test'xyz');?>
Run Code Online (Sandbox Code Playgroud)

我现在想要实现的目标如下:

<?php $this->doSomething('test\'xyz');?>
Run Code Online (Sandbox Code Playgroud)

所以我想用''替换所有单引号

Mad*_*sen 6

使用递归模板进行查找/替换:

<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>
Run Code Online (Sandbox Code Playgroud)

适用于您的示例:

   <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>
Run Code Online (Sandbox Code Playgroud)

注意:

  1. 采用<xsl:text>显式定义用于输出文本,而不必担心文本和模板调用之间的空白.
  2. 使用单引号括起replacewith参数的select语句,以便使用双引号来表示包含单引号的文本语句
  3. 使用&apos;单引号的实体引用(又名撇号)