Exemple : Un programme XSLT pour générer du HTML

ExempleFichier XML source

1
<?xml version="1.0" encoding="iso-8859-1"?>
2
<document titre="XSLT">
3
    
4
    <!--Première division-->
5
    
6
    <div titre="XSLT : Un besoin">
7
        <paragraphe>XML est un format de <important>représentation</important> de l'information.</paragraphe>
8
        <paragraphe>XML n'est pas un format de présentation.</paragraphe>
9
    </div>
10
    
11
    <!--Seconde division-->
12
    
13
    <div titre="XSLT : Un langage">
14
        <paragraphe>XSLT est un langage de <important>manipulation</important> de documents XML.</paragraphe>
15
        <paragraphe>XSLT est utilisé pour exporter une source XML sous un autre format, par exemple HTML.</paragraphe>
16
    </div>
17
</document>

ExempleFichier HTML cible souhaité

1
<html>
2
    
3
    <!--Head-->
4
    
5
    <head>
6
        <title>XSLT</title>
7
        <meta content="text/html" charset="iso-8859-1"/>
8
    </head>
9
    
10
    <!--Body-->
11
    
12
    <body>
13
        <h1>XSLT : Un besoin</h1>
14
        <p>XML est un format de <B>représentation</B> de l'information.</p>
15
        <p>XML n'est pas un format de présentation.</p>
16
        <h1>XSLT : Un langage</h1>
17
        <p>XSLT est un langage de <B>manipulation</B> de documents XML.</p>
18
        <p>XSLT est utilisé pour exporter une source XML sous un autre format, par exemple HTML</p>
19
    </body>
20
</html>

ExempleProgramme XSLT permettant la transformation

1
<?xml version="1.0" encoding="iso-8859-1"?>
2
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
3
    <xsl:output method="html" indent="yes" encoding="iso-8859-1"/>
4
5
    <!--1ère règle-->
6
7
    <xsl:template match="document">
8
        <html>
9
            <head>
10
                <title><xsl:value-of select="@titre"/></title>
11
                <meta content="text/html" charset="iso-8859-1"/>
12
            </head>
13
            <body>
14
                <xsl:apply-templates/>
15
            </body>
16
        </html>
17
    </xsl:template>
18
19
    <!--2nde règle-->
20
21
    <xsl:template match="div">
22
        <h1><xsl:value-of select="@titre"/></h1>
23
        <xsl:apply-templates/>
24
    </xsl:template>
25
26
    <!--3ème règle-->
27
28
    <xsl:template match="paragraphe">
29
        <p><xsl:apply-templates/></p>
30
    </xsl:template>
31
32
    <!--4ème règle-->
33
34
    <xsl:template match="important">
35
        <b><xsl:value-of select="."/></b>
36
    </xsl:template>
37
</xsl:stylesheet>