为什么函数 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
没有,为什么?
最佳答案
当一个函数被定义为对字符串进行操作,并且您向它传递一个节点时,它会“原子化”该节点(提取其内容)以创建该函数所需的字符串。这会删除有关节点的其他信息,例如其名称。 (请注意,当源文档被解析为节点树时,标签本身已被删除。)
我猜你可能打算写
<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>
关于java - XSLT 替换删除 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40364609/