Google

Aug 5, 2014

Java and XSLT tutorial to transform XML documents

Q. What is XSLT?
A. XSLT (Extensible Stylesheet Language Transformations) is a language for transforming XML documents into other XML, HTML, or plain text documents. XSLT is based on functional prgramming ideas, but it is not a full functional programming language as it lacks ability to treat functions as a first class data type.  XSLT supports XPath to query parts of XML. The major disadvantage of XSL is that it can be very verbose.

Step 1: The source XML

<Employee>
   <name type="first">Peter</name>
   <age>25</age>
</Employee>

Step 2: The style sheet (i.e XSL) that defines how to transform

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 <xsl:template match="/Employee">
    <HTML>
      <HEAD>
        <TITLE></TITLE>
      </HEAD>
      <BODY>
        <H1>
    Hello  
          <xsl:value-of select="name"/>
        </H1>
      </BODY>
    </HTML>

 </xsl:template>
</xsl:stylesheet>

Step 3: The Java code to perform the transformation by applying the above XSL.

package com.xml;

import java.io.ByteArrayInputStream;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class XsltTransform {

 public static void main(String[] args) {

  String xml = "<Employee><name type=\"first\">Peter</name><age>25</age></Employee>";
  String xsl = "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\r\n" + 
    " <xsl:template match=\"/Employee\">\r\n" + 
    "    <HTML>\r\n" + 
    "      <HEAD>\r\n" + 
    "        <TITLE></TITLE>\r\n" + 
    "      </HEAD>\r\n" + 
    "      <BODY>\r\n" + 
    "        <H1>\r\n" + 
    "    Hello  \r\n" + 
    "          <xsl:value-of select=\"name\"/>\r\n" + 
    "        </H1>\r\n" + 
    "      </BODY>\r\n" + 
    "    </HTML>\r\n" + 
    "\r\n" + 
    " </xsl:template>\r\n" + 
    "</xsl:stylesheet>";

  try {
   Source xmlSource = new StreamSource(new ByteArrayInputStream(xml.getBytes()));
   Source xslSource = new StreamSource(new ByteArrayInputStream(xsl.getBytes()));
   Result result = new StreamResult(System.out);
   
   TransformerFactory factory = TransformerFactory.newInstance();
   Transformer transformer = factory.newTransformer(xslSource);
   transformer.transform(xmlSource, result);

  } catch (TransformerException  e) {                         
   e.printStackTrace();
  }

 }
}


Output:

<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE></TITLE>
</HEAD>
<BODY>
<H1>
    Hello  
          Peter</H1>
</BODY>
</HTML>


Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home