XSLT替换删除html标签

时间:2016-11-01 16:45:35

标签: java html xml xslt

为什么函数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没有,为什么?

1 个答案:

答案 0 :(得分:1)

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

我猜你可能打算写

<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>