Reading and Writing XML Documents Using dom4j in Java

XML Parsing with dom4j

The dom4j library is a robust and flexible tool for processing XML data within Java applications. It simplifies the traversal, manipulation, and querying of XML documents using an intuitive object model. To integrate dom4j into your project, you can obtain the distribution from the official repository or include it via your dependency manager.

The following example demonstrates how to parse an XML file from the file system, navigate the node tree, and extract element text and atttributes. The code iterates through child nodes and filters them based on specific tag names.

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.util.Iterator;

public class XmlParserExample {

    public static void main(String[] args) throws Exception {
        // Initialize the SAX reader
        SAXReader reader = new SAXReader();
        
        // Load the XML document
        Document xmlDocument = reader.read("data/input.xml");
        
        // Retrieve the root element
        Element rootNode = xmlDocument.getRootElement();
        System.out.println("Root Element: " + rootNode.getName());

        // Iterate over child elements
        Iterator<Element> nodeIterator = rootNode.elementIterator();
        while (nodeIterator.hasNext()) {
            Element currentNode = nodeIterator.next();

            // Filter by element name
            if ("product".equals(currentNode.getName())) {
                Element descriptionNode = currentNode.element("description");
                // Safely print text content
                if (descriptionNode != null) {
                    System.out.println("Item Description: " + descriptionNode.getText());
                }
            }

            System.out.println("Child Tag: " + currentNode.getName());

            // Iterate over attributes of the current element
            Iterator<Attribute> attrIterator = currentNode.attributeIterator();
            while (attrIterator.hasNext()) {
                Attribute attr = attrIterator.next();
                System.out.println("Attribute [" + attr.getName() + "]: " + attr.getValue());
            }
        }
    }
}

Generating XML Documants

Beyond parsing, dom4j provides a fluent API for constructing XML documents from scratch. This allows for the programmatic creation of complex data structures which can then be serialized to disk or a network stream.

In the example below, a new document is created using DocumentHelper. We add a root node and append child elements containing attributes and text data. Finally, the document is written to a file using a FileWriter.

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.io.FileWriter;
import java.io.IOException;

public class XmlGeneratorExample {

    public static void main(String[] args) throws IOException {
        // Create a new empty document
        Document doc = DocumentHelper.createDocument();
        
        // Add the root element
        Element database = doc.addElement("Database");

        // Create first entry with attributes and content
        Element user1 = database.addElement("User");
        user1.addAttribute("id", "101")
             .addAttribute("role", "Admin")
             .addText("System Administrator");

        // Create second entry
        Element user2 = database.addElement("User");
        user2.addAttribute("id", "102")
             .addAttribute("role", "Guest")
             .addText("Temporary Access");

        // Write the document to a file
        try (FileWriter output = new FileWriter("users.xml")) {
            doc.write(output);
        }
    }
}

Tags: java XML DOM4J SAX Parser data serialization

Posted on Thu, 23 Jul 2026 16:27:31 +0000 by rawisjp