Tutorial #14: Reading XML file in Java

Hello everyone,

Today’s tutorial talks about reading an XML file in Java. In situations where you need to build enterprise Java applications, XML files are used for data representation, messaging and transfer. Java provides good support for handling XML files/documents by using various XML parsers available.

Now, there are various ways to read an XML file in Java. Some of them are as follows:

1. JAXP – Java API for XML parsing

Java provides support for reading/writing XML file and accessing any element from XML file. All XML parsing related classes and methods are present inside JAXP. All XML parsers are in javax.xml.parsers package.

2. Parse XML file using SAX parser

SAX parser is faster and uses less memory than DOM parser (discussed below). The Simple API for XML (SAX) provides a mechanism to read data from an XML document by operating on each piece of the XML document sequentially.

Program to implement SAX parser

Step 1: Create a new Java Application Project

Step 2:

The SAX parser uses a callback function org.xml.sax.helpers.DefaultHandler and hence we need to create a class say MyHandler that extends the DefaultHandler class.

More information can be obtained from here.

MyHandler.java


package pack;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyHandler extends DefaultHandler {

	@Override
	public void startDocument() throws SAXException {
		System.out.println("Start of document...");
	}

	@Override
	public void endDocument() throws SAXException {
		System.out.println("End of document");	
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		System.out.println("Got new element : "+qName);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		System.out.println("End of element");
	}
	
}

Step 3: Finally, implement the main method!

App1.java

package pack;

import org.xml.sax.*;
import javax.xml.parsers.*;

public class App1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		
		try{
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();	
		 //sample.xml is an XML file you want to parse. include it inside your source folder
			parser.parse("src/sample.xml", new MyHandler());
			System.out.println("Your XML file is valid!");
			
		}catch(SAXException ex){
			System.out.println("Validation failed!");
			System.out.println(ex.getMessage());
		}catch(Exception ex){
			System.out.println("Cannot read xml file");
			ex.printStackTrace();
		}

	}

}

sample.xml

<?xml version="1.0" encoding="UTF-8"?>
<EmpData>
<Emp id="101" name="karan" designation="developer"/>
<Emp id="102" name="kamal" designation="developer"/>
<Emp id="103" name="ganesh" designation="developer"/>
</EmpData>

Output
Start of document…
Got new element : EmpData
Got new element : Emp
End of element
Got new element : Emp
End of element
Got new element : Emp
End of element
End of element
End of document
Your XML file is valid!

Program to implement DOM parser

DOM parser will parse the entire XML document and then load it into the memory. It creates a tree structure for traversal.

AppMain2.java

package pack;

import java.io.IOException;

import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class AppMain2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
			
			try {
				DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
				DocumentBuilder db=	fact.newDocumentBuilder();
				Document d = db.parse("src/sample.xml");
				System.out.println("Validation is over");
				System.out.println("Root: "+d.getDocumentElement().getTagName());
				
				
				NodeList nList = d.getElementsByTagName("Emp");
				 
			 
				for (int temp = 0; temp < nList.getLength(); temp++) {
			 
					Node nNode = nList.item(temp);
			 
					
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
			 
						Element eElement = (Element) nNode;
			 
						System.out.println("Emp Id : " + eElement.getAttribute("id"));
						System.out.println("Employee Name : " + eElement.getAttribute("name"));
						System.out.println("Employee designation: " + eElement.getAttribute("designation"));
						
					}
				}
				
				
			} catch (ParserConfigurationException e) {
				System.out.println("Unable to initialize DOM Parser");
				e.printStackTrace();
			} catch (SAXException e) {
				System.out.println("Error in XML document");
				e.printStackTrace();
			} catch (IOException e) {
					System.out.println("Unable to read file");
					e.printStackTrace();
			}
			

	}

}

Output
Validation is over
Root: EmpData
Emp Id : 101
Employee Name : karan
Employee designation: developer
Emp Id : 102
Employee Name : kamal
Employee designation: developer
Emp Id : 103
Employee Name : ganesh
Employee designation: developer

So that’s all about reading XML files in Java. There are several other ways which are better than the ones discussed over here. I will try to include them in my further tutorials! Enjoy! 🙂

Time for some Jython magic!

Hello,

I love trying out new programming languages and my next learning would be Jython, an implementation of the Python programming language written in Java. Through this post, I will walk through the basic installation of Jython in Windows and help you write a small Jython program! 🙂

Follow these simple steps and you can start programming using Jython in no time!

Note: Ensure that you have the latest version of Java installed on your machine before you proceed further.

Step 1: Download the latest version of Jython from here. You need to download the .jar file for Jython-installer.

Step 2: After you have downloaded Jython, open Command prompt, navigate to the location where your downloaded .jar file exists and type:

java -jar jython-installer-2.7.jar

This should launch setup window for Jython. Just follow the instructions and you should have Jython configured in no time!

Step 3: Once installation is done you can now navigate to the bin folder inside Jython and double click the jython batch file. You will then see a window as follows:

jython_1

Now let’s write a simple program to import Java swing library! I will be using the Python IDLE to write the code.

swing_demo.py

from pawt import swing
import java

def exit(e): java.lang.System.exit(0)

frame = swing.JFrame('Swing Demo using Jython', visible=1)
button = swing.JButton('Click to close!', actionPerformed=exit)
frame.contentPane.add(button)
frame.pack()

If everything works fine and no errors are displayed you should get a new window similar to the one using Java Swing API. Happy coding! 🙂

My Android Smartwatch!

Hey everyone,

I bought a brand new Android Smartwatch recently. The watch is manufactured by Sony and is one of the coolest gadgets to have out there! 🙂

I had decided to buy the watch in December 2011. Back then it was priced at approximately 7,000 INR on a popular online shopping store. I decided to wait for a few months since I was doubtful about it’s availability in India. However, after a few initial hiccups, I now finally own the watch and it’s working perfectly fine! 🙂

So what’s so special about this watch? Well, all you need to do is pair your phone via Bluetooth to the smartwatch and it handles almost every task you do on your mobile. You can view your messages, call logs, facebook feeds, twitter updates and get the weather information. It also supports Google Maps and a camera application. The thing I love about the phone is the music player application using which I can play, pause and listen to any song without using my mobile.

BTW here’s how it looks! 🙂

The Display Time

The Display Time

Music player \m/

Music player \m/

Applications!

Applications!

Social networking!

Social networking!

Tutorial #13: Struts 2 XML based validation framework

Hello everyone,

Here’s another tutorial on Struts 2 that talks about the use of the validation framework that help enable validation rules to your actions before they are executed. The validation framework handles both server side and client side form validation. The main advantage of the validation framework is that it helps separate the validation logic from your actual Java code.

So let’s start implementing our validation logic by creating a new Struts 2 application!

Requirements: Eclipse for Java EE(latest version preferably), Apache Tomcat Server, Struts 2 libraries

Step 1: Create a new Dynamic Web Project in Eclipse and name it StrutsValidation.

Step 2: Create a new Action class named RegisterAction.java and add the following code:

package actions;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport
{
	
	private static final long serialVersionUID = 1L;
	
	private String name;
	private int age;
	private String email;
	private String contact;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getContact() {
		return contact;
	}
	public void setContact(String contact) {
		this.contact = contact;
	}
	
	
	public String execute() throws Exception
	{
		return SUCCESS;
	}
	
}

Step 3: After you have created your Action class, you need to create the corresponding JSP page that will display the Registration form.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration form</title>
</head>
<body>

 <s:form action="register.action" method="post" validate="true">
      <s:textfield name="name" label="name" size="20" />
      <s:textfield name="age" label="age" size="20" />
      <s:textfield name="email" label="email"/>
      <s:textfield name="contact" label="contact"/>
     <s:submit name="submit" label="submit" align="center" />
 </s:form>

</body>
</html>

In order to add client side validation we just need to add validate=”true” in our JSP file (as done above) and Struts 2 will automatically generate client side validation code of form.

Step 4: It’s now time to add your validation logic. To do so, we create an XML file and name it RegisterAction-validation.xml. Here it is important to note that the name of the XML file should be in the form (Action-class-name)-validation.xml

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE validators PUBLIC
  		"-//Apache Struts//XWork Validator 1.0.3//EN"
  		"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">

<validators>

   <field name="name">
      <field-validator type="requiredstring">
         <message>
            The name is required!
         </message>
      </field-validator>
   </field>

   <field name="age">
     <field-validator type="int">
         <param name="min">29</param>
         <param name="max">64</param>
         <message>
            Age must be in between 28 and 65!
         </message>
      </field-validator>
   </field>
   
   
   <field name="email">
  		<field-validator type="requiredstring">
  		<message>email is required!</message>
  		</field-validator>
  		<field-validator type="email">
  		<message>invalid email id!</message>
  		</field-validator>
  	</field>
  
   <field name="contact">
        <field-validator type="requiredstring">
            <message>Contact no is required! </message>
        </field-validator>
        <field-validator type="stringlength">
        <param name="minLength">10</param>
        <param name="maxLength">15</param>
        <message>Your contact no needs to be between ${minLength} and ${maxLength} digits long</message>
        </field-validator>
    </field>
   
</validators>

It is important to note that the above XML file must be inside the same package as that of your Action class. The XML file contains different field validators for respective fields of the form.

Step 5: Finally, ensure that no errors are present and run the application on Tomcat Server.

struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
	"http://struts.apache.org/dtds/struts-2.1.dtd">
	
<struts>
	<package name="p1" namespace="" extends="struts-default">
	  
	   
	  <action name="register" class="actions.RegisterAction">
	  		<result name="success">success.jsp</result>
	  		<result name="input">register.jsp</result>
	  </action>
	      
	</package>
</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>StrutsValidation</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
   <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
Home Page

Home Page

Registration form showing validation

Registration form showing validation

Successful registration

Successful registration

Source code of this tutorial can be found over here.

10,000 visitors and still counting!

Hello everyone,

I launched the website back in September 2012. It’s been just 5 months since then and the site has now achieved the 10K visitors milestone. I would sincerely like to thank each one of you who visit the website.

Of late, I have not posted any new articles due to my professional commitments but I assure a more quicker update from now. Hope you guys liked the content I posted till now and please keep visiting as I have lots in store for the future as well! 🙂

Crossed the 10K visitors milestone!

Crossed the 10K visitors milestone!

thank_you