Predicate Blocks

A predicate allows you to filter data returned from an XQuery. For example, in books.xml, you might want to return only those books whose bookid attribute was within a specified range of values. In Stylus Studio, you can display (and create) predicates as predicate blocks in XQuery Mapper.

A predicate block in XQuery Mapper is rendered as a pair of binoculars. It has two input ports - Context (shown as data in the predicate block's tool tip) and Expression - and a single Return port, as shown in this example of a greater than block.

Enabling Predicate Blocks

You can create predicates in the XQuery source at any time, but if you want them displayed in the Mapper canvas and/or you want to be able to create them graphically, you need to first enable them.

To enable predicate blocks:
1. Select Tools > Options from the Stylus Studio menu.
2. Navigate to Module Settings > XQuery > Mapper.
3. Select the Display predicates in XPath expressions in the canvas option.

Predicates will be displayed in the next XQuery file you open in Stylus Studio.

Creating a Predicate Block

To create a predicate block:
2. Open an XQuery file.
3. Click the Mapper tab.
4. Right-click the Mapper canvas.
5. Select Conditional Block > XPath predicate.

Example

Following is a simple example that selects all books books.xml whose bookid attribute equals 2. This example uses the books.xml and catalog.xml files in the simpleMappings folder in the examples project.

2. Open an XQuery file.
3. Click the Mapper tab.
4. Drag and drop books.xml to the Add Source Document pane, and drag and drop catalog.xml to the Set Target Document pane.
5. Drag title to Title.
6. Right-click the Mapper canvas and select Conditional Block > XPath predicate.

The predicate block appears on the Mapper canvas.

7. Since we want to look for all book elements, drag book to the predicate block's Context port.

Next, we use the conditional block to create predicate expression (that is, "only those book elements whose bookid attribute equals 2").

8. Right-click the Mapper canvas and select Conditional Block > =.

The equal block appears on the Mapper canvas.

9. Drag bookid to the first input port on the equal block.
10. Double-click the second port on the equal block and specify 2 for the value.
11. Drag the output port on the equal block to the expression port on the predicate block.
12. Finally, drag the output port on the predicate block to the control port on the link connecting title to Title.

At this point, your diagram should look something like this.

As you can see, Stylus Studio created the predicate, [./@bookid = 2], as part of the XPath expression used to query books.xml. (Note that we defined the document using the variable $a to simplify the XPath expression.)

13. Preview the XQuery by clicking the Preview Result button ( ).

The result appears in the Preview window:

 
Free Stylus Studio XML Training: