Query an HTML DOM with Aspose.HTML for Java

Aspose.HTML for Java evaluates XPath expressions against the same DOM used for loading, inspecting, editing, saving, rendering, and converting HTML. Call evaluate() with an expression, a context node, an optional namespace resolver, a requested XPathResultType, and an optional reusable result object.

Choose XPath when a query depends on text, node position, ancestors, descendants, or another structural condition that would be awkward to express with CSS selectors. The returned IXPathResult provides access to matching DOM nodes without requiring browser automation or a second document representation.


Find HTML Elements by Text with XPath

This example loads input.html, finds every heading whose normalized descendant text contains Release, and prints each match. Text-based selection is a common reason to choose XPath instead of a CSS selector.

Query Text in an Existing HTML File

try (HTMLDocument document = new HTMLDocument("input.html")) {
    IXPathResult result = document.evaluate(
            "//h2[contains(normalize-space(.), 'Release')]",
            document,
            null,
            XPathResultType.Any,
            null
    );

    for (Node node; (node = result.iterateNext()) != null; ) {
        System.out.println(node.getTextContent());
    }
}

Steps to Run an XPath Query in Java

  1. Load the HTML source into an HTMLDocument.
  2. Write an XPath expression for the required text, attribute, position, or structural condition.
  3. Choose the document or a specific DOM node as the evaluation context.
  4. Call document.evaluate() and iterate matching nodes with iterateNext().
  5. Read the results, edit matched nodes , or continue with extraction or conversion.

Start with a broad query such as //img when a complex expression returns no result. Add predicates one at a time and confirm that the context node contains the structure expected by the expression.


When XPath Is Better Than CSS Selectors

XPath is the stronger choice when a query depends on relationships or values that are not represented conveniently by a CSS selector:

  • Match text content. Select headings, paragraphs, labels, or other elements whose normalized descendant text meets a condition.
  • Use ancestor information. Find a node only when it belongs to a particular article, section, table row, or other structural container.
  • Select by position. Address the first, last, or conditionally positioned node in a result set.
  • Limit evaluation to a subtree. Supply an existing DOM node as the context when a query should inspect only one region of the document.
  • Continue with document processing. Read values from matched nodes, edit them, save the document, or pass the same HTMLDocument to a converter.

Use CSS selectors for straightforward tag, ID, class, attribute, descendant, and child matching. Keep XPath for cases where its text predicates, axes, position tests, or context handling make the query clearer.


How Aspose.HTML Returns XPath Results

  1. The context node determines where evaluation starts. Use the document for a document-wide query or another selected node when evaluation should be limited to one subtree. An expression beginning with .// searches descendants relative to the supplied context node.

  2. XPathResultType.Any lets the implementation return a suitable result for the expression used on this page. For iterable node results, call iterateNext() repeatedly; it returns null after the last match and immediately when the query finds no nodes.

  3. evaluate() locates values or nodes but does not edit the document. Retrieved DOM nodes can be changed through the usual editing methods. A namespace resolver is required only when an expression contains prefixes that must be mapped to namespace URIs; ordinary unprefixed HTML queries generally do not need one.


XPath Documentation for Java


XPath Queries in Java FAQ

1. How can Java find an HTML element by text with XPath?

Use a text predicate such as contains(normalize-space(.), 'Release') in the XPath expression. Evaluating the expression returns matching DOM nodes whose normalized descendant text contains the requested phrase.

2. What does document.evaluate() return in Aspose.HTML for Java?

It returns an IXPathResult. The requested XPathResultType determines how the result is represented. For iterable node results, call iterateNext() until it returns null.

3. How do I select an HTML element by attribute with XPath in Java?

Add an attribute predicate to the XPath expression. For example, //a[@href] selects links that have an href attribute, while //input[@name = 'email'] selects input elements with that specific name.

4. What happens when an XPath query matches no HTML nodes?

For an iterable IXPathResult, the first call to iterateNext() returns null. Treat this as an empty result and do not cast, read, or edit a node until a match has been returned.


Install Aspose.HTML for Java

Add Aspose.HTML for Java from the official Aspose repository. Replace ASPOSE_HTML_VERSION with an exact version from the Aspose.HTML for Java releases page, then reload or rebuild the project so the dependency is resolved.

Add the repository and dependency to the Maven project:

Maven – pom.xml

<repositories>
    <repository>
        <id>AsposeJavaAPI</id>
        <url>https://releases.aspose.com/java/repo/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>com.aspose</groupId>
        <artifactId>aspose-html</artifactId>
        <version>ASPOSE_HTML_VERSION</version>
    </dependency>
</dependencies>

Add the repository and dependency to the Gradle project:

Gradle – build.gradle

repositories {
    maven {
        url = uri('https://releases.aspose.com/java/repo/')
    }
}
dependencies {
    implementation 'com.aspose:aspose-html:ASPOSE_HTML_VERSION'
}

Use a JDK compatible with the selected release. For manual JAR installation, Kotlin DSL, updates, and dependency troubleshooting, see Install Aspose.HTML for Java .

Related Java HTML Parser Guides

Compare CSS selectors, load a source, edit results, or extract data.