chriisu
chriisu

Reputation: 13

XSL select text before and after element

I'm having problem selecting the correct part of text in XSL.

So my XML looks like this:

<paragraph>Some text and then <emphasis>emphasized text</emphasis> and
normal text. </paragraph>

I need to have output similar to:

<p>Some text and then <em>emphasized text</em> and normal text.</p>

I can't figure out a way to select the beginning text part and the ending text part seperately in order to handle the middle emphasis part on its own. What would be the correct approach here?

SOLUTION Ok, I found a solution with user3016153's help. I modified his suggestion to following:

<xsl:template match="paragraph">
    <p><xsl:apply-templates/></p>
</xsl:template>

<xsl:template match="emphasis">
    <em><xsl:value-of select="."/></em>
</xsl:template>

Upvotes: 1

Views: 1056

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116957

I can't figure out a way to select the beginning text part and the ending text part seperately in order to handle the middle emphasis part on its own.

You don't need to do that; you can let the stylesheet to handle them as they come:

<xsl:template match="paragraph">
    <p><xsl:apply-templates/></p>
</xsl:template>

<xsl:template match="emphasis">
    <em><xsl:apply-templates/></em>
</xsl:template>

EDIT
To clarify a point, this stylesheet:

<xsl:template match="*">
    <xsl:copy><xsl:apply-templates/></xsl:copy>
</xsl:template>

<xsl:template match="paragraph">
    <p><xsl:apply-templates/></p>
</xsl:template>

<xsl:template match="emphasis">
    <em><xsl:apply-templates/></em>
</xsl:template>

when applied to:

<paragraph>Plain text and then <emphasis>emphasized text with a <span>special part</span> in it</emphasis> and plain text again.</paragraph>

will produce:

<p>Plain text and then <em>emphasized text with a <span>special part</span> in it</em> and plain text again.</p>

However, if you change the last template to:

<xsl:template match="emphasis">
    <em><xsl:value-of select="."/></em>
</xsl:template>

you will get:

<p>Plain text and then <em>emphasized text with a special part in it</em> and plain text again.</p>

The point of this example is that you can't consider a template in isolation.

Upvotes: 2

Related Questions