How to parse xml using dom4j

Dom4j is an open source library for working with XML on the java platform. This post will show you how to parse xml document using dom4j.

You can download dom4j jar from http://dom4j.sourceforge.net/download.html.

For this tutorial i used following xml file. You can create it somewhere in your file system.

<!--?xml version="1.0" encoding="UTF-8"?-->
<vehicles>
	<vehicle type="bike">
		<manufacturer>Hero Honda</manufacturer>
		<model>Passion</model>
		<price>55000</price>
		<colors>
			<color>red</color>
			<color>black</color>
			<color>blue</color>
		</colors>
	</vehicle>

	<vehicle type="bike">
		<manufacturer>Hero Honda</manufacturer>
		<model>Splendor</model>
		<price>50000</price>
		<colors>
			<color>red</color>
			<color>black</color>
			<color>blue</color>
		</colors>
	</vehicle>

	<vehicle type="bike">
		<manufacturer>Bajaj</manufacturer>
		<model>Pulsar</model>
		<price>60000</price>
		<colors>
			<color>red</color>
			<color>black</color>
		</colors>
	</vehicle>

	<vehicle type="car">
		<manufacturer>Honda</manufacturer>
		<model>City</model>
		<price>1000000</price>
		<colors>
			<color>white</color>
			<color>red</color>
			<color>black</color>
		</colors>
	</vehicle>

	<vehicle type="car">
		<manufacturer>Maruti Suzuki</manufacturer>
		<model>Swift</model>
		<price>600000</price>
		<colors>
			<color>white</color>
			<color>red</color>
			<color>black</color>
		</colors>
	</vehicle>

</vehicles>

Sample code to read xml.

package com.elitejavacoder.xml.dom4j;

import java.io.FileInputStream;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class XMLReader {

public static void main(String[] args) {

	try {
		// Create Document object
		SAXReader reader = new SAXReader();
		Document document = reader.read(new FileInputStream("F:\\development\\test_files\\vehicles.xml"));

		// Count all nodes
		System.out.println("Total Vehicles: " + document.selectNodes("//vehicles/vehicle").size());

		// Count specific nodes
		System.out.println("No. of bikes: " + document.selectNodes("//vehicles/vehicle[@type='bike']").size());

		System.out.println("No. of cars: " + document.selectNodes("//vehicles/vehicle[@type='car']").size());

		// Get specific node (i.e. bikes manufacturerd by 'Hero Honda')
		System.out.println("Bikes manufacturerd by 'Hero Honda': " + document.selectNodes("//vehicles/vehicle[@type='bike'][manufacturer='Hero Honda']").size());

		// Get the last element (i.e. last bike element and print it's details)
		Node lastBike = document.selectSingleNode("//vehicles/vehicle[@type='bike'][last()]");
		if (lastBike != null) {
			System.out.println("n==== Last Bike Details ===");
			// Get the node value inside the node
			System.out.println("Manufacturer: " + lastBike.selectSingleNode("manufacturer").getText());
			System.out.println("Model: " + lastBike.selectSingleNode("model").getText());
		}

		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}