This page is a list of examples that you can use to write your own XPaths and XQueries. The examples on this page are limited in complexity.
XPath tests are used when using one of the configureAs functions or the configureProperties function. These tests are run the node that needs to be checked set as the context item.
Matching any node
Matching any element
Match an element having an "id" attribute
Match an element having an "id" attribute set to "node
self::element()[@id = "nodeA"]
Match hovercrafts full of eels
self::hovercraft[eel and not(*[not(self::eel)])]
Here you will find some examples for selecting nodes. Remember to take a look at the Selecting nodes page for more examples.
Selecting child nodes
Selecting child nodes is simple. If you want to select a child element of the context node, simply write its name. This is called a name test.
Child node selector
Abbreviated child node selector
Use a filter expression to only select child elements which, for example, have an id attribute.
Child node selector selecting a child with an id attribute
You can also use the filter expression to select a node at a given index.
Indices in XPath and XQuery are one-based instead of zero-based. This means that the first item in a sequence is located at index 1, the second item at index 2, and so forth.
The filter is part of the step expression. This might lead to unexpected results. Read more about why this happens on the Selecting nodes page.
Child node selector selecting the third child node
Selecting ancestor nodes
Select all ancestor having an attribute "id" set to "wrapper"
ancestor::ancestorNode[@id = "wrapper"]
Selecting descendant nodes
Following sibling axis
Preceding sibling axis
You can select nodes based on their node type.
Element kind test
Text node kind test
Processing instruction kind test
Comment kind test
Here we explicitly use the ancestor-or-self axis since a document node can never be a child node of any other node in a document.
Document node kind test
You can count the number of items in a sequence. You can do this by using the fn:count built-in function.
Count the number of child elements of the context node
Count the number of ancestor elements of a given node
let $givenNode := . return count($givenNode/ancestor::*)
Get the number of characters in a text node
let $givenTextNode := . return string-length($givenTextNode)
Count the number of preceding nodes to determine the index of the context node
count(preceding-sibling::node()) + 1