Back to Java
2025-12-158 min read

DOM Navigation (Java)

Learn DOM Navigation (Java) step by step with clear examples and exercises.

Why This Matters

Welcome to our full guide on Java Document Object Model (DOM) navigation! This tutorial aims to provide you with a thorough understanding of this essential tool, which is crucial for any web developer who wants to manipulate HTML documents programmatically. By the end of this tutorial, you will be able to build more interactive and responsive web applications using DOM navigation in Java.

Prerequisites

To follow this tutorial, you should have a basic understanding of:

  1. Java programming language: Familiarity with variables, loops, functions, classes, and exceptions is required.
  2. HTML and CSS basics: Understanding the structure of HTML documents, including elements, attributes, and CSS styles, is essential.
  3. Basic concepts of web development: Knowledge of client-side scripting (JavaScript), server-side scripting (PHP, Node.js, etc.), and web architecture is beneficial but not strictly necessary.
  4. Familiarity with an Integrated Development Environment (IDE) such as Eclipse or IntelliJ IDEA: A basic understanding of how to set up a project, write code, and run programs in an IDE is required.

Core Concept

The Document Object Model (DOM) is an API that provides a tree-like representation of an HTML document. In Java, we use the javax.xml.parsers package to parse HTML documents and navigate through their structure using various methods.

Parsing an HTML document

To parse an HTML document in Java, we first need to create a DocumentBuilderFactory, which will be used to build a DocumentBuilder. The DocumentBuilder is then used to parse the HTML document into a Document object. Here's an example:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("index.html");
}
}

In this example, we create a DocumentBuilderFactory, get a DocumentBuilder, and parse the "index.html" file into a Document object.

Navigating through the DOM tree (expanded)

Once we have the Document object, we can navigate through its tree structure using various methods such as getElementsByTagName(), getChildNodes(), and getAttribute(). Here's an example of how to find all `` elements in the document:

NodeList pElements = document.getElementsByTagName("p");
for (int i = 0; i < pElements.getLength(); i++) {
System.out.println(pElements.item(i).getTextContent());
}

In this example, we use the getElementsByTagName() method to get all `` elements in the document and print their text content.

Navigating using XPath expressions (optional)

XPath is a query language for selecting nodes from an XML document, including HTML documents. In Java, you can use the javax.xml.xpath package to navigate through the DOM tree using XPath expressions. Here's an example of how to find all `` elements with the class "highlight":

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathExpression;
import org.w3c.dom.NodeList;

public class Main {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("index.html");

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/html/body//p[@class='highlight']");
NodeList pElements = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

for (int i = 0; i < pElements.getLength(); i++) {
System.out.println(pElements.item(i).getTextContent());
}
}
}

In this example, we use an XPath expression to find all `` elements with the class "highlight".

Worked Example

Let's work through an example where we parse an HTML document, find a specific element, modify its content, and save the changes back to the file.

  1. First, create a new Java project in your preferred IDE.
  2. Create a new file named "index.html" in the src folder with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Navigation Example</title>
</head>
<body>
<h1>Welcome to our website!</h1>
<p id="greeting">Hello, World!</p>
</body>
</html>
  1. Create a new class named DomNavigationExample in the same package as your project's main class.
  2. Write the following code to parse the HTML document, find the element with the id "greeting", modify its content, and save the changes back to the file:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Attr;
import java.io.File;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class DomNavigationExample {
public static void main(String[] args) throws Exception {
// Parse the HTML document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File inputFile = new File("src/index.html");
Document document = builder.parse(inputFile);

// Find the element with the id "greeting"
NodeList elements = document.getElementsByTagName("*");
for (int i = 0; i < elements.getLength(); i++) {
Node node = elements.item(i);
if ("p".equals(node.getNodeName()) && "greeting".equals(node.getAttributeNode("id").getValue())) {
// Modify the content of the element
Node newContent = document.createTextNode("Hello, Java!");
node.replaceChild(newContent, node.getFirstChild());

// Save the changes back to the file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(inputFile);
transformer.transform(source, result);
}
}
}
}
  1. Run the DomNavigationExample class and check the "index.html" file in your project's src folder to see the modified content.

Common Mistakes

  1. Forgetting to import necessary packages: Make sure you have imported all required packages at the beginning of your Java files.
  2. Incorrectly parsing the HTML document: Make sure you are using the correct method (parse()) and providing the correct file path for the File object.
  3. Not finding the desired element: Check that you have used the correct tag name, attribute name, or XPath expression to find the desired element.
  4. Modifying the wrong element: Double-check that you are modifying the intended element and not an unintended sibling or child node.
  5. Not saving changes back to the file: Make sure you have saved the modified Document object back to the original HTML file using a Transformer.
  6. Ignoring exceptions: Always handle exceptions when working with Java DOM navigation to ensure your program can recover gracefully from errors.
  7. Overlooking character encoding issues: Ensure that the character encoding of your HTML document matches the one used by your Java program to avoid unexpected behavior or errors.
  8. Neglecting performance considerations: Be aware that parsing and manipulating large HTML documents can be resource-intensive, so optimize your code where possible to improve performance.

Common Mistakes - Modifying content (expanded)

  1. Modifying the wrong node type: Make sure you are modifying the intended node type (e.g., Text, Element, Attr) and not an unintended one.
  2. Creating new nodes with incorrect data types: Ensure that new nodes created with methods like createTextNode() or createElement() have the correct data types to avoid unexpected behavior or errors.
  3. Not handling nested elements correctly: When modifying nested elements, be aware of their relationships and ensure that you are modifying the intended element without affecting others.
  4. Mismanaging event listeners: If your HTML document contains event listeners (e.g., JavaScript), make sure to handle them appropriately when modifying the DOM tree to avoid unexpected behavior or errors.

Practice Questions

  1. Write a Java program that counts the number of `` elements in an HTML document and prints their href attributes.
  2. Given the following HTML:
<ul id="myList">
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>

Write a Java program that adds an - Orange `` element to the end of the list.

  1. Write a Java program that finds all images in an HTML document and prints their alt attributes.
  2. (Advanced) Write a Java program that uses XPath expressions to find all links with the class "external" and open them in a new tab using JavaScript.
  3. (Challenge) Write a Java program that extracts all email addresses from an HTML document and sends them an email notification.

FAQ

  1. Why do I need to use DOM navigation in my web development projects?
  • DOM navigation allows you to manipulate HTML documents programmatically, making it easier to create dynamic and interactive web applications.
  1. What are some common mistakes when working with Java DOM navigation?
  • Common mistakes include forgetting to import necessary packages, incorrectly parsing the HTML document, not finding the desired element, modifying the wrong element, not saving changes back to the file, ignoring exceptions, overlooking character encoding issues, neglecting performance considerations, and mismanaging event listeners.
  1. How can I find a specific element in an HTML document using DOM navigation?
  • You can use methods such as getElementsByTagName(), getElementById(), or XPath expressions to find a specific element in an HTML document.
  1. What is the best way to modify the content of an HTML element using Java DOM navigation?
  • To modify the content of an HTML element, you can create a new text node with the desired content and replace the existing content node using the replaceChild() method. Be aware of node types and relationships when modifying nested elements or handling event listeners.
  1. How do I save changes made to an HTML document using Java DOM navigation back to the file?
  • You can use a Transformer to save the modified Document object back to the original HTML file by creating a DOMSource for the Document, a StreamResult for the output file, and calling the transform() method on the Transformer.
  1. What is XPath, and how can it be used with Java DOM navigation?
  • XPath is a query language for selecting nodes from an XML document, including HTML documents. In Java, you can use the javax.xml.xpath package to navigate through the DOM tree using XPath expressions. This allows for more flexible and powerful queries when finding specific elements in an HTML document.
DOM Navigation (Java) | Java | XQA Learn