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.

Related posts:

  1. Using Dom4J: Writing An XML
  2. XML Object Cereal
  3. Escape From XML
  4. The Word Is POI
  5. Class HighLite File

This entry was posted in HTML/XML, Java, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. dbea
    Posted January 21, 2008 at 11:09 am | Permalink

    Perfect for newbies.

    Brief, direct and clear…

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*