Transforming XML data to another format

Here is a quick start tutorial on how to transform XML data to another XML document or any other format.

Main components or actors for achieving this:
  1. XSL Stylesheet
  2. XML document (input data)
  3. JAXP Transform libraries
JAXP stands for Java API for XML Processing. JAXP lets you validate, parse and transform XML using several different APIs. JAXP is vendor neutral and easy to incorporate in to your project.




JAXP’s interpreting implementation of XSLT is Xalan. JAXP’s transformation libraries are found under javax.xml.transform package.

javax.xml.transform:
  • Defines basic set of interfaces for XSLT processors.
  • Defines factory class you use to get a Transformer object.
  • You can configure the transformer with input and output objects, and invoke its transform() method to make the actual transformation.
You can define 3 different types of Source and Result:
  • DOM (javax.xml.transform.dom) – uses DOM.
  • SAX (javax.xml.transform.sax) – uses SAX event generator.
  • Stream (javax.xml.transform.stream) – uses I/O stream.
Code snippet:


try {

TransformerFactory factory = TransformerFactory.newInstance();

// Specify XSL document
Transformer transformer = factory.newTransformer(new StreamSource(xsl-document));

// Specify XML Input
StreamSource xmlsource = new StreamSource(xml-input);

// Specify Target Output
StreamResult output = new StreamResult(System.out);

// Do the magic
transformer.transform(xmlsource, output);

} catch (TransformerException) {
// Handle Exception Code
}

No comments:

Post a Comment

Followers