Skip to main content

How to use XML and XSL in Java?

Almost everyday, somewhere we come across XML and we know that many systems use XML as their data store; more precisely, they talk in XML language.

Now, how do I write an application where I need to present the data, which is in XML format, to users? Is it possible to write XML processing application in Java?

Yes, Java SE provides extensive support for XML parsing and processing. Java supports two types of XML parsers, viz, SAX and DOM. These parsers and their supporting classes are collectively called JAXP, Java API for XML Processing.

Now given a XML document, how do I transform it in a user presentable format rather than parsing the XML document? Or do I need to parse the XML to transform it?

No and may be. No - you don't have to parse it to transform it; java will do it for you with the help of XSL. May be - if you want to.

Enough of theory. Let's program. Here is the sample XML file.
<?xml version="1.0" encoding="UTF-8"?>
<report
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:w ='http://xml.netbeans.org/schema/newXmlSchema'>
<students>
<student>                      
  <name>Joanus</name>
  <marks>
      <maths>80</maths>
      <physics>75</physics>
      <chemistry>90</chemistry>
      <biology>96</biology>
  </marks>
</student>              
<student>                      
  <name>Shawn</name>
  <marks>
      <maths>90</maths>
      <physics>73</physics>
      <chemistry>79</chemistry>
      <biology>98</biology>
  </marks>
</student>
<student>                      
  <name>Jarius Asir</name>
  <marks>
      <maths>70</maths>
      <physics>74</physics>
      <chemistry>89</chemistry>
      <biology>68</biology>
  </marks>
</student>
<student>                      
  <name>Janola Violet</name>
  <marks>
      <maths>100</maths>
      <physics>65</physics>
      <chemistry>90</chemistry>
      <biology>88</biology>
  </marks>
</student>
</students>
</report>


I want to render this data in a tabular format to the user. Let's write the XSL as follows.


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
  <head>
      <style type="text/css">
          #top-table
          {
              border-collapse:collapse;
          }
          #top-table td, #top-table th
          {
              font-size:1em;
              border:1px solid #98bf21;
              padding:3px 7px 2px 7px;
          }
          #top-table th
          {
              font-size:1.1em;
              text-align:left;
              padding-top:5px;
              padding-bottom:4px;
              background-color:#A7C942;
              color:#ffffff;
          }
          #top-table tr.alt td
          {
              color:#000000;
              background-color:#EAF2D3;
          }
      </style>
  </head>
  <body>
      <xsl:apply-templates select="/report/students"/>
  </body>
</html>
</xsl:template>

<xsl:template match="students">
<table id="top-table">
  <thead>
      <tr>
          <th>Student's Name</th>
          <th>Maths</th>
          <th>Physics</th>
          <th>Chemistry</th>
          <th>Biology</th>
      </tr>
  </thead>
  <tbody>
      <xsl:apply-templates select="student"/>
  </tbody>
</table>
</xsl:template>

<xsl:template match="student">
<xsl:choose>
  <xsl:when test="position() mod 2 > 0">
      <tr class="alt">
          <xsl:apply-templates select="name"/>
          <xsl:apply-templates select="marks"/>
      </tr>
  </xsl:when>
  <xsl:otherwise>
      <tr>
          <xsl:apply-templates select="name"/>
          <xsl:apply-templates select="marks"/>
      </tr>
  </xsl:otherwise>
</xsl:choose>
</xsl:template>

<xsl:template match="name">
  <td>
      <xsl:value-of select="."/>
  </td>
</xsl:template>
<xsl:template match="marks">
  <td><xsl:value-of select="maths"/></td>
  <td><xsl:value-of select="physics"/></td>
  <td><xsl:value-of select="chemistry"/></td>
  <td><xsl:value-of select="biology"/></td>
</xsl:template>
</xsl:stylesheet>

The Java code that transforms the above XML to HTML is as follows

import java.io.File;
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;

/**
* Translates XML into HTML using XSL
* @author Pragalathan M
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws TransformerException, Exception {
   File xmlFile = new File("xml/student-marks.xml");
   File xsltFile = new File("xml/student-marks.xsl");
   Source xmlSource = new StreamSource(xmlFile);
   Source xsltSource = new StreamSource(xsltFile);
   Result result = new StreamResult(System.out);

   TransformerFactory transFactory = TransformerFactory.newInstance();

   Transformer transformer = transFactory.newTransformer(xsltSource);
   transformer.transform(xmlSource, result);
}
}

Generated output looks like this.

Student's NameMathsPhysicsChemistryBiology
Joanus80759096
Shawn90737998
Jarius Asir70748968
Janola Violet100659088



Comments

Popular posts from this blog

Using Nginx as proxy server for Keycloak

I have used Keycloak  in its very early stage ( when it is was in 2.x version). But now it has come a long way (at this time of writing it is in 21.x) In this article let's configure Keycloak behind Nginx. Here are the points to consider.  If you want to configure Apache2 as a proxy server for your java application, please check  this article . We are going to use a domain name other than localhost Anything other than localhost will require Keycloak to run in production mode which requires SSL configurations etc. Or it requires a proxy server. Lets begin. Requirements Keycloak distribution Ubuntu 22.04 server Configuring Keycloak 1. Download Keycloak from here . 2. Extract it using tar -xvzf  keycloak-21.0.1.tar.gz 3. Create a script file called keycloak.sh with the following contents #!/bin/bash export KEYCLOAK_ADMIN=<admin-username-here> export KEYCLOAK_ADMIN_PASSWORD=<admin-password-here> nohup keycloak-21.0.0/bin/kc.sh start-dev --proxy edge --hos...

Installing GoDaddy certificate in Wildfly/Keycloak

In the previous post we saw how to set up Keycloak . Here we will see how to generate and install GoDaddy.com certificate in Keycloak. The steps are similar for Wildfly as well. Step 1: Generate CSR file Run the following commands in your terminal. <mydomain.com> has to be replaced with your actual domain name. keytool -genkey -alias mydomain_com -keyalg RSA -keysize 2048 -keystore mydomain_com.jks keytool -certreq -alias mydomain_com -file mydomain_com.csr -keystore mydomain_com.jks Step 2: Generate certificate Upload  mydomain_com . csr  file content into GoDaddy.com, generate and download certificate for tomcat server (steps to generating SSL certificate is beyond the scope of this article). If you unzip the file, you will see the following files. gd_bundle-g2-g1.crt ..5f8c...3a89.crt   #some file with alphanumeric name gdig2.crt Files 1 and 2 are of our interest. Third file is not required. Step 3: Import certificate to key...

Hibernate & Postgresql

If you are using Hibernate 3.5 or above to talk to Postgresql database, have you ever tried to store a byte array? Let's take an example. Here is the mapping which will store and read byte[] from the database. @Lob @Column(name = "image") private byte[] image; Here is the JPA mapping file configuration. <persistence version="2.0"  xmlns="http://java.sun.com/xml/ns/persistence"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">   <persistence-unit name="testPU" transaction-type="JTA">     <provider>org.hibernate.ejb.HibernatePersistence</provider>     <jta-data-source>test</jta-data-source>     <properties>     </properties>   </persistence-unit> </persistence> When you try to save your entity you will get t...

Dynamic SOAP Service Client

If you have written SOAP service client, you might know that you need the WSDL file; need to generate Java code for that,compile that Java classes and add it as dependency for your module. What would you do if you have to incorporate your code with a new SOAP service every now and then? What would you do if all you need is to consume the service and do a little processing on the output, i.e., you need the data in XML format? What would you do if you don't have a complete WSDL? What would you do if your service is in .NET whose WSDL is having problem while generating Java classes? Is there a way to write a dynamic client which can consume any SOAP service? .... YES!... there is a way. Let's quickly write a web (SOAP) service. Software used: Java 7 NetBeans IDE 7.4 GlassFish 4.0 Maven Create a web project and choose Glassfish as server. Now add web service (not a rest service) as below. Edit the SimpleService.java as follows. package com.mycom...

How to retry a method call in Spring or Quarkus?

Have you ever come across a situation where you wanted to retry a method invocation automatically? Let's say you are calling a stock ticker service for a given stock and get a transient error. Since it is a transient error, you will try again and it may work in second attempt. But what if it doesn't? Well, you will try third time. But how many times can you try like that? More importantly after how much time will you retry? Imagine if you have a handful of methods like this. Your code will become convoluted with retry logic. Is there a better way? Well, if you are using spring/spring boot, you are in luck. Here is how you can do that using spring. Let's write our business service as follows. import java.time.LocalDateTime; import java.util.concurrent.CompletableFuture; import lombok.extern.slf4j.Slf4j; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.scheduling.annotation.Async; import...