Class XPathExpression

java.lang.Object
eu.maveniverse.domtrip.XPathExpression

public class XPathExpression extends Object
Mini-XPath expression support for string-based element queries.

Compiles a subset of XPath expressions into efficient element queries that can be evaluated against any element in a DomTrip document tree. This provides a convenient string-based alternative to the programmatic ElementQuery API.

Supported Expressions:

Path navigation
foo/bar/bazDirect child path
//fooDescendant-or-self (search anywhere below)
foo//barbar anywhere under foo children
.Current element
..Parent element
*Any element (wildcard)
Predicates
foo[@attr]Element with attribute present
foo[@attr='value']Element with attribute equal to value
foo[bar='text']Element with child text content
foo[1]First element (1-based)
foo[last()]Last element

Usage Examples:

// Compile once, reuse many times
XPathExpression expr = XPathExpression.compile("//dependency[@scope='test']");
List<Element> results = expr.select(root);
Optional<Element> first = expr.selectFirst(root);

// Or use convenience methods on Element
List<Element> deps = element.select("dependencies/dependency");
Optional<Element> match = element.selectFirst("dependency[groupId='junit']");

// Or on Editor
List<Element> allDeps = editor.select("//dependency");

What is NOT Supported:

  • Full axis specifiers (preceding-sibling::, ancestor::)
  • XPath functions (contains(), normalize-space())
  • Boolean operators (and, or)
  • Arithmetic operators
  • Union operator (|)
Since:
1.3.0
See Also:
  • Method Details

    • compile

      public static XPathExpression compile(String expression)
      Compiles an XPath expression string into a reusable XPathExpression.

      The compiled expression can be evaluated multiple times against different context elements without re-parsing.

      Parameters:
      expression - the XPath expression to compile
      Returns:
      a compiled XPathExpression
      Throws:
      DomTripException - if the expression is null, empty, or syntactically invalid
    • select

      public List<Element> select(Element context)
      Evaluates this expression against the given context element and returns all matching elements.
      Parameters:
      context - the element to evaluate the expression against
      Returns:
      a list of matching elements, never null
    • selectFirst

      public Optional<Element> selectFirst(Element context)
      Evaluates this expression against the given context element and returns the first match.
      Parameters:
      context - the element to evaluate the expression against
      Returns:
      an Optional containing the first matching element, or empty if none found
    • expression

      public String expression()
      Returns the original expression string.
      Returns:
      the expression string
    • toString

      public String toString()
      Overrides:
      toString in class Object