Coding Tips (JavaScript/CSS/VBA/Win32)

Useful code snippets, tips and some Windows applications

A simple way to find data in XML using dom4j

The dom4j is a small but powerful package to parse XML documents. It has the advantage of a very small footprint and being very easy to use. The dom4j website has a lot of examples on how to use it.

If you have a simple xml file like the following one, I will show you how to use dom4j to find data.

<?xml version="1.0"?>
<students>
        <student>
                <name>Mike</name>
                <course>JSP</course>
        </student>
        <student>
                <name>Janet</name>
                <course>EJB</course>
        </student>
</students>

The file name is students.xml.

Suppose, you need to find the course for a student named Mike.

First, you need to parse a document:

public Document parse(String file) throws DocumentException {
	SAXReader reader = new SAXReader();
	Document document = reader.read(file);
	return document;
}

Document doc= parse("students.xml");

Then, use the following statement:

String course = doc.valueOf("//student[name='Mike']/course");

This statement uses an XPath Engine library from Jaxen which means you need to have it in your classpath.

If you want to limit your library usage to dom4j proper you'll have to write your own method which may look like the following:

public String findStudentCourse(Document doc, String studentName) {
	Element root = doc.getRootElement();
	for (Iterator i = root.elementIterator(); i.hasNext();) {
		Element el = (Element) i.next();
		if (el.elementText("name").equals(studentName)) {
			return el.elementText("course");
		}
	}
	return null;
}

If you want to iterate through all the student elements and print the name-course combinations use the following example:

Element root = document.getRootElement();
for (Iterator i = root.elementIterator(); i.hasNext();) {
	Element el = (Element) i.next();
	System.out.println("Child Element Path :" + el.getPath());
	System.out.println("	Name:" + el.elementText("name"));
	System.out.println("	Course:" + el.elementText("course"));
}

More Java Tips

Text File Splitter Class. Full code listed

Add single quotes around a String if it is not a number

Enumerate all keys of a Hashtable

JSTL SQL Tips