[Java] -How to use XSLT files ?

What is it?

XSLT files are files that help us to transform XML files into other formats such as html for example to facilitate this conversion however is not much currently used in the market because usually XSLT files grow very fast getting difficult to maintain.

When I should it?

XSLT files can be useful when we want to get all the data from our sale and display in the browser to the user for example.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="sell">
        <h2>Sell</h2>
        <p>Payment: <xsl:value-of select="payment" /></p>
        <xsl:apply-templates select="products" />
    </xsl:template>

    <xsl:template match="products">
        <h3>Products</h3>
        <xsl:apply-templates select="product" />
    </xsl:template>

    <xsl:template match="product">
        <h1><xsl:value-of select="name" /></h1>
        <p><xsl:value-of select="price" /></p>
        <hr />
    </xsl:template>
</xsl:stylesheet>

Code Java to make this transformation:

TransformerFactory factory = TransformerFactory.newInstance();
// Get the file - Here you will put the path of your xsl
InputStream template = new FileInputStream("src/sellHtml.xsl");
StreamSource stylesheet = new StreamSource(template);
Transformer transformer = factory.newTransformer(stylesheet);
// Get the file - Here you will put the path of your xml
InputStream vendas = new FileInputStream("src/sell.xml"); 
StreamSource source = new StreamSource(sell); 
StreamResult result = new StreamResult("src/output.html"); 
transformer.transform(source, result);

Now, you will have a HTML file with all information that has in your XSL file.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s