XPath Predicates: Mastering Node Filtering in XML

Learn to use XPath predicates to precisely filter nodes in XML documents. This tutorial explains how to use predicates to refine node selection based on various criteria, making your XPath expressions more powerful and efficient. Master advanced XML querying techniques.



Using XPath Predicates for Node Filtering

XPath predicates are expressions enclosed in square brackets (`[]`) that filter node sets based on specified criteria. They're a very powerful way to refine your node selection in XML documents, making your XPath expressions more precise.

Understanding XPath Predicates

Predicates are added to an XPath expression to filter the nodes selected by that expression. They are very helpful when you need to select only specific nodes within a larger set of nodes. Only nodes that match the condition within the predicate are included in the result. Predicates are a powerful tool in XPath that helps us to target specific parts of our XML documents.

Predicate Syntax

The basic syntax for a predicate is:


node[condition]

This selects `node` elements only if the `condition` is true for that node. The `condition` can be any valid XPath expression.

Examples of XPath Predicates

(Note: These examples assume an XML document similar to the one shown in the original text. Screenshots from the original text are not included here. Please refer to the original document for visual verification of the XPath expressions' results. The descriptions below aim to convey the information in those screenshots.)

Index XPath Expression Description
1 /class/employee[1] Selects the first `employee` element that is a child of the `class` element.
2 /class/employee[last()] Selects the last `employee` element that is a child of the `class` element.
3 /class/employee[@id = '002'] Selects the `employee` element where the `id` attribute is '002'.
4 /class/employee[salary > 10000] Selects `employee` elements where the `salary` child element's value is greater than 10000.

Example: Generating an Employee Table

(Note: This example assumes an XML document named `employee.xml` and an XSLT stylesheet named `employee.xsl`. Screenshots from the original text are not included here. Please refer to the original document for visual verification of the XPath expressions' results and the XSLT output. The descriptions below aim to convey the information present in those screenshots.)

This example demonstrates using predicates within an XSLT stylesheet to iterate over employee elements and display their details in an HTML table.

(The original content includes the `employee.xml` and `employee.xsl` files. Since we cannot display the files here, please refer to the original document for the file content.)

Test it Now