Using Dom4J: Reading An XML File

For almost every project I have worked on I have had to work with XML files. I’ve used SAX and DOM parsers and have even written my own XML writers. But now for most of my XML needs I use Dom4J. Dom4J will get you started quickly. These four little lines will read in an XML file:

File xml = new File("simple.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(xml);
Element root = doc.getRootElement();

Of course, you will need to import the Dom4J SAXReader, Document and Element classes from the correct package. The SAXReader read method is heavily overloaded and you can read from a String, URL, InputStream, etc. Once you have an Element object you can get the name, attributes, and child elements. The following code will iterate through the child elements:

for(Iterator i = root.elements().iterator(); i.hasNext();)
   Element elem = (Element)i.next();

This is all the code you need to start reading in an XML document.