Read XML Xalan Java

Read XML Xalan Java

Xalan is very popular library from Apache which implements XSLT XML transformation language and XPath language. Reading XML file using is faster where you could use Xpath to read the file.

If you are building new application and want to keep configuration related information in one central location, many choices are available out of which keeping information on XML file can be good choice and this will work as central location of all configuration where you can divide XML config file based on the environment. We will use Xalan parser to read XML file. Below is sample XML file which is divided in two environment i.e DEV and QA. I will create small project to show you how to load and read XML file where static block will be use load XML file first time when user makes call and keep data in cache to give better performance in web application.

  • Sample maven project structure:

Read XML Xalan Java

  • pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javahonk</groupId>
	<artifactId>ReadXMLConfig</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>ReadXMLConfig Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>xalan</groupId>
			<artifactId>xalan</artifactId>
			<version>2.7.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>ReadXMLConfig</finalName>
	</build>
</project>
  • Sample xml file: XMLBootstrap.xml
<SAMPLE_CONFIG>
   <DEV>
	  <READXML>Successful</READXML>
      <TestServices>
         <class>MyController</class>         
      </TestServices>
      <JNDI>
         <JDBC>
            <DATABASE>
               <NAME>MYSQLDB</NAME>               
            </VWDB>
            <USERNAME>
            	<NAME>JavaHonk</NAME>
            </USERNAME>            
         </JDBC>        
      </JNDI>      
   </DEV>
   <QA>
	  <READXML>Successful</READXML>
      <TestServices>
         <class>MyController</class>         
      </TestServices>
      <JNDI>
         <JDBC>
            <DATABASE>
               <NAME>MYSQLDB</NAME>               
            </VWDB>
            <USERNAME>
            	<NAME>JavaHonk</NAME>
            </USERNAME>            
         </JDBC>        
      </JNDI>      
   </QA>
</SAMPLE_CONFIG>
  • XMLConfig.java: To parse XML file:
package com.javahonk;

import java.io.File;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.xpath.CachedXPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class XMLConfig
{
   private static final String ENVIRONMENT = "DEV";
   private static final Node CONFIG_ROOT;
   private static final CachedXPathAPI XPATH_API;
   private static final HashMap<String, String> CONFIG_CACHE = new HashMap<String, String>();

   static
   {
      //static initializer
      try
      {
         File oConfigFile = new File("src\\main\\resources\\XMLBootstrap.xml");
         DocumentBuilderFactory oFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder oBuilder = oFactory.newDocumentBuilder();
         Document oDoc = oBuilder.parse(oConfigFile);
         XPATH_API = new CachedXPathAPI();
         CONFIG_ROOT = XPATH_API.selectSingleNode(oDoc, "/SAMPLE_CONFIG/" + ENVIRONMENT);
         if (CONFIG_ROOT == null)
         {
            throw new Exception("Unable to location environment configuration at '/SAMPLE_CONFIG/" + ENVIRONMENT + "'.");
         }
      }
      catch (Exception e)
      {
         throw new RuntimeException("Unable to load trexo bootstrap file at XMLBootstrap.xml.", e);
      }
   }
   
   //returns a bootstrap parameter as a string
   public static String GetString(String sParamName)
   {
      //first check the cache
      String sReturn = (String) CONFIG_CACHE.get(sParamName);

      if (sReturn == null)
      {
         //not in cache so retrieve it from the XML then put it in the cache
         sReturn = GetParameterAsString(sParamName);
         CONFIG_CACHE.put(sParamName, sReturn);
      }

      return sReturn;
   }
   
   public static int GetInt(String sParamName)
   {
      return Integer.parseInt(GetString(sParamName));
   }

   public static boolean GetBool(String sParamName)
   {
      return Boolean.getBoolean(GetString(sParamName));
   }

   //it is assumed that the name of the node is the parameter name and
   //the value of the text node is the value of the parameter
   private static String GetParameterAsString(String sParamName)
   {
      try
      {
         Node oNode = null;

         synchronized(XPATH_API)
         {
            //synchronize access to the XPath evaluation object
            oNode = XPATH_API.selectSingleNode(CONFIG_ROOT, sParamName + "/text()");
         }

         if (oNode == null)
         {
            //if null, then the parameter isn't defined so throw an exception
            throw new RuntimeException("Unable to locate parameter '" + sParamName + "' in the " + ENVIRONMENT + " region of the bootstrap configuration file.");
         }
         
         return oNode.getNodeValue();
      }
      catch (Exception e)
      {
         //if the XPath fails, then the TransformerException will be caught h ere
         throw new RuntimeException("Unable to locate parameter '" + sParamName + "' in the " + ENVIRONMENT + " region of the bootstrap configuration file.");
      }
   }
}
  • Client class which will call XMLConfig.java and read its value:
package com.javahonk;

public class ReadXMLConfigFile {

	public static void main(String[] args) {
		
		//Read XML file		
		System.out.println("Read XML: "+XMLConfig.GetString("/SAMPLE_CONFIG/DEV/READXML"));
		System.out.println("User name: "+XMLConfig.GetString("/SAMPLE_CONFIG/DEV/JNDI/JDBC/USERNAME/NAME"));
		System.out.println("Database name: "+XMLConfig.GetString("/SAMPLE_CONFIG/DEV/JNDI/JDBC/DATABASE/NAME"));

	}

}
  • Output:

Read XML Xalan Java

  • For more details on Xalan please please go here 

download  Download Project: ReadXMLConfig

Leave a Reply

Your email address will not be published. Required fields are marked *