Uso de XML/XSLT

O que são XSL e XSLT?

            - XSL Transformations (XSLT): Uma linguagem para transformar XML.
            - XML Path Language (XPath): Uma linguagem para acessar e referir a partes de um documento XML.
            - XSL Formatting Objects (XSL-FO): Um vocabulário XML para especificar semântica de formatação.

XML e XSLT

<employee id="03432">
<name>Joe Shmo</name>
<title>Manager</title>
</employee>
<html>
<body>
<p><b>Joe Shmo</b>: Manager</p>
</body>
</html>
<xsl:stylesheet xmlns:xsl="">
<xsl:template match="/">
<html>
<body>
<p>
<b>
<xsl:value-of select="employee/name"/>
</b>
<xsl:text>: </xsl:text>
<xsl:value-of select="employee/title"/>
</p>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Comandos XSL básicos

Declaração de stylesheet

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
.
.
.
</xsl:stylesheet>
xmlns:java="http://xml.apache.org/xslt/java"

Casamento de padrões

<employee id="03432">
<name>Joe Shmo</name>
<title>Manager</title>
</employee>

Templates

<xsl:template match="nodename">
.
.
.
</xsl:template>
<xsl:apply-templates select="nodename"/>
<xsl:template match="name"
<xsl:value-of select="..."/>
</xsl:template>
<xsl:apply-templates select="name"/>

Comandos Lógicos

Comando Choose

<xsl:choose>
<xsl:when test="test situation">
stylesheet commands
</xsl:when>
<xsl:otherwise>
stylesheet commands
</xsl:otherwise>
</xsl:choose>
<xsl:otherwise/>

Command  if

<xls:if test="test situation">
...
</xsl:if>

Laços (comando for-each)

<xsl:for-each select="select statement">
...
</xsl:for-each>
<xsl:for-each select="employee[title='Manager']">
...
</xsl:for-each>

Variáveis

<xsl:variable name="count">atribuir valor a count aqui</xsl:variable>
<xsl:value-of select="$count"/>

Parâmetros

<xsl:param name="param1" select="'default value'"/>
 transformer.setParameter("param1", "default value");

Extensões

xmlns:java="http://xml.apache.org/xslt/java"

A API do XSLT da JRE

Class javax.xml.transform.Transformer

Class javax.xml.transform.Source

Class javax.xml.transform.Result

Um exemplo completo

<!ELEMENT orders (invoice)+>
<!ELEMENT invoice (item+,name,address+)>
<!ELEMENT item EMPTY>
<!ELEMENT name (#PCDATA)>
<!ELEMENT address (street, city, state, zip)>
<!ELEMENT street (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
<!ATTLIST invoice
number CDATA #REQUIRED
orderDate CDATA #REQUIRED
shipDate CDATA #REQUIRED>
<!ATTLIST item
part CDATA #REQUIRED
quantity CDATA #REQUIRED
cost CDATA #REQUIRED>
<!ATTLIST address
type (shipping|billing|other) #REQUIRED>

A View de transações

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:java="http://xml.apache.org/xslt/java"
exclude-result-prefixes="java"
version="1.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/orders">
<html>
<h1>Today's Invoices</h1>
<body>

<table border="on" cellspacing="1" cellpadding="5">
<thead>
<th>Invoice Number</th>
<th>Customer Name</th>
<th>Total Purchase</th>
</thead>
<tbody>
<xsl:for-each select="invoice">
<tr>
<td>
<xsl:element name="a">
<xsl:attribute name="href">

<xsl:text>xsl?stylesheet=detail&invoiceNum=</xsl:text>
<xsl:value-of select="@number"/>
</xsl:attribute>
<xsl:value-of select="@number"/>
</xsl:element>
</td>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="java:SumInvoice.summ(item)"/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

jw-0630-xsl1.gif (38573 bytes)

A view de detalhes

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:java="http://xml.apache.org/xslt/java"
exclude-result-prefixes="java"
version="1.0">
<xsl:param name="invoiceNum" select="string('none')"/>
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<html>
<body>
<table border="on" cellspacing="1" cellpadding="5">
<xsl:for-each select="orders/invoice[@number=$invoiceNum]">
<tr>
<td>
<table border="on" cellspacing="1" cellpadding="5">
<tr>
<td><b>Invoice Number:</b>
<xsl:value-of select="@number"/>
</td>
<td colspan="3"><xsl:value-of select="name"/></td>
</tr>
<tr>
<td colspan="4">
<xsl:apply-templates select="address"/>
</td>
</tr>
<tr>
<td colspan="4"><b>Items</b>
</td>
</tr>
<tr>
<td>Part</td>
<td>Quantity</td>
<td>Cost</td>
<td>Subtotal</td>
</tr>
<xsl:for-each select="item">
<tr>
<td><xsl:value-of select="@part"/></td>
<td><xsl:value-of select="@quantity"/></td>
<td><xsl:value-of select="@cost"/></td>
<td><xsl:value-of select="@quantity * @cost"/></td>
</tr>
</xsl:for-each>
<tr>
<td>
<b><xsl:text>Total</xsl:text></b>
</td>
<td>
<xsl:value-of select="sum(item/@quantity)"/>
</td>
<td>
<xsl:text></xsl:text>
</td>
<td>
<xsl:value-of select="java:SumInvoice.summ(item)"/>
</td>
</tr>
</table>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="address">
<table>
<tr>
<td><i>
<xsl:choose>
<xsl:when test="@type='shipping'">
<xsl:text>Shipping Address</xsl:text>
</xsl:when>
<xsl:when test="@type='billing'">
<xsl:text>Billing Address</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>Other Address</xsl:text>
</xsl:otherwise>
</xsl:choose></i>
</td>
</tr>
<tr>
<td colspan="4">
<xsl:value-of select="street"/>
</td>
</tr>
<tr>
<td colspan="4">
<xsl:value-of select="city"/>
<xsl:text> </xsl:text>
<xsl:value-of select="state"/>,
<xsl:value-of select="zip"/>
</td>
</tr>
</table>
</xsl:template>
</xsl:stylesheet>

jw-0630-xsl2.gif (47423 bytes)

O servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

public class XSLTServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException {
super.init(config);
}

// By redirecting our doGets to the doPost method we can have a stylesheet
// executed from a link
// ex. <a href="xsl?stylesheet=detail&invoiceNum=00002">00002
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

// Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = new PrintWriter(response.getOutputStream());

// Get the stylesheet selected by the user
String stylesheet = request.getParameter("stylesheet");

// Get the invoice number selected by the user, this is used only for
// certain
// stylesheets. If it is not present, the stylesheet won't use it.
String invoiceNum = request.getParameter("invoiceNum");

// Prepare FileReaders for the stylesheet and XML
FileReader xslReader = new FileReader(".\\javaworld\\xsl\\"
+ stylesheet + ".xsl");
FileReader xmlReader = new FileReader(".\\javaworld\\xml\\"
+ "invoice.xml");

response.setContentType("text/html");
try {
// Create an instance of a Transformer
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(new StreamSource(
xslReader));
// Set the invoice number parameter
trans.setParameter("invoiceNum", invoiceNum);

// Process the stylesheet, all the output will go straight
// out to the browser.
trans.transform(new StreamSource(xmlReader), new StreamResult(out));

} catch (TransformerConfigurationException e) {
out.write(e.getMessage());
e.printStackTrace(out);
} catch (TransformerException e) {
out.write(e.getMessage());
e.printStackTrace(out);
}
out.close();
}

// Get Servlet information
public String getServletInfo() {
return "XSLTServlet Information";
}
}

Quando usar XML/XSL/XSLT?

Vantagens

Desvantagens


Exemplos

Bibliografia