【问题标题】:XSLT replace remove html tagsXSLT 替换删除 html 标记
【发布时间】:2016-11-02 01:42:51
【问题描述】:

为什么replace()函数会删除我变量的html标签?

我有两个变量:

    <xsl:variable name="content1">
        <xsl:apply-templates select="." mode="my-mode">
        </xsl:apply-templates>
    </xsl:variable>
    <xsl:variable name="content2">
        <xsl:copy-of select="$content1, 'a', 'b')" />
    </xsl:variable>

$content1 有 html 标签,$content2 没有,为什么?

【问题讨论】:

  • replace 是一个字符串函数,它需要一个字符串作为第一个参数。如果您将节点作为第一个参数传入,它将获取该节点的字符串值并使用它。因此,例如,&lt;content&gt;&lt;a&gt;hello&lt;/a&gt; &lt;b&gt;world&lt;/b&gt;&lt;/content&gt; 的字符串值就是“hello world”,这就是replace 的作用。

标签: java html xml xslt


【解决方案1】:

当一个函数被定义为对一个字符串进行操作,并且你向它传递一个节点时,它会“原子化”节点(提取其内容)以创建函数所需的字符串。这将删除有关节点的其他信息,例如其名称。 (请注意,在将源文档解析为节点树时,标签本身已被删除。)

我猜你可能打算写

<xsl:variable name="content2">
    <xsl:copy-of select="replace($content1, 'a', 'b')" />
</xsl:variable>

注意,最好写成

<xsl:variable name="content2" select="replace($content1, 'a', 'b')"/>

避免从字符串到文本节点再转换回字符串的重复转换成本。

如果不确切知道您的源文档是什么,就很难确切地建议您应该如何编写此代码。如果 $content 是一个简单的文本内容没有属性的元素,那么最简单的可能是

<xsl:variable name="content2">
    <xsl:apply-templates select="$content1" mode="replace"/>
</xsl:variable>

<xsl:template match="*" mode="replace">
  <xsl:copy>
    <xsl:value-of select="replace(., 'a', 'b')" />
  </xsl:copy>
</xsl:template>

【讨论】:

  • 谢谢。 content1 实际上是一个 HTML 节点,我想将它打印到一个 javascript 变量中(例如 var myContent = '&lt;xsl:value-of select="replace(., 'a', 'b')" /&gt;';)。我还需要做一些文本替换,不仅在文本上,而且在 HTML 的属性上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
相关资源
最近更新 更多