Building an XQuery Using the Mapper

This section describes how to build a new XQuery using Stylus Studio's XQuery mapper. This section covers the following topics:

Process Overview

The process of using the XQuery mapper to build a new XQuery consists of the following steps:

1. Create a new XQuery file in Stylus Studio ( File > New > XQuery File).
2. Click the Mapper tab in the XQuery editor.
3. Add one or more source documents.
4. Specify a target structure.
5. Map source document nodes to target structure nodes. As part of this step, you can optionally define function, FLWOR (For each, Let, Where, Order by, Return), If, and condition blocks to perform actions on source document nodes and map the return value to the target structure node.
6. Optionally, specify an XML document against which you want to test your XQuery.

Stylus Studio uses the information expressed on the Mapper tab to compose an XQuery that returns as its result an XML document that conforms to the structure represented by the target structure you specify.

Each of these steps is described in greater detail in the following sections.

Working with Existing XQueries

You can, of course, open an existing XQuery in Stylus Studio. When you do, the XQuery Source page displays the XML used to compose the XQuery, and the Mapper tab displays the source documents, target structure, and source-target mappings that can be inferred from the source XQuery file. All of the procedures described in this section can be performed on new or existing XQuery documents.

Source Documents

In Stylus Studio, a source document can be an XML document, an XML Schema (XSD), or a document type definition (DTD). The role of a source document is to provide Stylus Studio with a structure that it can use to compose the XQuery, based on how you map individual source document elements and attributes to nodes in the target structure. Stylus Studio infers the structure from the document you specify and displays this structure on the Mapper tab.

In this section

This section covers the following topics:

Choosing Source Documents

You can use one or more source documents to build an XQuery in Stylus Studio. You might want to select multiple documents if you need their elements or attributes to fully describe the target structure or the desired XQuery result content, for example.

If you choose an XSD or DTD document, you must also choose an XML instance document to associate with it. Stylus Studio uses the instance document associated with a XSD or DTD source document to generate the XPath document() function in the finished XQuery code. This document is also used to preview XQuery results.

For more information

See Source Documents and XML Instances to learn more about how Stylus Studio treats source documents. See Creating an XQuery Scenario to learn more about XQuery scenarios.

Source Documents and XML Instances

As described previously, Stylus Studio uses the source document you specify to infer a structure you can use to create mappings to the target structure. In addition to the document structure, Stylus Studio needs document content information in order to compose a complete XQuery. You provide this information by associating a XML instance to each source document you specify.

Association types

Source documents can have one of three associations, each of which has implications for the XPath expressions written by Stylus Studio when it composes the XQuery code. A source document can be associated with

  • Itself. That is, the document represented by structure displayed on the Mapper tab and the XML instance are one in the same. In this situation, Stylus Studio generates the document() function in the XQuery code. For example:


              for $book in document("file://c:\Program Files\Stylus Studio\examples\
simpleMappings\catalog.xml")/books/book
              
               

            

  • The XML document specified in the optional XQuery scenario. Only one source document can be associated with the XQuery scenario. In this situation, Stylus Studio does not generate the document() function in the XQuery code. For example:
  • for $book in /books/book

    The document() function is not necessary because Stylus Studio uses the XQuery input document specified in the Scenario Properties dialog box.

    By default, Stylus Studio uses the first XML document you add to the XQuery mapper as the source XML for the XQuery scenario, as shown here:

    Figure 273. Default Source Document

    The document specified in the Source XML URL field on the Scenario Properties dialog box is the document used to preview XQuery results. You can select this association for another XML document if you choose, but only one source document may have this association.

    Note

     

    Creating a scenario for an XQuery is optional. See Creating an XQuery Scenario.

  • Some other XML instance. A XSD or DTD document used as an XQuery source document must always be associated with an XML instance. In this situation, Stylus Studio generates the document() function in the XQuery code.

Source document icons

Stylus Studio uses different icons to indicate how a source document is associated with the other documents used to compose the XQuery.

Icon
Meaning
The source document is associated with itself. This is the default for most XML documents (and XML documents only).
The source document is associated with the XML document specified in the XQuery scenario. This is the case with the first XML document you add to XQuery mapper, but you can change this association manually if you choose. See How to Change a Source Document Association.
The source document is associated with a separate XML document instance. XSD and DTD source documents are always associated with an XML instance.
Table 70. Source Document Icons

How to Change a Source Document Association

To change a source document association:
1. Right click the source document whose association you want to change.

The source document shortcut menu appears.

2. Click Associate With, and then select the document you want to associate with the source document.

How to Add a Source Document

To add an XQuery source document to XQuery mapper:
1. Click the Mapper tab if necessary.
2. Click the Add Source Document button at the top left of the Mapper tab.

The Open dialog box appears.

3. Select the document you want to use as the source document for building the XQuery.
4. Click Open.

If you selected an XML document in step 3, the document appears in the source document pane of the Mapper tab. Go to step 5.

If you selected an XSD or DTD document, Stylus Studio displays the Choose Root Element dialog box.

Figure 274. Choose Root Element Dialog Box

You use this dialog box to associate the XSD or DTD with an XML instance.

Note

 

The Associate With field appears only when you add a second document to the XQuery mapper source and that document is an XSD or DTD. You use it to specify the XML instance that you want to associate with the XSD or DTD. This field does not appear if the XSD or DTD is the first source document you add to the XQuery mapper - Stylus Studio uses the XML Source document specified in the Scenario Properties dialog box as the XML instance in this case.

a. Select the element from the XSD or DTD document that you want to use as the root element. The Choose root element drop-down list displays elements defined in the document you selected in step 3.
b. Use the Browse ( ) button to specify the XML instance to which you want to map the root element you have selected. The root element of the XML document you select must be the same as the element you selected as the root element from the XSD or DTD document.
c. Click OK.

The document appears in the source document pane of the Mapper tab. Go to step 5.

5. To add another source document, return to step 2.

How to Remove a Source Document

Note

 

A source document cannot be removed from XQuery mapper if it is mapped to the target structure. See Removing Source-Target Map.

To remove a source document from XQuery:
1. Remove any maps from the source document to the target schema. (See Removing Source-Target Map if you need help with this step.)
2. Right click on the source document.

The source document shortcut menu appears.

3. Select Remove Schema.

How Source Documents are Displayed

A source document is represented using a page icon, and its name is displayed using a different color to help distinguish it from element and attribute names. The page icon is modified based on the source document's association with other documents. See Source Documents and XML Instances for more information on this topic.

By default, only the file name itself is displayed; if you want, you can display the document's full path by selecting Show Full Path on the document's shortcut menu. (Right-click on the document name to display the shortcut menu.)

Figure 275. Source Document Display

Source documents are displayed using the tree view; you can use your keyboard's *, +, and - number pad keys to expand and collapse selected documents.

Document structure symbols

Stylus Studio uses the following symbols to represent nodes in both source and target document structures:

Symbol
Meaning
Repeating element
Element
Attribute
Table 71.

See Source document icons to learn about the different ways source document icons are depicted.

Getting source document details

If you want details about the document that are not available in tree view, you can open the document by selecting Open from the document's shortcut menu. When you open a document this way, Stylus Studio displays it in its own editor (the XML editor if it is an XML document, for example).

Specifying a Target Structure

There are two ways to specify an XQuery target structure:

  • You can select an existing document from which Stylus Studio infers a structure and, optionally, modify the structure. Existing nodes in a target structure are displayed in blue. Nodes that you add are displayed in red.
  • You can build a structure from scratch, starting with the root element and defining other elements and attributes as needed. Nodes for target structures you define are displayed in red.

This section covers the following topics:

For more information

See Modifying the Target Structure to learn about the types of changes you can make to a target structure.

Using an Existing Document

To use an existing document to provide the XQuery target structure:
1. Click the Mapper tab if necessary.
2. Click the Set Target Document button at the top left of the Mapper tab.

The Open dialog box appears.

3. Select the document you want to use to provide the target structure for defining the XQuery.
4. Click Open.

The structure of the document you select appears in the target document pane of the Mapper tab.

Building a Target Structure

To build a target structure from scratch, you first create a root element, and then define child elements and attributes as needed.

How to create a root element
To create a root element:
1. Click the Mapper tab if necessary.
2. Right click the area underneath the Set Target Document button.

The target document shortcut menu appears.

3. Select Create Root Element.

The Name dialog box appears.

Figure 276. Name Dialog Box

4. Type a name for the root element and click OK.

The root element you specified appears in the target document pane of the Mapper tab.

Note

 

You can create elements and attributes in a new or existing target structure.

How to create elements and attributes
To create elements and attributes:
1. Click the Mapper tab if necessary.
2. Select the attribute or element to which you want to add a child element or attribute. If you have just created a root element, select the root element.
3. Right click the area underneath the Set Target Document button.

The target document shortcut menu appears.

4. Choose one of the following:
    • Add Attribute
    • Add Child Element
    • Insert Element After (This choice is not applicable to the root element; it creates the element as a sibling of the selected element.)
    • The Name dialog box appears.

      Figure 277. Name Dialog Box

5. Type a name for the node and click OK.

The node you specified is added to the target structure in the Mapper tab.

Modifying the Target Structure

This section describes the techniques you can use to modify the structure and content of an XQuery mapper target structure. It covers the following topics:

Adding a Node

See How to create elements and attributes.

Removing a Node

Note

 

Before you can remove a node, you must delete any links to that node. See Removing Source-Target Map.

To remove a node from the target structure:
1. Remove any links to the node you want to remove from the target structure. See Removing Source-Target Map if you need help with this step.
2. Select the node and press the Delete key.

Alternative: Right-click the node and select Remove Node from the shortcut menu.

Setting a Text Value

You can set text values for target structure elements and attributes. You might want to do this if you are composing an XQuery with an element or attribute that requires a fixed value, instead of using a value gathered from an input XML document.

Example

Here is the XQuery code Stylus Studio generates for the Title element when a text value is specified for it:

<Book>
               
	<Title>Confederacy of Dunces</Title>
               
</Book>
               

            

Stylus Studio displays a red letter T for nodes for which you define a text value: .

How to set a text value
To set a text value for a target structure node:
1. Right-click the node for which you want to set the text value.

The shortcut menu appears.

2. Select Set Text Value from the shortcut menu.

The Value dialog box appears.

Figure 278. Value Dialog Box

3. Type the string you want to use as the text value and click OK.

Mapping Source and Target Document Nodes

You map a source document node to a target structure node using drag and drop to create a link between the two nodes. Stylus Studio composes XQuery code based on these maps.

This section covers the following topics:

Preserving Mapper Layout

As you add function blocks to the XQuery mapper, Stylus Studio places them in the center of the mapper canvas. You can change the default placement of function blocks by dragging and drag and dropping them where you like. Stylus Studio preserves the placement you select within and across sessions (as you toggle between the mapper and the XQuery Source tab, for example).

As you use the splitter in the XQuery mapper to widen the source and target document panes, the size of the mapper canvas is reduced. The Fit in Mapper Canvas button ( ), located at the top of the XQuery mapper, redraws the diagram in whatever space is currently available to the mapper canvas. This feature is also available from the mapper short-cut menu (right-click anywhere on the mapper canvas to display the short-cut menu).

Left and Right Mouse Buttons Explained

You can use either the left or the right mouse button to perform the drag and drop operation used to create source-target mappings in XQuery.

If you use the left mouse button to perform the drag operation, the link always maps the source node to the target node, one-to-one, without making any changes to the target structure. If you use the right mouse button, Stylus Studio displays a shortcut menu that provides you with alternatives for modifying the target structure.

Figure 279. Displaying a Shortcut Menu

Using this menu, you can

  • Map a source document node to an existing target structure node - this menu choice, Map to This Node, is the same as creating the link using the left mouse button.
  • Add a source document node (element or attribute) as an attribute of the target structure node you select and map the two nodes.
  • Add a source document node as a child element of the target structure node you select and map the two nodes.
  • Add a source document node as a sibling of the target structure node you select and map the two nodes.
  • Copy the entire source document node - its structure and its content - to the target structure and map it.

How to Map Nodes

To map nodes:
1. Using either the left or right mouse button, drag the source document element or attribute to the appropriate node on the target structure.
2. When the pointer is on the appropriate target element, release the mouse button to complete the link.

Link Lines Explained

Stylus Studio draws lines for the maps you create from source document nodes to target structure nodes. Different line styles are used to convey information about the XQuery represented by the node mapping. There are three line styles:

  • Thin
  • Dashed
  • Thick

The sample files used to illustrate these styles are books.xml and catalog.xml, from the Stylus Studio examples\simpleMappings directory.

Thin line

A thin line indicates that the XQuery code generated by Stylus Studio copies content from the source node to the target node. Such a line is created when you map one element or attribute to another using the left mouse button, or any of the following choices on the map shortcut menu:

  • Create Root Element and Map It
  • Add Attribute and Map It
  • Add Child Element and Map It
  • Insert Element After and Map It

In addition, the structure required to navigate to the node is also generated if it does not already exist in the XQuery. For example, consider the map between the title element in books.xml and the Title element in catalog.xml:

Figure 280. Thin Lines in XQuery Mapper

This map results in Stylus Studio composing the following XQuery code:


              <Catalog>
               

              	<Book>
               

              		<Title>
               

              			{/books/book/title/text()}
               

              		</Title>
               

              	</Book>
               

              </Catalog>
               

            

The content is expressed as {/books/book/title/text(), and this statement is preceded by the structure needed to locate the title element content.

Dashed line

A dashed line indicates that only structure code is being generated. Such a line is created when you use a FLWOR or IF block. For example, consider the map between the book and Book repeating elements:

Figure 281. Dashed Lines in XQuery Mapper

A map involving a FLWOR block results in the following code:


              <Catalog>
               

              	{
               

              		for $book in /books/book
               

              		return
               

              		<Book>
               

              			<Title/>
               

              		</Book>
               

              	}
               

              </Catalog>
               

            

Notice that the FOR loop returns only structure (shown in italics), not content. To add content, we could also map the title element to the Title element, which results in the following:


              <Catalog>
               

              	{
               

              		for $book in /books/book
               

              		return
               

              		<Book>
               

              			<Title>
               

              				{$book/title/text()}
               

              			</Title>
               

              		</Book>
               

              	}
               

              </Catalog>
               

            

Of course, the FLWOR block can be used to define much more complex expressions, involving maps from source document nodes to its WHERE and ORDER BY ports, for example.

Thick line

A thick line indicates that the XQuery code generated by Stylus Studio replicates the complete structure and content of the source document node in the target. Such a map is created when you use the Copy Node choice on the link shortcut menu. Consider the following map - the bookid attribute on the source was copied to the target as a child of the Book repeating element:

Figure 282. Thick Lines in XQuery Mapper

For this type of map, Stylus Studio creates the XQuery code required to duplicate the source structure and content in the target, as shown in the following sample:


              <Catalog>
               

              	<Book>
               

              		{/books/book/@bookid}</Book>
               

              </Catalog>
               

            

Notice that the bookid attribute is displayed in gray in the target structure pane. This indicates that you cannot edit it.

Removing Source-Target Map

To remove a map from a source document node to a target element node:
1. Select the line that represents the map you want to delete.
Note

 

Select the portion of the line that is drawn on the XQuery mapper canvas.

2. Press the Delete key.

Alternative: Select Delete from the line shortcut menu (right click on the line to display the shortcut menu).

FLWOR Blocks

This section describes how to work with FLWOR blocks in the XQuery Mapper tab. It covers the following topics:

Parts of a FLWOR Block

FLWOR blocks are drawn as a green block with an illustration of a flower at its center, and five connectors, called ports, placed along the block's border:

Figure 283. FLWOR Block

For, Order by, and Return ports

You define a FLWOR statement's For and Order by clauses by mapping source document elements and attributes to them, as appropriate. For example, if you wanted your XQuery to return a list of books ordered by publication date, you would map the book repeating element in books.xml to the FLWOR block's For port, and the Return port to the Book repeating element in catalog.xml. (As an alternative, you could map the two repeating elements directly, and Stylus Studio would create the FLWOR block and this mapping for you automatically, as described in Creating a FLWOR Block). Next, you would map the source document pubdate attribute to the Order by port. For a FLWOR block defined in this way, Stylus Studio generates the following XQuery:


              <Catalog>
               

              	{
               

              		for $book in /books/book
               

              		order by $book/@pubdate
               

              		return
               

              		<Book/>
               

              	}
               

              </Catalog>
               

            

Where port

The input for the Where port must be the output port of another block, such as a condition, IF, or function block. Imagine you have two source documents - you can create an Equal condition block, and specify that the content of an element in one source document must match the content of an element in the other source document, and map the return value of this condition to the Where port on the FLWOR block. Creating an Equal condition that specifies that the bookid attribute must be equal to the title element results in Stylus Studio generating the following XQuery code, for example:


              <Catalog>
               

              	{
               

              		for $book in /books/book
               

              		where $book/@bookid = $book/title
               

              		order by $book/@pubdate
               

              		return
               

              		<Book/>
               

              	}
               

              </Catalog>
               

            

See IF Blocks and Function Blocks for information on using other types of blocks in XQuery mapper.

Flow port

The Flow port, which is also present on IF and function blocks, allows you to link the result from other FLWOR, IF, and function blocks to define a conditional execution order for your XQuery expressions. You might decide you want a particular For each statement executed only after performing a certain function, for example. Inputs for the Flow port include the Return port of IF, function, and other FLWOR blocks.

Creating a FLWOR Block

You can create FLWOR blocks in the XQuery Mapper tab in one of two ways:

  • Right-click on the mapper canvas and select New | FLWOR Block from the shortcut menu.
  • Map one repeating element to another - Stylus Studio automatically creates a FLWOR block, mapping the source document node to the For port, and the Return port to the target structure node. Consider this code, which Stylus Studio generated after mapping the book repeating element in books.xml to the Book repeating element in catalog.xml:
    
                          <Catalog>
                           
    
                          	{
                           
    
                          		for $book in /books/book
                           
    
                          		return
                           
    
                          		<Book/>
                           
    
                          	}
                           
    
                          </Catalog>
                           
    
                        

Function Blocks

Stylus Studio supports standard functions defined by the W3C and any user-defined functions you might have created. This section describes how to work with function blocks in Stylus Studio and covers the following topics:

Standard Function Block Types

Stylus Studio provides graphic support for the following types of XQuery functions:

  • Accessor
  • Aggregate
  • Boolean
  • Date time
  • Error
  • Node
  • Notation
  • Number
  • QName
  • Sequence
  • Sequence generator
  • String

If a standard function does not provide the functionality you need, create a user-defined function. See User-Defined Functions.

Creating a Function Block

The procedure for creating standard and user-defined function blocks varies slightly:

To create a standard function block:
1. Right-click on the mapper canvas.
2. Select New > Function Block from the shortcut menu. Available functions are displayed in submenu categories.
To create a user-defined function block:
1. Right-click on the mapper canvas.
2. Select New > User Functions from the shortcut menu.

Any user-defined functions defined in the XQuery source are displayed in a sublist.

See User-Defined Functions to learn more about creating user-defined functions in Stylus Studio.

Parts of a Function Block

Function blocks are drawn as a purple block with an italic "f" at its center, and connectors, called ports, placed along the block's border. Input ports (none or more based on the function), the Flow port at the top, and the Return port on the right:

Figure 284. Function Block

Input ports

Input ports are on the left side of the function block. The number and definition of input ports varies from function to function. To specify a value for an input port, drag a source document element or attribute to the port and release it.

Flow port

Flow ports, on the top of function blocks, are the same for FLWOR, function, and IF blocks. See Flow port.

Return port

The Return port is on the right side of the function block. You use the Return port to map the function result directly to a target structure element or attribute, or to a FLWOR, IF, condition, or another function block.

User-Defined Functions

You can define your own functions in XQuery, such as the following:


              define function total-price( $i as element) as xs:decimal
               

              {
               

                let $subtotals := for $s in $i return $s/quantity * $s/USPrice
               

                return sum( $subtotals )
               

              }
               

            

This particular user-defined function, which takes an element as its argument and returns a sum of the prices, might be used as follows (shown in italics):


              <Catalog>
               

              	{
               

              		for $book in /books/book
               

              		return
               

              		<Book>
               
			<Price>
               

              				{total-price($book/@bookid)}
               
			</Price>
               

              		</Book>
               

              	}
               

              </Catalog>
               

            

When you create a user-defined function, Stylus Studio adds it to the New > User Functions shortcut menu available when you right-click the mapper canvas.

Figure 285. User-Defined Functions

This makes it easy to reuse a user-defined function on the Mapper tab once it has been defined in the XQuery source.

concat Function Blocks

There are three types of concatenation ( concat) functions for strings:

  • concat() as string allows you to specify a literal value that you might wish to concatenate to some other value in your XQuery.

    Figure 286. concat() as string
  • concat($op1 as string?) as string allows you to specify a variable that you might wish to concatenate to some other value.

    Figure 287. concatn($op1 as string?)
  • concat($op1 as string?, $op2 as string?, ...) as string allows you to concatenate two or more variables.

    Figure 288. concat($op1 as string?, $op2 as string?, ...)
  • Note that only the first two input ports are associated with variables ( $op1 as string? and $op2 as string?). When you map a value to the third input port ( ...), Stylus Studio automatically adds a fourth input port to allow you concatenate a fourth value. This behavior is repeated for each additional string you define.

IF Blocks

IF blocks have a single input port, labeled condition; a Flow port; and two result ports: if then, and if else.

Figure 289. IF Block

You use IF blocks to compose if then, else XQuery expressions, such as the following:


              		<Book>
               

              			{
               

              				if( $book/title ) then
               

              					<Title/>
               

              				else
               

              					<ISBN/>
               

              			}
               

              		</Book>
               

            

This expression, for example, was composed by mapping

  • The title element in the source document to the IF block's input port.
  • The if then result port to the Title element in the target structure.
  • The if else result port to the ISBN element in the target structure.

IF blocks create a structure if the if then or if else branches are true. These ports can be connected to the target schema; otherwise they can be connected to Flow ports of FLWOR, function, and other IF blocks.

Condition Blocks

The Stylus Studio XQuery mapper allows you to graphically define the following types of conditions:

  • Equal (=)
  • Less than (<)
  • Greater than (>)
  • Less than or equal to (<=)
  • Greater than or equal to (>=)
  • and (&)
  • or (||)

All condition blocks have two input ports and a single Return port, as shown in this example of a greater than block.

Figure 290. Greater Than Block

You can map the Return port to a target structure element or attribute, or to the input port on a FLWOR, function, IF, or another condition block.

 
Free Stylus Studio XML Training: