HTML DOM Navigation in Java

Aspose.HTML for Java provides several ways to locate and inspect content in an HTMLDocument. Java code can move between related DOM nodes, traverse a document with a filter, evaluate an XPath expression, or select elements with a CSS selector.

Use direct DOM navigation when the position of a node is already known, TreeWalker with NodeFilter for controlled traversal, XPath for structural expressions, and CSS selectors for familiar matching by tag, class, ID, or attribute.

The Node API provides methods for moving through parent, child, and sibling relationships. Node-based methods can return text, comment, or element nodes, while element-specific methods skip non-element nodes.

Java methodResult
getFirstChild() and getLastChild()The first or last child node, including non-element nodes
getNextSibling() and getPreviousSibling()The adjacent sibling node
getChildNodes()A NodeList containing all child nodes
getFirstElementChild() and getLastElementChild()The first or last child element
getNextElementSibling() and getPreviousElementSibling()The adjacent sibling element

The following example creates an HTML document from a string, reads its first child element, and then moves to the next element sibling:

 1// Navigate the HTML DOM using Java
 2
 3// Prepare HTML code
 4String html_code = "<span>Hello,</span> <span>World!</span>";
 5
 6// Initialize a document from the prepared code
 7HTMLDocument document = new HTMLDocument(html_code, ".");
 8
 9// Get the reference to the first child (first <span>) of the document body
10Element element = document.getBody().getFirstElementChild();
11System.out.println(element.getTextContent());
12// @output: Hello,
13
14// Get the reference to the second <span> element
15element = element.getNextElementSibling();
16System.out.println(element.getTextContent());
17// @output: World!

Filter Nodes with TreeWalker and NodeFilter

For controlled traversal, create a TreeWalker or NodeIterator and supply a custom NodeFilter. The following filter accepts <img> elements and skips other nodes:

 1// Create custom NodeFilter to accept only image elements in Java
 2
 3public static class OnlyImageFilter extends NodeFilter {
 4    @Override
 5    public short acceptNode(Node n) {
 6        // The current filter skips all elements, except IMG elements
 7        return "img".equals(n.getLocalName())
 8                ? FILTER_ACCEPT
 9                : FILTER_SKIP;
10    }
11}

Use the filter when creating a TreeWalker, call nextNode() to advance through accepted nodes, and read the current node as an HTMLImageElement:

 1// Filter HTML elements using TreeWalker and custom NodeFilter in Aspose.HTML for Java
 2
 3// Prepare HTML code
 4String code = "    <p> Hello, </p>\n" +
 5        "    <img src = 'image1.png'>\n" +
 6        "    <img src = 'image2.png'>\n" +
 7        "    <p> World! </p>\n";
 8
 9// Initialize a document based on the prepared code
10HTMLDocument document = new HTMLDocument(code, ".");
11
12// To start HTML navigation, we need to create an instance of TreeWalker
13// The specified parameters mean that it starts walking from the root of the document, iterating all nodes, and using our custom implementation of the filter
14ITreeWalker iterator = document.createTreeWalker(document, NodeFilter.SHOW_ALL, new NodeFilterUsageExample.OnlyImageFilter());
15// Use
16while (iterator.nextNode() != null) {
17    // Since we are using our own filter, the current node will always be an instance of the HTMLImageElement
18    // So, we don't need the additional validations here
19    HTMLImageElement image = (HTMLImageElement) iterator.getCurrentNode();
20
21    System.out.println(image.getSrc());
22    // @output: image1.png
23    // @output: image2.png
24}

Select HTML Elements with XPath

XPath selects nodes through expressions based on document structure, attributes, and relationships. It is useful when a query must describe more than a simple tag, class, or ID match.

The following example calls document.evaluate() with the expression //*[@class='happy']//span and iterates through the matching <span> nodes:

  1. Create an HTML document containing the elements to inspect.
  2. Evaluate an XPath expression against the document.
  3. Request an iterable XPath result.
  4. Call iterateNext() until every matching node has been processed.
 1// Select HTML elements using XPath expression in Aspose.HTML for Java
 2
 3// Prepare HTML code
 4String code = "<div class='happy'>\n" +
 5        "        <div>\n" +
 6        "            <span> Hello! </span>\n" +
 7        "        </div>\n" +
 8        "    </div>\n" +
 9        "    <p class='happy'>\n" +
10        "        <span> World! </span>\n" +
11        "    </p>\n";
12
13// Initialize a document based on the prepared code
14HTMLDocument document = new HTMLDocument(code, ".");
15
16// Here, we evaluate the XPath expression where we select all child <span> elements from elements whose 'class' attribute equals to 'happy'
17IXPathResult result = document.evaluate("//*[@class='happy']//span",
18        document,
19        null,
20        XPathResultType.Any,
21        null
22);
23
24// Iterate over the resulted nodes
25for (Node node; (node = result.iterateNext()) != null; ) {
26    System.out.println(node.getTextContent());
27    // @output: Hello!
28    // @output: World!
29}

Select HTML Elements with CSS Selectors

CSS selectors provide concise matching by element name, class, ID, attribute, and relationship. The example uses document.querySelectorAll(".happy span") to select descendant <span> elements inside elements whose class includes happy.

  1. Create an HTML document containing the target elements.
  2. Pass a CSS selector to querySelectorAll().
  3. Iterate through the returned NodeList and read the selected elements.
 1// Select HTML elements using CSS selector querySelectorAll method in Aspose.HTML for Java
 2
 3// Prepare HTML code
 4String code = "<div class='happy'>\n" +
 5        "        <div>\n" +
 6        "            <span> Hello, </span>\n" +
 7        "        </div>\n" +
 8        "    </div>\n" +
 9        "    <p class='happy'>\n" +
10        "        <span> World! </span>\n" +
11        "    </p>\n";
12
13// Initialize a document based on the prepared code
14HTMLDocument document = new HTMLDocument(code, ".");
15
16// Here, we create a CSS Selector that extracts all elements whose 'class' attribute equals to 'happy' and their child SPAN elements
17NodeList elements = document.querySelectorAll(".happy span");
18
19// Iterate over the resulted list of elements
20elements.forEach(element -> {
21    System.out.println(((HTMLElement) element).getInnerHTML());
22    // @output: Hello,
23    // @output: World!
24});

Choose an HTML Selection Method

MethodBest suited for
Direct DOM navigationMoving between known parents, children, or siblings
TreeWalker and NodeFilterTraversing a document while accepting or skipping specific nodes
XPathSelecting nodes with structural paths and relationship conditions
CSS selectorsMatching elements with familiar web selector syntax

Common HTML Navigation Issues

IssueCauseFix
getFirstChild() returns a text nodeWhitespace between tags is represented by a DOM text node.Use getFirstElementChild() when only an element is required.
XPath or CSS query returns no nodesThe expression does not match the DOM loaded by the application.Inspect the actual elements and attributes, then test a simpler expression first.
A cast to an element type failsThe traversal can return nodes of another type.Restrict accepted nodes with NodeFilter or check the node type before casting.

Related Aspose.HTML Articles

Try AI Keyword Extractor

Aspose.HTML offers AI Keyword Extractor, an online tool for extracting keywords from a web page, plain text, or a file without writing Java code.

Text “AI Keyword Extractor”