XSL Processor in Java


The XSLT (eXtensible Stylesheet Language Transformations) Processor is a piece of software that processes XML documents and applies transformation rules to create new XML documents or other output formats like HTML, plain text, or PDF. With the use of templates, element selection and manipulation, and operations like sorting and filtering, developers can build rules for converting XML documents into various formats using the powerful language known as XSLT.

An XSL processor that can be used to implement XSLT transformations is built into the popular programming language Java for processing XML documents. Developers can read, parse, and process XML documents, apply XSLT transformations to create new documents; and carry out other XML-related actions using the Java XSL Processor.

Extensible Markup Language (XML) is a well-liked markup language that offers a structured approach to storing and transmitting data. Its platform-independent nature and readability to humans make it suitable for exchanging data among diverse systems. Nonetheless, to make the most of its potential, it necessitates a method to transform XML documents into different formats like plain text, PDF, or HTML. This situation can make use of XSL processors and the eXtensible Stylesheet Language (XSL). Java, a programming language that's widely recognized, will be our focus in this discussion about XSL processors. Here, we will find out how to change XML documents to a few different forms via XSL processors.

Algorithm for an XSL (eXtensible Stylesheet Language) Processor in Java

  • Load the XSL stylesheet and the XML input document.

  • Create a DOM (Document Object Model) tree from the input XML document.

  • Parse the XSL stylesheet into a DOM tree.

  • Beginning with the root element, navigate the input document's DOM tree.

  • For each component in the source document −

    • Verify the XSL stylesheet to see if there is a matching template rule.

    • Apply the corresponding transformation to the input element if a matching template rule is discovered.

    • Use the default template rule in the absence of a matching template rule.

  • If an XML, HTML, or text file is the desired output format, serialize the transformed DOM tree back into that document.

  • Finally, return the transformed output document or other desired output, such as a string representation or an output stream, to the calling code or client for further processing or presentation.

Different Approaches

Using an XSLT stylesheet and a Java XSLT processor to transform an XML document

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class XSLProcessorExample {

   public static void main(String[] args) {
      try {
         // Initialize input, XSL, and output files
         File inputFile = new File("input.xml");
         File xsltFile = new File("stylesheet.xsl");
         File outputFile = new File("output.xml");

         // Obtain a new TransformerFactory object
         TransformerFactory transformerFactory = TransformerFactory.newInstance();

         // Create a new Transformer object from the TransformerFactory, using the XSL stylesheet as input
         Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsltFile));

         // Call the transform method on the Transformer object, passing in the input and output files as StreamSource and StreamResult objects respectively
         transformer.transform(new StreamSource(inputFile), new StreamResult(outputFile));

         // Print a message to the console indicating the location of the output file
         System.out.println("XML transformation complete. Output written to: " + outputFile.getAbsolutePath());

        } catch (Exception e) {
         // Print any exceptions that occur during the transformation process
         e.printStackTrace();
      }
   }
}

First, the javax.xml.transform package's essential classes are imported. These classes are used to convert XML documents using XSLT. The javax.xml.transform package offers an API for converting XML files into several file types, including HTML, PDF, and plain text. It includes a factory class that generates transformer instances as well as classes that represent the source and output of a transformation.

A class called XSLProcessorExample is created, and it has a single main method that acts as the application's entry point. The primary approach carries out the subsequent steps −

  • This produces the first iterations of the input XML, XSL stylesheet, and output file File objects. The program's current working directory is where these files are thought to be located.

  • This obtains a fresh instance of a TransformerFactory-made item. This object is used to create transformer objects, which are in charge of performing XSLT transformations.

  • It then uses the TransformerFactory and the XSL stylesheet file as input to construct a new Transformer object. The StreamSource class is used to represent the XSL stylesheet file as a stream of XML data.

  • StreamSource and StreamResult objects are used to deliver the input XML file and the output file, respectively, to the Transformer object's transform function call. The XSLT transformation is carried out through the transform method, which then outputs the modified file.

  • It then gives the location of the output file as a message that is printed to the console. This will capture and print any exceptions that are encountered throughout the transformation process into the console.

    Overall, this program offers a straightforward method of how to carry out XSLT transforms in Java. For XSLT transformations, there are a lot more choices and configurations available, and more complicated transformations could need more setup and configuration.

Using the JAXP API to apply an XSL stylesheet to an XML document −

import javax.xml.transform.*;
import javax.xml.transform.stream.*;

public class XSLTProcessor {
  public static void main(String[] args) throws Exception {
   // Set up the input and output files
   Source xmlInput = new StreamSource("input.xml");
   Source xslInput = new StreamSource("stylesheet.xsl");
   Result output = new StreamResult("output.html");

   // Create a new transformer factory and a transformer instance
   TransformerFactory factory = TransformerFactory.newInstance();
   Transformer transformer = factory.newTransformer(xslInput);

   // Apply the transformation to the input file and save the output
   transformer.transform(xmlInput, output);
  }
}
  • We are first loading javax.xml.transform and javax.xml.transform.stream. With the help of these, the Java API for XML Processing (JAXP) library's essential classes may be imported.

  • Before creating a Result object for the output file, we first build Source objects for the input XML file, the XSL stylesheet file, and the output file using ‘new StreamSource()’ and ‘new StreamResult().

  • Then, using the XSL stylesheet as an argument to the newTransformer function, we construct a new TransformerFactory instance and a new Transformer object.

  • The transform method on the Transformer object is then called after submitting the input XML and the output Result object. This applies the XSL stylesheet to the XML document and saves the result to the specified file.

Conclusion

In conclusion, utilizing Java's XSL (eXtensible Stylesheet Language) processors can be a highly effective method for converting XML files into other file types like HTML, PDF, or text. A standardized and effective method for applying stylesheets created using XSLT (XSL Transformations) to XML documents is provided by XSL processors.

The widely used programming lasnguage Java provides a number of libraries and APIs that let programmers include XSL processors in their Java projects. Apache Xalan, Saxon, and XSLTC are a few of the frequently employed XSL processors in Java. For managing complicated XML documents, these processors offer a wealth of functionality, including support for the XPath and XSLT standards, extension functions, template matching, and more.

The use of XSL processors in Java allows developers to accomplish a number of goals. It will be simpler to maintain and update the stylesheets if, for instance, they can separate the presentation logic from the data logic. Large XML documents may be processed effectively thanks to the comprehensive error handling and performance optimizations offered by XSL processors. Additionally, XSL processors give programmers the ability to create dynamic content and alter the output format to suit certain needs.

Updated on: 18-Jul-2023

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements