Search code examples
xmlxsltxsl-fo

XSL: How to get all textpieces, keep the order and apply certain templates within


following code:

<elem1> This is an example text
<elem2> and i want to select all of this
<elem3> and apply a template on elem3 </elem3>
<elem3> so it gets bold </elem3>
exampletext </elem2>
exampletext  </elem1>

The output should look like:

This is an example text and i want to select all of this <b>and apply a template on elem3</b><b> so it gets bold </b> exampletext exampletext 

How can I do this with xsl? If I use 'text()' or select'.' while looping through every element with for-each select="*" I get some of the text many times. How do I archive the outcome I wrote earlier? Even if I do a template for every element I don't know how to get the text only of this node and not of the child. And it should also stay in the same order, so I want the part of text before I enter a child node and so on...

It may be a dumb question, but im new and im desperate about that :/


Solution

  • Just use XSLT's default recursive processing model. For example, the following stylesheet:

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="elem3">
        <b>
            <xsl:apply-templates/>
        </b>
    </xsl:template>
    
    </xsl:stylesheet>
    

    will copy all text nodes (using the built-in template rules) and add a <b> wrapper around those contained in elem3 elements, to return:

    <?xml version="1.0" encoding="UTF-8"?>
     This is an example text
     and i want to select all of this
    <b> and apply a template on elem3 </b><b> so it gets bold </b>
    exampletext 
    exampletext  
    

    If you prefer, you could add:

    <xsl:template match="text()">
       <xsl:value-of select="normalize-space()" />
    </xsl:template>
    

    and get:

    <?xml version="1.0" encoding="UTF-8"?>
    This is an example textand i want to select all of this<b>and apply a template on elem3</b><b>so it gets bold</b>exampletextexampletext