How XPath Wildcards Asterisk and @* Work

XPath wildcards allow you to query XML documents when element or attribute names are unknown, variable, or need to be selected collectively. In XML XPath navigation, the principal wildcards are the asterisk (*) for element nodes and the at-asterisk (@*) for attribute nodes. This guide explains how these wildcards function, their syntax, and practical examples of their usage in navigating XML data structures.

The Element Wildcard: *

The asterisk (*) wildcard matches any element node at the specified location path, regardless of its tag name. It does not select text nodes, comments, processing instructions, or attributes.

Common Usage Patterns for *

The Attribute Wildcard: @*

The at-asterisk (@*) wildcard matches any attribute node within an element. It ignores the specific attribute name and targets the attribute itself or tests for its presence.

Common Usage Patterns for @*

Differences Between *, @*, and node()

To avoid common pitfalls in XML navigation, it is important to distinguish between wildcards and node-type tests:

Pattern Target Match Ignores
* Any element node Attributes, text, comments, processing instructions
@* Any attribute node Element nodes, text, comments
node() Any node type (elements, text, comments) Attribute nodes

Practical XML Example

Consider the following XML snippet:

<store>
  <product id="101" category="electronics">
    <name>Laptop</name>
    <price currency="USD">999.99</price>
  </product>
  <product id="102">
    <name>Desk</name>
    <price>149.99</price>
  </product>
</store>