tags:

views:

82

answers:

2

I have the following XML

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

and want to convert into

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

I try this xslt, only can ge the text inside title tag, how can I also convert the highlight tag?

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

Use xsl:copy-of instead of xsl:value-of if you want a full copy of the node and all of its children:

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

But for what you are trying to do, I would create one template for the title element and one for the highlight element:

<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>
Oded
thanks, how how could I convert <highlight> tag into <span class="hightlight"> in copy-of?
cc96ai
@cc96ai - answer updated
Oded
<xsl:apply-templates select="title" /> only execute title template, it doesn't run highlight template. how could it convert highlight tag and pass back to title template? thanks.
cc96ai
@cc96ai - you need to use <xsl:apply-templates /> without a `select`.
Oded
without select, it is same, it executes title template only.if I removed title template, then it will execute the highlight template, how can it execute both?
cc96ai
+3  A: 
<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>

or, if you want, collapse it into a single template:

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

Key point is the <xsl:apply-templates /> - it runs all child nodes of the current node through the appropriate templates. In the upper variant, the appropriate templates are separate, in the lower variant the one template is called recursively.

There is a default rule defined in XSLT that copies text nodes. All text is run through this rule by <apply-templates>, so text nodes appear in the output autmatically.

Tomalak