HTML Navigation – Java Examples

Data Extraction, also well known as web data extraction, is used for extracting data from websites. A Data Extraction software will help you to automate the process of extracting data based on your requirements. Using Aspose.HTML class library, you can easily create your own application, since our API provides a powerful toolset to analyze and collect information from HTML documents.

HTML navigation

There are many ways that can be used to make HTML navigation. The following shortlist shows the simplest way to access to all DOM elements:

PropertyDescription
FirstChildAccessing this attribute of an element must return a reference to the first child node.
LastChildAccessing this attribute of an element must return a reference to the last child node
NextSiblingAccessing this attribute of an element must return a reference to the sibling node of that element which most immediately follows that element.
PreviousSiblingAccessing this attribute of an element must return a reference to the sibling node of that element which most immediately precedes that element.
ChildNodesReturns a list that contains all children of that element.

Using the mentioned properties, you can navigate through an HTML document as it follows:

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

For the more complicated scenarios, when you need to find a node based on a specific pattern (e.g., get the list of headers, links, etc.), you can use a specialized TreeWalker or NodeIterator object with a custom Filter implementation.

The next example shows how to implement your own NodeFilter to skip all elements except images:

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

Once you implement a filter, you can use HTML navigation as it follows:

 1// Prepare HTML code
 2String code = "    < p > Hello, </p >\n" +
 3        "    <img src = 'image1.png' >\n" +
 4        "    <img src = 'image2.png' >\n" +
 5        "    <p > World ! </p >\n";
 6
 7// Initialize a document based on the prepared code
 8HTMLDocument document = new HTMLDocument(code, ".");
 9
10// To start HTML navigation, we need to create an instance of TreeWalker
11// 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
12ITreeWalker iterator = document.createTreeWalker(document, NodeFilter.SHOW_ALL, new OnlyImageFilter());
13// Use
14while (iterator.nextNode() != null) {
15    // Since we are using our own filter, the current node will always be an instance of the HTMLImageElement
16    // So, we don't need the additional validations here
17    HTMLImageElement image = (HTMLImageElement) iterator.getCurrentNode();
18
19    System.out.println(image.getSrc());
20    // output: image1.png
21    // output: image2.png
22}

XPath

The alternative to the HTML Navigation is XML Path Language. The syntax of the XPath expressions is quite simple and what is more important, it is easy to read and support.

The following example shows how to use XPath queries within Aspose.HTML API:

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

CSS Selector

Along with HTML Navigation and XPath you can use CSS Selector API that is also supported by our library. This API is designed to create a search pattern to match elements in a document tree based on CSS Selectors syntax.

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

Get monthly newsletters & offers directly delivered to your mailbox.