Comment regrouper les éléments appartenant à un chapitre en utilisant XSLT ?
Eric van der Vlist,
Dyomedea (vdv@dyomedea.com).
mercredi 3 janvier 2001
Je voudrais regrouper les éléments appartenant à un même chapitre:
<html>
<body>
<h1>Chapitre 1.</h1>
<p>Paragraphe 1.1</p>
<p>Paragraphe 1.2</p>
<h1>Chapitre 2.</h1>
<p>Paragraphe 2.1</p>
<h1>Chapitre 3.</h1>
</body>
</html>
Pour cela, il faut travailler en "pas à pas", ce qui est possible mais quelque peu contre nature avec XSLT…
La transformation suivante:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="/">
<document>
<xsl:apply-templates select="/html/body/h1"/>
</document>
</xsl:template>
<xsl:template match="h1">
<chapitre>
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
<xsl:if test="name(following-sibling::*[1])!='h1'">
<xsl:apply-templates select="following-sibling::*[1]" mode="pas"/>
</xsl:if>
</chapitre>
</xsl:template>
<xsl:template match="h1" mode="pas"/>
<xsl:template match="*" mode="pas">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
<xsl:apply-templates select="following-sibling::*[1]" mode="pas"/>
</xsl:template>
</xsl:stylesheet>
Donnera le document:
<document>
<chapitre>
<h1>Chapitre 1.</h1>
<p>Paragraphe 1.1</p>
<p>Paragraphe 1.2</p>
</chapitre>
<chapitre>
<h1>Chapitre 2.</h1>
<p>Paragraphe 2.1</p>
</chapitre>
<chapitre>
<h1>Chapitre 3.</h1>
</chapitre>
</document>
Cette relative difficulté est une des raisons pour lesquelles on considère généralement que XSLT est mieux adaptée aux transformations de documents bien structurés vers des documents moins structurés que l'inverse.
[xml-tech] Structure plate vers arbre[xml-tech] Re: Structure plate vers arbre[xml-tech] Regroupement en XSLT[xml-tech] Re: Regroupement en XSLT[xml-tech] XSLT : Grouper une séquence[xml-tech] Re: XSLT : Grouper une séquence
Copyright 2001,
Eric van der Vlist.
|