What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Reverse XPath” has two different meanings. To move from a matched node toward its parent, ancestors, or earlier siblings, use a reverse axis such as ancestor or preceding-sibling. To reverse the order of items already in a sequence, use fn:reverse() when your XPath processor supports it. Neither operation automatically creates a general inverse of an arbitrary XPath expression.

First decide what “reverse” means

XPath addresses relationships in a hierarchical tree. A request to reverse an expression usually means one of these:

  • Reverse navigation: start at a selected node and move toward containing nodes or nodes that occur before it.
  • Reverse order: keep the same sequence items but return them from last to first.

These are different operations. Axis direction changes how a path finds related nodes; fn:reverse() changes the order of a sequence after it has been constructed.

Use reverse axes for navigation

XPath defines five reverse axes: parent, ancestor, ancestor-or-self, preceding, and preceding-sibling. They select nodes toward the context node’s containing elements or toward nodes that occur before it in document order.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Axis What it selects Typical use
parent The immediate parent node Move up one level
ancestor All containing ancestors, excluding the context node Find a containing section, form, or root element
ancestor-or-self The context node and all its ancestors Include the current element when testing a hierarchy
preceding-sibling Siblings before the context node Find the previous item or heading
preceding Most nodes before the context node, subject to XPath’s axis rules Search earlier parts of a document

A reverse axis is not a mathematical inverse of a path. It is a direction defined by the tree relationship at the current context node.

Get the nearest ancestor with ancestor::*[1]

Given a context node nested several levels deep, this expression selects its nearest ancestor element:

ancestor::*[1]

The important detail is predicate context. For a reverse-axis step, positions are evaluated in reverse document order. Position 1 therefore means the ancestor closest to the context node.

For example, if an input is inside a label, which is inside a form, ancestor::*[1] returns the label, not the form. To select a particular type, add a node test:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ancestor::form[1]

This finds the nearest containing form element, skipping unrelated ancestor types.

Why parentheses change the meaning of [1]

These expressions look nearly identical but select different nodes:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
ancestor::*[1]
(ancestor::*)[1]

In ancestor::*[1], the predicate belongs to the reverse-axis step, so position 1 is the nearest ancestor. In (ancestor::*)[1], parentheses first produce the axis result as a primary expression. The predicate is then applied to that result in document order, so it selects the first ancestor in document order (the outermost ancestor in a normal element hierarchy).

Use the first form for “nearest” and the parenthesized form when you intentionally need the earliest node in document order. This distinction also applies to other reverse axes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Find the nearest preceding sibling

To move to the closest earlier sibling named item, use:

preceding-sibling::item[1]

Because preceding-sibling is a reverse axis, its first predicate position is the nearest preceding matching sibling. A parenthesized version has different ordering semantics:

(preceding-sibling::item)[1]

That expression applies [1] after the axis result is formed, so it selects the first matching sibling in document order rather than the one immediately before the context node.

To select the second nearest preceding sibling, use:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
preceding-sibling::item[2]

To move upward and then test an ancestor’s attribute, keep the predicate on the step:

ancestor::section[@class = 'details'][1]

This selects the nearest ancestor section whose class is details.

Reverse a sequence with fn:reverse()

Sequence reversal is separate from tree navigation. In XPath versions that provide the function, write:

fn:reverse((1, 2, 3))

The result is the sequence (3, 2, 1). The function signature documented for XPath 2.0-and-later Saxon environments is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
reverse($arg as item()*) as item()*

You can reverse nodes returned by a path as well:

fn:reverse(/catalog/product)

This does not change the document tree and does not alter how predicates on the original path were evaluated. It only changes the order of items in the resulting sequence.

If your host supports XPath 1.0 only, fn:reverse() is unavailable. Browser DOM XPath evaluators and older embedded engines commonly expose a restricted XPath feature set. Check the runtime’s documented XPath version before using functions from XPath 2.0 or later. A host language may also expose only a subset of the standard axes.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

There is no automatic inverse for an arbitrary XPath

XPath has no operator that takes any expression and generates a path that “undoes” it. An expression can contain predicates, unions, functions, positional tests, variables, and context changes that do not have a single reversible path.

To write a path back toward a starting node:

  1. Identify the current context node and its actual relationship to the desired node.
  2. Choose the matching axis: parent for one level, ancestor for containment, or preceding-sibling for an earlier sibling.
  3. Repeat steps when the route has multiple relationships, for example parent::div/ancestor::main[1].
  4. Reapply the predicates that identify the intended target, and decide whether each positional predicate must remain on a reverse-axis step.

For example, if a selected button is inside a div inside a form, a route to the form can be expressed as:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ancestor::form[1]

If you need a particular related element rather than the nearest one, use a predicate that describes that element instead of assuming that reversing the original text is sufficient.

Document order versus axis order

Two ordering rules operate at once:

  • Predicate evaluation: reverse-axis steps use reverse document-order positions, which makes [1] mean “nearest” for ancestor and preceding-sibling.
  • Returned path result: the final result of an axis step is returned in document order, even when the step itself was a reverse axis.

This explains a common surprise: preceding-sibling::item[1] correctly selects the nearest preceding item, but a larger expression that returns several preceding siblings may present them in document order. Use fn:reverse() afterward if the consumer needs the sequence displayed in the opposite order.

Practical examples

Nearest containing element

ancestor::*[1]

Nearest containing table row

ancestor::tr[1]

Previous matching sibling

preceding-sibling::item[1]

All earlier siblings, then reverse their output

fn:reverse(preceding-sibling::item)

Include the current node while walking upward

ancestor-or-self::*[@data-region][1]

Here the reverse-axis predicate selects the nearest node, including the context node, that has the requested attribute.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting reverse XPath expressions

“[1] returned the wrong ancestor”

Check for parentheses. ancestor::*[1] means nearest ancestor; (ancestor::*)[1] means the first node in the resulting document-order sequence.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

“The function is unknown”

Your processor may implement XPath 1.0 or another restricted subset. Confirm the supported version and whether fn:reverse() is exposed. Replace sequence reversal with host-language code when the function is unavailable.

“The path returns no nodes”

Verify the context node, namespaces, and node test. An unprefixed name matches no-namespace elements in many XPath environments; namespaced XML requires a prefix bound by the host language.

“The order looks forward again”

Selection direction and output order are separate. A reverse axis can choose the nearest node while the returned node sequence is presented in document order. Apply fn:reverse() to the completed sequence when output order matters.

“The expression works in one tool but not another”

XPath is embedded in browsers, XSLT processors, databases, test tools, and XML editors with different version and feature limits. Check the host documentation rather than inferring support from the W3C XPath 3.1 Recommendation published on 21 March 2017.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Performance and reliability considerations

  • Use the narrowest node test and a selective predicate, such as ancestor::form[1] instead of collecting every ancestor and filtering later.
  • Keep positional predicates attached to reverse-axis steps when you need the nearest match; moving them outside parentheses changes both semantics and potentially the amount of data processed.
  • For large documents, avoid broad preceding::* searches when a sibling or ancestor relationship expresses the requirement more precisely.
  • Cache or reuse a compiled XPath where your host supports compilation, but validate the context node and namespace bindings for every evaluation.
  • Do not assume that a browser, database, or XSLT engine supports every XPath 3.1 feature. Version-check expressions during deployment, not only during local testing.

Or skip the browser setup

If your XPath work involves capturing a rendered page for debugging or documentation, ScreenshotNeo can return a screenshot or PDF through one GET request. It removes cookie-consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with the result identified by response headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Quick decision guide

Goal Use
Move to the immediate parent parent::*
Find the nearest ancestor ancestor::*[1]
Find the nearest preceding sibling preceding-sibling::*[1]
Choose the first ancestor in document order (ancestor::*)[1]
Reverse an existing sequence fn:reverse($sequence), if supported
Construct a general inverse path No automatic XPath operator; model the tree relationship explicitly

Frequently Asked Questions

Can I reverse an XPath string by writing its steps backward?

No. Reversing the text does not reliably identify the original node. Choose axes from the actual XML relationships and recreate necessary predicates.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does preceding-sibling::*[1] mean the first sibling in the file?

No. On the reverse axis it means the nearest preceding matching sibling relative to the context node.

Is fn:reverse() available in every XPath engine?

No. Its availability depends on the XPath version and host implementation; verify support before deploying it.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.