Archive for XSL

XSL basics

Posted in Computación with tags , , , on 12/March/2009 by Alex Pérez

I’ve been playing arround with XML and XSL transformations recently. XSL transformations may be very useful for:

  • transforming XML to XML with different structure.
  • converting XML to another well-known formats, as CSV or SQL. Then, you can pipe the output to another tools like awk/sqlplus or perform some complex querys in a RDBM.
  • simple ordering / extracting node-values from the XML. Do you want to extract only a numeric value from a SOAP-response, if there is no a “soap fault” element?

All the above possible usages make XSL a powerful tool to deal with XML specially when integrating applications.

So, lets see a sample XML file, storing some info about music CDs:

< ?xml version="1.0" encoding="ISO-8859-1"?>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <company>CBS Records</company>

And a Java class to perform XSL transformation:

public static void main(String[] args)
    throws FileNotFoundException,
    TransformerException {
    File inXMLFile = new File("input.xml");
    File inXSLFile = new File("transformation.xsl");
    File outXMLFile = new File("output.xml");

    javax.xml.transform.TransformerFactory tFactory =

    // Get the XML input document and the stylesheet
    javax.xml.transform.Source xmlSource =

    javax.xml.transform.Source xslSource =

    // Generate the transformer.
    javax.xml.transform.Transformer transformer =
    // Perform the transformation, sending the output to the response.

In the code above, there are three files:

  • input.xml: XML input file. We are using the CD catalog as input for our tests.
  • transformation.xsl: XSL sheet. The cornerstone of this test.
  • output.xml: The resulting XML from the XSL processing will be stored here. The output may no be an XML file (csv,txt,…) Continue reading