如何复制任何类型的模板上下文元素的所有子节点

mon*_*nty 14 xslt xslt-1.0

我正在使用XSLT将XML转换为HTML.

我有以下XML结构:

<root>
    <element>
        <subelement>
            This is some html text which should be <span class="highlight">displayed highlighted</span>.
         </subelement>
    </element>
</root>
Run Code Online (Sandbox Code Playgroud)

我使用以下模板进行转换:

<xsl:template name="subelement">
  <xsl:value-of select="." />
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

不幸的是,我失去了<span>-tags.

有没有办法保留它们以便正确显示HTML(突出显示)?

Emi*_*ggi 34

获取当前匹配节点(包括文本节点)的所有内容的正确方法是:

    <xsl:template match="subelement">
       <xsl:copy-of select="node()"/>
    </xsl:template>
Run Code Online (Sandbox Code Playgroud)

这将复制一切后代.


Jon*_*ton 7

尝试使用<xsl:copy-of...而不是<xsl:value-of...例如:

<xsl:template name="subelement">
  <xsl:copy-of select="*" />
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

注意,*这将停止<subelement></subelement>输出到结果的位,而不是使用.包含<subelement></subelement>位的位.

例如,xsl样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:template match="root/element">
        <output>
            <xsl:apply-templates select="subelement"/>
        </output>
    </xsl:template>

    <xsl:template match="subelement">
        <xsl:copy-of select="*"/>
    </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

当应用于您的示例x​​ml文件时返回:

<?xml version="1.0" encoding="UTF-8"?>
<output>
    <span class="highlight">displayed highlighted</span>
</output>
Run Code Online (Sandbox Code Playgroud)