terça-feira, 8 de abril de 2008

XSLT: Uma fonte, várias saídas

Se tivermos um XML, poderemos utilizar do XSL Transformations(XSLT) para gerar várias saídas diferentes. Ou seja, podemos ter um XML e utilizar um XSLT para gerar um XML em outra estrutura, gerar um HTML/XHTML ou um arquivo texto.

Para quem trabalhou com o antigo ASP, JSP ou PHP a idéia de usarmos tags especiais lembra. No caso de XSLT, temos várias tags para fazer ifs, for, definir atributos e por aí vai.

Isto nos dá várias possibilidades, vejamos o código abaixo que transforma um XML numa saída HTML. Veja:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="oimundo.xslt"?>
<root>
<mensagem>
<
texto>Oi Mundo</texto>
<
sites>
<
siteId>00001</siteId>
<
siteId>00002</siteId>
</
sites>
</mensagem>
<
sites>
<
site>
<
id>00001</id>
<
descricao>http://aplicacoesweb.blogspot.com</descricao>
</
site>
<
site>
<
id>00002</id>
<descricao>http://silverlightpt.blogspot.com</descricao>
</
site>
</sites>
</root>

Código 1 : XML


<?xmlng="" style="font-size: 85%; color: #0000ff"> version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
<html>
<head>
<style>

body { font-family:verdana; }

</
style>
</
head>
<
body>
<
xsl:apply-templates select="mensagem" />
</
body>
</
html>

</xsl:template>

<xsl:template match="mensagem"> <h1> <xsl:value-of select="texto"/> </h1>

<h2>Sites</h2>
<table style="width:100%" border="1">
<
tr>
<th style="width:100%">
Url </th>
</
tr>
<xsl:for-each select="sites/siteId">
<xsl:variable name="siteId" select="text()" />
<tr>
<td>
<
a>
<
xsl:attribute name="href">
<
xsl:value-of select="/root/sites/site[id=$siteId]/descricao"/>
</
xsl:attribute>
<xsl:value-of select="/root/sites/site[id=$siteId]/descricao"/>
</
a>
</
td>
</
tr>
</xsl:for-each>

</table>

<xsl:template>

</xsl:stylesheet>


Código 2 : XSLT




Imagem 1 : Resultado visualizado no navegador

Para fazer o exemplo, salve o código 1 no arquivo oimundo.xml e o código 2 no
arquivo oimundo.xslt, ambos no mesmo diretórios. Após isto abra o arquivo
oimundo.xml no navegador.


Referências:

http://www.w3.org/TR/xslt
http://www.w3schools.com/XSL/el_attribute.asp