2010-03-17 57 views
1

我有以下XMLXSLT如何在标签内转换标签?

<title> 
    This is a <highlight>test</highlight> thanks. 
</title> 

,想转换成

<span class="title">this is a <span class="highlight">test</span> thanks.</span> 

我试试这个XSLT,只能GE标题标签中的文本,我怎么也转换亮点标签?

<span class="title"><xsl:value-of select="title"/></span> 

回答

4
<xsl:template match="title"> 
    <span class="title"> 
    <xsl:apply-templates /> 
    </span> 
</xsl:template> 

<xsl:template match="highlight"> 
    <span class="highlight"> 
    <xsl:apply-templates /> 
    </span> 
</xsl:template> 

或者,如果你愿意,塌陷成一个模板:

<xsl:template match="title|highlight"> 
    <span class="{name()}"> 
    <xsl:apply-templates /> 
    </span> 
</xsl:template> 

关键点是<xsl:apply-templates /> - 它通过适当的模板来运行当前节点的所有子节点。在上面的变体中,适当的模板是分开的,在较低的变体中,一个模板是递归调用的。

在XSLT中定义了一个默认规则,用于复制文本节点。所有文本均通过<apply-templates>运行此规则,因此文本节点会自动显示在输出中。

2

使用xsl:copy-of而不是xsl:value-of如果你想节点的完整副本和所有子:

<span class="title"><xsl:copy-of select="title"/></span> 

但对于你正在尝试做的,我会创造了一个模板为highlight元件title元件和一个:

<xsl:template match="title"> 
    <span class="title"><xsl:value-of select="." /></span> 
    <xsl:apply-templates /> 
</xsl:template> 

<xsl:template match="highlight"> 
    <span class="highlight"><xsl:value-of select="." /></span> 
</xsl:template> 
+0

谢谢,我怎样才能将标记转换为的副本? – cc96ai 2010-03-17 18:01:42

+0

@ cc96ai - 回答更新 – Oded 2010-03-17 18:03:33

+0

只执行标题模板, 它不运行高亮模板。它如何转换高亮标记并传递回标题模板?谢谢。 – cc96ai 2010-03-17 18:18:37