XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

48
XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale Laurea Magistrale in Informatica in Informatica

Transcript of XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

Page 1: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT (eXtensible Stylesheet

Language Transformation)

Laurea Magistrale Laurea Magistrale

in Informaticain Informatica

Page 2: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 2

CSS e XSL

CSS (Cascading Style Sheets) è un linguaggio puramente descrittivo. Assegna ai nodi del documento XML una caratterizzazione tipografica senza nessuna modifica strutturale o organizzativa

XSL (eXtensible Stylesheet Language), invece, permette sia caratterizzazione tipografica che riscrittura, ovvero la possibilità di organizzare il contenuto finale in maniera diversa dall'originale

Page 3: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 3

XSL e XSLT

XSLT (XSL Transformation) estende il concetto di foglio di stile fino a permettere la manipolazione della struttura stessa del documento

XSLT permette di trasformare un documento XML filtrandone i dati e riorganizzandoli in un’altra struttura XML, o persino in un semplice testo

XSLT possiede molte delle caratteristiche di un linguaggio di programmazione imperativo!

XSLT, inoltre, si basa su XPath

Page 4: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 4

Cosa è XSLT XSLT trasforma un

documento XML in altri documenti Usato principalmente per

ottenere un documento HTML

Trasformare significa analizzare il contenuto ed eseguire determinate azioni in funzione degli elementi trovati al suo interno

Per eseguire la trasformazione occorre un processore XSLTprocessore XSLT Msxml vers. 3.0 il

processore XSLT usato da IE5

Documento XML

Ecc…Documento

XMLDocumento

HTML

XSLXSL (eXXstensible SStyle LLanguage)

Specifica per la trasformazione e la formattazione dei documenti XML :

1.1. XSLTXSLT per trasformare

2.2. XSL-FOXSL-FO per formattare gli oggetti

Page 5: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 5

Struttura dati per animali in estinzione (animali.xml)

Italian

language

t ig re

n am e

cacciatori

th reat

distruzione ...

th reat th reat

th rea ts

w e ig h tle ng h tso u rcep ic tu reso tto spe c ie... .. . . .. . . .. . . ..so tto spe c ie

a n im a l

Italian

language

r inoce ron te

n am e

cacciatori

th reat

distruzione ...

th reat

th rea ts

w e ig h tle ng h tso u rcep ic tu reso tto spe c ie... .. . . .. . . .. . . ..so tto spe c ie

a n im a l

sp e cie _ es tinz io ne

Page 6: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 6

Processo di trasformazione

1. Il processore XSLT analizza il documento XML

2. Lo converte in un albero e ne identifica i nodi

3. Il processore esamina un foglio di stile XSLT per sapere come

trattare questi nodi

4. Le istruzioni sono contenute nei modelli (template)

5. Composizione dei template

1. Etichetta che identifica i nodi ai quali il template può essere applicato;

2. Istruzioni riguardanti la trasformazione che dovrebbe avere luogo

6. I dati trasformati vengono quindi visualizzati o salvati in un altro

file

Page 7: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 7

Primo foglio di stile XSLT (animali_01.xsl)

<?xml version="1.0"?> [1]

<xsl:stylesheet

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0"> [2]

<xsl:template match="/"> [3]

<html><head><title>Specie in via di estinzione</title></head><body bgcolor="yellow">

<p>Gli animali in via di estinzione subiscono numerose minacce. Per maggiori informazioni consulta <a href="http://www.worldwildlife.org/ species/species.cfm?"> World Wildlife Federation's</a>.

</p><hr/></body></html>

</xsl:template> [/3]

</xsl:stylesheet> [/2]

1. Ogni documento XSLT è un

documento XML e quindi deve

iniziare con una dichiarazione XML

standard

2. Elemento radice per il foglio di stile

che identifica il prefisso xsl

3. Template di massimo livello che

contiene

1. Valori letterali che rimangono

invariati nell’output (generalmente

tag html e caratteri)

2. Istruzioni XSLT che eseguono

l’output dei nodi del documento

sorgente o li elaborano

ulteriormente

Per utilizzare msxml di IE il documento XML deve avere nel prologo la PI

<?xml:stylesheet type = "text/xsl" href="animali_01.xsl"?>

Page 8: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 8

OUTPUT del contenuto di un nodo

Nella struttura dell’esempio <specie_estinzione><animal><name language="Italian">Tigre</name><name language="Latin">panthera tigris</name>

<threats>

<threat>cacciatori</threat>

Si voglia far apparire in output il valore dell’elemento name

<xsl:value-of select = <xsl:value-of select = “espressione”/>“espressione”/>

Dove espressione identifica l’insieme dei

nodi del documento XML sorgente il cui

contenuto deve essere inserito in questa

posizione.

<?xml version="1.0"?>

<xsl:stylesheet

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0">

<xsl:template match="/">

<html><head><title>Specie in via di estinzione</title></head><body bgcolor="yellow">

<p>Gli animali in via di estinzione subiscono numerose minacce. (esempio: <b>

<xsl:value-of select = "specie_estinzione/animal/name"/>

</b>)</p>

<p>Per maggiori informazioni consulta <a href="http://www.worldwildlife.org/ species/species.cfm?"> World Wildlife Federation's</a>.

</p><hr/></body></html>

</xsl:template>

</xsl:stylesheet>

<?xml version="1.0"?>

<xsl:stylesheet

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0">

<xsl:template match="/">

<html><head><title>Specie in via di estinzione</title></head><body bgcolor="yellow">

<p>Gli animali in via di estinzione subiscono numerose minacce. (esempio: <b>

<xsl:value-of select = "specie_estinzione/animal/name"/>

</b>)</p>

<p>Per maggiori informazioni consulta <a href="http://www.worldwildlife.org/ species/species.cfm?"> World Wildlife Federation's</a>.

</p><hr/></body></html>

</xsl:template>

</xsl:stylesheet>

(animali_02.xsl)

Page 9: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 9

ESERCITAZIONE

Modificare il documento xslt animali_02.xsl in modo che l’output appaia nalla seguente maniera :

Page 10: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 10

Creazione di regole template

Le regole dei template sono moduli che descrivono come eseguire l’output di una determinata porzione di XML

Sono costituite da tre parti:

1. Il tag di apertura che descrive a quale parte la regola deve essere applicata <xsl:template match=“…..”><xsl:template match=“…..”>

2. La parte centrale che dice cosa accade quando viene trovata una corrispondenza

3. Tag di chiusura che completa il template </xsl:template></xsl:template>

L’ordine dei template è del tutto irrilevante; l’importante è quando vengono richiamati

Template di massimo livello

match=“/”

Template che riguarda gli elementi animal

match=“specie_estinzione/animal”

Template che riguarda gli elementi name con

attributo language=“Italian”

Template che riguarda gli elementi name con

attributo language=“Latin”

Page 11: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 11

Applicazione di regole template

L’elemento xsl:apply-

template Cerca ed invoca la regola più

appropriata per ciascun nodo Decide quali nodi elaborare

esaminando la propria

espressione “select” Decide quali template

utilizzare esaminando i loro

pattern (“match”) E’ possibile utilizzare un

differente template per

ciascun nodo

<xsl:template match="/">

<html>

<head><title>Specie in via di estinzione</title></head>

<body bgcolor="yellow">

<p>Gli animali in via di estinzione subiscono numerose minacce.</p>

<p><b> I maggiori esempi sono rappresentati da :</b></p>

<xsl:apply-templates <xsl:apply-templates select="specie_estinzione/animal"/>select="specie_estinzione/animal"/>

<p>Per maggiori informazioni consulta <a href="http://www.worldwildlife.org/ species/species.cfm?"> World Wildlife Federation's</a>.

</p></body>

</html>

</xsl:template>

Page 12: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 12

animali_03.xsl

Template per elemento animal

<xsl:template match="animal">

<p align="center"> <font size="+3">

<xsl:apply-templates select="name"/>

</font></p><hr/>

</xsl:template>

Template per elemento name con attributo language=Italian

<xsl:template match="name[@language='Italian']">

<b> <xsl:value-of select="."/>: </b>

</xsl:template>

Template per elemento name con attributo language=Latin

<xsl:template match="name[@language='Latin']">

<i> <xsl:value-of select="."/> </i>

</xsl:template>

Page 13: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 13

Elaborazione di tutti i nodi di un dato insieme

Template per elementi animal

<xsl:template match="animal">

<p align="center"> <font size="+3">

<xsl:apply-templates select="name"/>

</font></p><hr/>

</xsl:template>

Template per elementi animal modificato

<xsl:template match="animal">

<p align="center"> <font size="+3">

<xsl:apply-templates select="name"/>

</font></p>

<table width="100%" border="2">

<xsl:for-each select="subspecies">

<tr>

<td><xsl:apply-templates select="name"/></td>

<td><xsl:value-of select="region"/></td>

</tr>

</xsl:for-each>

</table>

<hr/>

</xsl:template>

All’interno dell’istruzione

<xsl:for-each select=“……….”><xsl:for-each select=“……….”>

Si trova tutto ciò che deve accadere per ciascun nodo dell’insieme selezionato

Nel nostro caso per ogni sottospecie dell’elemento animal corrente

All’interno dell’istruzione

<xsl:for-each select=“……….”><xsl:for-each select=“……….”>

Si trova tutto ciò che deve accadere per ciascun nodo dell’insieme selezionato

Nel nostro caso per ogni sottospecie dell’elemento animal corrente

Page 14: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 14

animali_04.xsl

Page 15: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 15

Elaborazione condizionale

Si voglia far apparire nella

tabella precedente in luogo del

valore zero sulla popolazione la

stringa “ESTINTA”

</xsl:if test=“espressione”>

Espressione = condizione

Si specifica cosa deve accadere

se il test è vero

</xsl:if>

Avevo <td><xsl:value-of

select="population"/></td> Devo avere l’applicazione del

template “population” <td><xsl:apply-templates

select="population"/></td> Template “population”

<xsl:template match="population">

<xsl:value-of select="."/>

<xsl:if test=".=0">

<font color="red"> (ESTINTA) </font>

</xsl:if> </xsl:template>

Animali_05.xsl

Page 16: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 16

Aggiunta di scelte condizionali

In luogo dello 0 la parola “ESTINTA”

<xsl:template match="population"><xsl:choose>

<xsl:when test=".=0"><font color="red"> (ESTINTA) </font></xsl:when><xsl:otherwise><xsl:value-of select="."/></xsl:otherwise>

</xsl:choose></xsl:template>

animali_06.xsl

Page 17: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 17

Ordinamento dei nodi

Si voglia far apparire la tabella in ordine decrescente rispetto alla popolazione ed alla regione di ciascuna sottospecie

<xsl:template match="animal"><p align="center"> <font size="+3"><xsl:apply-templates select="name"/></font></p><table width="100%" border="2"><tr><th>Sottoscpecie</th><th>Regione</th><th>Popolazione</th></tr><xsl:for-each select="subspecies"><xsl:sort select="population" data-type="number" order="descending" /><xsl:sort select="region" data-type="text" order="ascending" />

<tr><td><xsl:apply-templates select="name"/></td><td><xsl:value-of select="region"/></td><td><xsl:apply-templates select="population"/></td></tr>

</xsl:for-each></table><hr/>

</xsl:template> animali_07.xsl

Page 18: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 18

All’interno di un elemento è possibile specificare degli attributi in maniera esplicita con il tag <xsl:attribute>

Dato il frammento

<persona id=”1678.1245” nome=”Mario Rossi”/>

e il template

<xsl:template match=“persona”> <A><xsl:attribute name=“HREF”> <xsl:value-of select=“@id”/>.html </xsl:attribute> <xsl:value-of select=“@nome”/></A>

</xsl:template>

ottengo il frammento

<A HREF=“1678.1245.html”>Mario Rossi</A>

Creazione di Attributi

Page 19: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 19

Generazione attributi

<img src=“nome_file” width=“ “ height=“ “> tag HTML

<xsl:template match="picture"><img><xsl:attribute name="src"><xsl:value-of select="./@filename"/></xsl:attribute><xsl:attribute name="width"><xsl:value-of select="./@x"/></xsl:attribute><xsl:attribute name="height"><xsl:value-of select="./@y"/></xsl:attribute></img></xsl:template>

animali_08.xsl

Page 20: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 20

I fogli di stile XSLT

Un foglio di stile XSL è composto sostanzialmente di template di costruzione, che permettono di riscrivere, modificandola, una selezione del documento XML d’origine nel documento destinazione

Ogni template individua un pattern da ricercare nel documento di partenza, e vi associa un blocco di elementi e testo da inserire nel documento di destinazione

Un template è indicato dall’elemento template<xsl:template match=pattern name=qname priority=number mode=qname > <!-- azione -->

</xsl:template>

The name attribute allows you to specify a name for a template, so that the template can be called later by the call-templates element

The match attribute is a very important attribute, because this is what will determine what component your template will be applied to in the XML document

Page 21: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 21

Address Book Example

<?xml version="1.0" encoding="UTF-8" ?>

- <address_book>

- <contact>

- <name>

<first>Jane</first>

<last>Doe</last>

</name>

- <address location="office">

<street>123 Fake Street</street>

<city>Springfield</city>

<state>IL</state>

<zip>49201</zip>

</address>

- <phone>

<number type="office">708-555-212</number>

<number type="mobile">708-855-4848</number>

<number type="fax">800-555-1212</number>

</phone>

<email>[email protected]</email>

</contact>

- <contact>

- <name>

<first>John</first>

<last>Smith</last>

</name>

- <address location="home">

<street>205 Peaceful Lane</street>

<city>Bloomington</city>

<state>IN</state>

<zip>47401</zip>

</address>

- <address location="office">

<street>8192 Busy Street</street>

<city>Bloomington</city>

<state>IN</state>

<zip>47408</zip>

</address>

- <phone>

<number type="office">812-555-1212</number>

<number type="mobile">812-855-4848</number>

<number type="fax">800-333-0999</number>

</phone>

<email>[email protected]</email>

<email>[email protected]</email>

</contact>

</address_book>

Page 22: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 22

Visualizzare l’intero contenuto del nostro esempio (address_book01.xsl)

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

JaneDoe123 Fake StreetSpringfieldIL49201708-555-1212708-855-4848800-555-1212jane@doe.comJohnSmith205 Peaceful LaneBloomingtonIN474018192 Busy StreetBloomingtonIN47408812-555-1212812-855-4848800-333-0999john@[email protected]

The apply-templates element is used to communicate to the processor that it should apply the template to the current selected node. In the previous example, the node is specified as "/," or the root element, so it contains the entire document.

Page 23: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 23

apply-templates (I)

Apply templates instruct the XSL processor to cycle through child elements of the selected node, which allows you to actually apply templates to more than just the root node of your document.

You can use either the apply-templates element with no selector, which will process the current node, or a select attribute to specify a node to apply the template to.

<xsl:template match="/"><xsl:apply-templates select="//address"/></xsl:template>

will first match the root node, and then apply the template to any address children because of the apply-templates element

Page 24: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 24

apply-templates (II)

For example, if we wanted to process the name elements, which are children of the contact element in our example, we could use

<xsl:template match="contact"><xsl:apply-templates select=".//name"/></xsl:template>

Result JaneDoeJohnSmith

Page 25: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 25

Value-of

The xsl:value-of element is used to insert the value of a component into the template.

The value-of element has a select attribute for specifying the element or attribute you want to select the value of, using an XPath expression.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" ><xsl:template match="contact"><html><xsl:value-of select="name/first" /> <xsl:value-of select="name/last" /></html></xsl:template></xsl:stylesheet>

You should also note that the template selects the contact node, which then becomes our context for locating the first and last elements, which are children of the name element.

Page 26: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 26

<xsl:value-of> crea un nodo di testo nell’albero di destinazione. L’attributo select (obbligatorio) contiene un espressione XPath che viene valutata e convertita in stringa. La stringa viene combinata con gli altri nodi di testo intorno L’uso tipico è per convertire markup in testo (ad esempio il valore di attributi in contenuto). Dato il frammento

<persona nome=”Mario” cognome=”Rossi”/> e il template

<xsl:template match=“persona”> <p><xsl:value-of select=“@nome”/> <xsl:text> </xsl:text> <xsl:value-of select=“@cognome”/></p></xsl:template>

ottengo il frammento<p>Mario Rossi</p>

Prelievo di valori

Page 27: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 27

Laddove non sia possibile usare del markup (ad esempio come valore di un attributo), è possibile usare le parentesi graffe, che hanno in questo senso lo stesso significato di <xsl:value-of> L’uso tipico è per convertire markup in altro markup (ad esempio il valore di un attributo nel nome di un tag). Dato il frammento

<persona nome=”Mario” cognome=”Rossi”/> e il template

<xsl:template match=“persona”> <a href=“mailto:{@nome}.{@cognome}@unicam.it”>

<xsl:value-of select=“@nome”/> </a></xsl:template>

ottengo il frammento<a href=“mailto:[email protected]”>Mario</a>

Uso delle graffe {}

Page 28: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 28

Se è necessario scrivere un elemento complesso o calcolato si usa <xsl:element> Ad esempio può servire per trasformare il valore di un attributo del documento di partenza nel nome di un tag nel documento destinazione Dato il frammento

<persona tipo=”studente” nome=”Mario Rossi”/> e il template

<xsl:template match=“persona”> <xsl:element name=“{@tipo}”> <xsl:value-of select=“@nome”/> </xsl:element></xsl:template>

ottengo il frammento<studente>Mario Rossi</studente>

Creazione di Elementi

Page 29: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 29

Creare Elementi ed Attributi

Da un

doc.XML

Ad un altroDoc XML

Page 30: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 30

Come avviene la trasformazione

<xsl:element name="{@title}">

È utilizzato per creare un elemento specificandone il nome nell’attributo name. ( espressione XPATH tra parentesi graffe

<xsl:attribute name="id">

<xsl:value-of select="id" />

</xsl:attribute>

Per creare l’attributo di un elemento (name = nome dell’attributo)

Page 31: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 31

Per applicare un comportamento specifico ad ognuno dei figli direttamente dentro al template si utilizza <xsl:for-each> Ad esempio il template: <xsl:template match=”BODY"> <xsl:apply-templates select=“H1”/></xsl:template><xsl:template match=”H1"> <P><xsl:value-of select=“.”/></P></xsl:template> viene più facilmente realizzato così: <xsl:template match=”BODY"> <xsl:for-each select=“H1”/> <P><xsl:value-of select=“.”/></P> </xsl:for-each></xsl:template>

Iterazione <xsl:for-each>

Page 32: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 32

<xsl:sort> ordina i nodi nella lista dei nodi correnti. Esso può essere soltanto figlio di un <xsl:apply-templates> o di un <xsl:for-each>

Gli elementi <xsl:sort> possono annidarsi Vari attributi:

Select: l’espressione in base alla quale fare il sort Data-type: il tipo di dato da ordinare (numero o

testo o altro) Order: il tipo ascendete o discendente di ordine Case-order: come trattare le maiuscole e le

minuscole

Ordinamento <xsl:sort>

Page 33: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 33

<xsl:template match=”lista"> <ul> <xsl:apply-templates select=“persona”> <xsl:sort select=”cognome"/> <xsl:sort select="nome"/> </xsl:apply-templates> </ul></xsl:template><xsl:template match=”persona"> <li> <xsl:value-of select=”nome"/> <xsl:text> </xsl:text> <xsl:value-of select=”cognome"/> </li></xsl:template>

Esempio di ordinamento

Page 34: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 34

Iterazione ed Ordinamento

USAGEXSLT

Page 35: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 35

<xsl:if> attiva condizionalmente dei comportamenti a seconda della verità di un XPath di test. Ad esempio il template seguente colora di giallo lo sfondo di una riga ogni due di una tabella HTML: <xsl:template match="item"> <tr> <xsl:if test="position() mod 2 = 0"> <xsl:attribute name="bgcolor"> yellow </xsl:attribute> </xsl:if> <xsl:apply-templates/> </tr></xsl:template>

Istruzioni condizionali <xsl:if>

Page 36: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 36

<xsl:choose> seleziona una tra molte alternative (la funzione di switch in java)<xsl:template match="item"> <tr> <xsl:choose> <xsl:when test="position() mod 3 = 0"> <xsl:attribute name="bgcolor">blue</xsl:attribute> </xsl:when> <xsl:when test="position() mod 3 = 1"> <xsl:attribute name="bgcolor">green</xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:attribute name="bgcolor">red</xsl:attribute> </xsl:otherwise> </xsl:choose> <xsl:apply-templates/> </tr> </xsl:template>

Istruzioni condizionali <xsl:choose>

Page 37: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 37

Istruzioni condizionali

conditional.xls

Page 38: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 38

Uso di variabili

E’ possibile definire delle variabili. Il valore di una variabile è quello di qualunque espressione.

La variabile può essere usata nel sottoalbero in cui è definita e deve essere richiamata con l’uso delle graffe e del segno $<xsl:variable name=”fs">12pt</xsl:variable><xsl:template match="para"> <fo:block font-size="{$fs}"> <xsl:apply-templates/> </fo:block></xsl:template>

Page 39: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 39

Merging E’ possibile porre frammenti di fogli di stile in file esterni. Con gli

elementi <xsl:import> e <xsl:include> è possibile inserire frammenti esterni con due significati leggermente diversi: <xsl:import> modifica, diminuendola, la priorità degli elementi inclusi, mentre <xsl:include> la mantiene

Metodi di output E’ possibile specificare che il documento risultante è XML, HTML o testo

con l’elemento <xsl:output>. Se l’output è HTML o testo, il processore è meno rigoroso nel valutare la buona forma del documento risultante

White space E’ possibile specificare quali elementi debbano preservare e quali

debbano collassare il white space con due appositi elementi, <xsl:preserve-space> e <xsl:strip-space>

Altri aspetti di XSLT

Page 40: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 40

Un altro esempio

Page 41: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 41

<?xml version="1.0"?> <book>

<chapter title="It begins"><para title="First paragraph"/><para title="2nd paragraph"/><para title="3rd paragraph"/>

</chapter><chapter title="The sequel">

<para title="Paragraph"/><para title="Yet another

paragraph"/></chapter>

</book>

Un esempio finale

Page 42: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 42

<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/">

<formatted-book><xsl:apply-templates select="book/chapter"/>

</formatted-book></xsl:template>….

</xsl:stylesheet>

Numerare i capitoli ed i paragrafi

...<xsl:template match="chapter">

Chapter <xsl:number format="I"/>:<xsl:value-of select="@title"/><xsl:apply-templates select="para"/>

</xsl:template>...

<xsl:template match="para">Paragraph <xsl:number count="para|chapter"

format="I.a"/>:<xsl:value-of select="@title"/>

</xsl:template>...

Page 43: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 43

...<xsl:template match="chapter">

Chapter <xsl:number format="I"/>:<xsl:value-of select="@title"/><xsl:apply-templates select="para"/>

</xsl:template>...

<xsl:template match="para">Paragraph <xsl:number count="para|chapter" format="I.a"/>:<xsl:value-of select="@title"/>

</xsl:template>...

Un esempio complesso

Page 44: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 44

<?xml version="1.0" encoding="utf-8"?><formatted-book>

Chapter I: It beginsParagraph I.a: First paragraphParagraph I.b: 2nd paragraphParagraph I.c: 3rd paragraph

Chapter II: The sequelParagraph II.a: ParagraphParagraph II.b: Yet another paragraph

</formatted-book>

Risultato

Page 45: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 45

XSLT consente di trasformare documenti XML in altri documenti con struttura diversa

Funziona con un meccanismo di pattern matching e si basa su Xpath

Implementa istruzioni condizionali e meccanismi di iterazione

Conclusione

Page 46: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 46

ESERCITAZIONE (menu.xml)

Page 47: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 47

Esercitazione (segue)

Scrivere un documento di stile XSL per ottenere il seguente risultato in HTML

Quindi ordinare il menu’ per prezzoScrivere un documento di stile XSL per ottenere il seguente risultato in HTML

Quindi ordinare il menu’ per prezzo

Page 48: XSLT (eXtensible Stylesheet Language Transformation) Laurea Magistrale in Informatica.

XSLT - eXtensible Stylesheet Language Transformation 48

Riferimenti

Deitel et al, XML Corso di programmazione, Apogeo

Chris Bates, XML in theory and Practice, Wiley

Extensible Stylesheet Language (XSL) Version 1.1 W3C Recommendation 05 December 2006 http://www.w3.org/TR/xsl/

W3Schools Online Web Tutorialshttp://www.w3schools.com/xsl/default.asp