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"?>
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
<price>10.90</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
<price>9.90</price>
        <year>1988</year>
    </cd>
....
</catalog>

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 =
    javax.xml.transform.TransformerFactory.newInstance();

    // Get the XML input document and the stylesheet
    javax.xml.transform.Source xmlSource =
    new javax.xml.transform.stream.StreamSource(inXMLFile);

    javax.xml.transform.Source xslSource =
    new javax.xml.transform.stream.StreamSource(inXSLFile);

    // Generate the transformer.
    javax.xml.transform.Transformer transformer =
    tFactory.newTransformer(xslSource);
    // Perform the transformation, sending the output to the response.
    transformer.transform(xmlSource,
    new javax.xml.transform.stream.StreamResult(outXMLFile));
}

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