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
    <div titre="XSLT : Un besoin">
6
        <paragraphe>XML est un format de <important>représentation</important> de l'information.</paragraphe>
7
        <paragraphe>XML n'est pas un format de présentation.</paragraphe>
8
    </div>
9
    
10
    <!--Seconde division-->    
11
    <div titre="XSLT : Un langage">
12
        <paragraphe>XSLT est un langage de <important>manipulation</important> de documents XML.</paragraphe>
13
        <paragraphe>XSLT est utilisé pour exporter une source XML sous un autre format, par exemple HTML.</paragraphe>
14
    </div>
15
</document>

ExempleFichier HTML cible souhaité

1
<html>
2
    <head>
3
        <title>XSLT</title>
4
        <meta content="text/html" charset="iso-8859-1"/>
5
    </head>
6
    <body>
7
        <h1>XSLT : Un besoin</h1>
8
        <p>XML est un format de <B>représentation</B> de l'information.</p>
9
        <p>XML n'est pas un format de présentation.</p>
10
        <h1>XSLT : Un langage</h1>
11
        <p>XSLT est un langage de <B>manipulation</B> de documents XML.</p>
12
        <p>XSLT est utilisé pour exporter une source XML sous un autre format, par exemple HTML</p>
13
    </body>
14
</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
    <xsl:template match="document">
7
        <html>
8
            <head>
9
                <title><xsl:value-of select="@titre"/></title>
10
                <meta content="text/html" charset="iso-8859-1"/>
11
            </head>
12
            <body>
13
                <xsl:apply-templates/>
14
            </body>
15
        </html>
16
    </xsl:template>
17
18
    <!--2nde règle-->
19
    <xsl:template match="div">
20
        <h1><xsl:value-of select="@titre"/></h1>
21
        <xsl:apply-templates/>
22
    </xsl:template>
23
24
    <!--3ème règle-->
25
    <xsl:template match="paragraphe">
26
        <p><xsl:apply-templates/></p>
27
    </xsl:template>
28
29
    <!--4ème règle-->
30
    <xsl:template match="important">
31
        <b><xsl:value-of select="."/></b>
32
    </xsl:template>
33
</xsl:stylesheet>