How to Use XPath Wildcard
When writing XPath expressions, you don't always know or need to specify the exact name of the nodes you want to select. Wildcards provide a powerful way to write more flexible and robust path expressions that can select unknown or varying XML nodes.
note
XPath wildcards can be used to select unknown XML nodes.
XPath Wildcard List
XPath defines the following wildcards on nodes to be used with the XPath expressions.
| Wildcard | Expression |
|---|---|
* | to match any element node. |
. | to match the current node in context. |
@* | to match any attribute node. |
node() | to match node of any type. |
note
The node() wildcard is more general than *. While * only matches element nodes, node() will match any type of
node: elements, text, comments, processing instructions, etc.
Example
Consider the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">A Great Book</title>
<author>Tom Nolan</author>
<price>19.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<author>Tutorial Reference</author>
<price>29.99</price>
</book>
</bookstore>
In the following table there are some examples of selection:
| Example | Result |
|---|---|
//* | Matches ALL nodes in the input XML document |
/bookstore/* | Matches all child nodes of bookstore. In this example the only child nodes are book. |
/*/category | Matches all book nodes as children of the root node (bookstore). If there are nodes other than book under the bookstore node then this expression will only return the required book nodes. |
attribute::* | Selects all attributes of the current node |
//*[@*] | Matches ANY element node which has an attribute defined. This example will only match title nodes. |
//title[@*] | Matches only title element nodes with an attribute defined. |