XML Tutorial

Xpath tutorial, xslt tutorial, xquery tutorial, xsd data types, web services, xquery syntax.

XQuery is case-sensitive and XQuery elements, attributes, and variables must be valid XML names.

XQuery Basic Syntax Rules

Some basic syntax rules:

  • XQuery is case-sensitive
  • XQuery elements, attributes, and variables must be valid XML names
  • An XQuery string value can be in single or double quotes
  • An XQuery variable is defined with a $ followed by a name, e.g. $bookstore
  • XQuery comments are delimited by (: and :), e.g. (: XQuery Comment :)

The XML Example Document

We will use the "books.xml" document in the examples below (same XML file as in the previous chapters).

View the "books.xml" file in your browser .

XQuery Conditional Expressions

"If-Then-Else" expressions are allowed in XQuery.

Look at the following example:

Notes on the "if-then-else" syntax: parentheses around the if expression are required. else is required, but it can be just else ().

The result of the example above will be:

XQuery Comparisons

In XQuery there are two ways of comparing values.

1. General comparisons: =, !=, <, <=, >, >=

2. Value comparisons: eq, ne, lt, le, gt, ge

The difference between the two comparison methods are shown below.

The following expression returns true if any q attributes have a value greater than 10:

The following expression returns true if there is only one q attribute returned by the expression, and its value is greater than 10. If more than one q is returned, an error occurs:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

XQuery by Priscilla Walmsley

Get full access to XQuery and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Variable Declarations

Variables can optionally be declared (and bound) in the query prolog. If a variable is bound within an expression in the query body, it does not have to be declared in the prolog as well. For example, you can use the expression let $myInt := 2 in the query body without declaring $myInt in advance. $myInt is bound when the let expression is evaluated.

However, it is sometimes necessary to declare variables in the prolog, such as when:

They are referenced in a function that is declared in that module

They are referenced in other modules that import the module

Their value is set by the processor outside the scope of the query

Declaring variables in the prolog can also be a useful way to define constants , or values that can be calculated up front and used throughout the query. It's important to remember that global variables (prolog-declared variables) are immutable, just like other XQuery variables.

Variable Declaration Syntax

The syntax of a variable declaration is shown in Figure 12-4 . For example, the declaration:

binds the value 12 to the variable $maxItems .

Syntax of a variable declarationThe optional as clause, useful for static typing, is described in

Figure 12-4. Syntax of a variable declaration [ a ]

A previous draft of the XQuery recommendation specified the following syntax for variable declarations:

Some popular XQuery implementations still use this old syntax.

The Scope of Variables ...

Get XQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

xquery variable assignment

Use XQuery from a Java Environment Example Tutorial

  • Search documents with XQuery from Java applications

Article by:  Brett D. McLaughlin, Sr.  ([email protected]), Author and Editor, O'Reilly Media, Inc. April 29, 2008 View the original article

XML data format can be hard to search, but with the fairly recent introduction of the XQuery API, XML searches are now flexible and easy to perform. For Java™ programmers who work with XML documents using SAX, DOM, JDOM, JAXP, and more, the XQuery API for Java is a welcome addition to the programmer's toolkit. Now the power of XQuery is available to Java programmers without resorting to system calls or unwieldy APIs, all in a Sun-standardized package.

  • SQL databases, XML data, and queries, oh my!

While the world of programming—and particularly Java programming—seems to increase, the number of standardized choices is growing as well. In other words, more and more APIs blessed or approved by Sun are available. The result of this standardization is that an increasing number of developers are branching out beyond their core competencies, and learning new technologies.

High on the list of interesting and worthwhile tools and APIs to master are those that deal with data. No matter how cool or clever an application, it's ultimately only as useful as its ability to work with data. And, while the number of APIs constantly expands, the popular and commonly used number of data formats steadily decreases. While some data managers still use object-oriented database management systems, or XML-driven databases, relational databases (RDBMSs) have weathered that storm, and still seem the choice of most data managers. That leaves the Java developer with JDBC (for database connectivity) or perhaps JDO (Java Data Objects) to interact with SQL databases.

Data not in databases has also almost all standardized on XML as a data format. XML is robust, albeit verbose, and there are perhaps more APIs for working with XML than any other non-Java medium in the language. Whether it's parsing, data binding, or transforming, if your application can't deal with XML, then it's considered limited and perhaps even a bit behind the times.

These two seemingly unrelated facts—the propensity for data to live in SQL databases and the popularity of XML for all data outside of a database—has created some unique problems, though. SQL databases are easy to query; XML documents are not. Consumers expect to be able to search through data easily, and while this works nicely with data in databases, it's not so trivial with data in XML documents. Obviously, taking XML-formatted data and dumping it into a database just to make searching easier is the wrong approach. And that's where XQuery—and as a corollary, the XQuery API for Java (XQJ) comes in.

  • XQuery: A three-part technology

XQuery, at its simplest, is a language used to define searches of XML documents. Much as SQL gives specific meaning to SELECT and FROM—in a particular context—XQuery defines a meaning for forward slash (/0 and at-sign (@), as well as a host of other keywords and key-characters.

At its heart, though XQuery is made up of three components:

  • The XPath specification: a means to select zero, one, or multiple nodes in an XML document
  • Additional syntax to select a particular XML document, and to add selection criteria to the nodes returned from an XPath
  • An API—like XQJ, the XQuery for Java API—that evaluates XQuery expressions in a specific programming language

To really master XQuery, you need a solid grasp of all three of these components. For the Java programmer, that obviously means learning XPath, learning the additional XPath syntactical constructs, and then wrapping all of this up in a Java-based API to issue XQuery expressions to an XML document.

The good news is that the XPath and XQuery syntax is fairly intuitive. If you've ever navigated a directory structure in a UNIX® shell, a Mac OS X terminal, or a DOS window, you're way ahead of the game. Add to that basic use of operators like less than (<), greater than (>), and equals (=), and you're over half of the way to being an XPath pro.

  • XPath Basics

XQuery actually depends almost entirely on another XML specification, the XPath spec. XPath isn't about functionality as much as defining a way to create  paths  that refer to parts of an XML document. For example, the XPath /play/act/scene translates to all of the scene elements nested within an act element, nested within the play root element.

XPaths are relative

Basic XPaths use element names and forward slashes. And by default, an XPath begins with your current location in an XML document. So if you use the DOM, for example, and navigate to a speech element, and then you issue the path speaker, that evaluates to any speaker elements within the speech element that is your current location. So an XPath evaluates relative to your location in a document.

Moving away from the current node

To move to the root of a document, precede your path with a forward slash. So /play looks for the root element called play, no matter where in a document you are. And you can select a parent element of the current element with ../. In fact, this should start to look a lot like a directory structure. So the path ../../personae/title would go two levels up from the current element, then look for a personae element, and then a title element nested within that.

Selecting attributes

You can select a lot more than just elements. Consider an XPath like this: /cds/cd@title. This returns all attributes named "title" that are on cd elements, nested within a root element named cds.

Remember that the @ syntax doesn't return the value of an attribute, but the attribute itself. So @isbn would select all attributes named isbn, not the  value  of those attributes. Additionally, in XPath, the term attribute refers to the attribute's name and value.

Selecting text

Just as you can select elements and attributes, you can select the text within elements. If your XPath ends in an element name, like /cds/cd/title, then you're selecting elements—and those elements do  not  include the text within those elements. However, if you want the text within an element, use the text() syntax. So for all the textual titles of a set of CDs, you can use a path like /cds/cd/title/text(). So that path doesn't give you any elements; it gives you the text within the indicated elements.

XPath selects sets of nodes

One of the keys to effectively using XPath is to realize that an XPath always evaluates to a  node set . That set might have zero, one, or multiple nodes, but the result of an XPath is  always  a set. That flies in the face of what most people think when they write XPaths: that the path returns an element, or an attribute, or some text. However, that's not at all the case.

If you use the DOM, you've thought of nodes before. In the DOM, everything in an XML document—elements, attributes, text—is a node. An element is an element node; an attribute (and its value) is an attribute node; even text within an element is a text node. So a path like ../../personae/title, which ultimately results in selecting title elements, actually returns a node set. The set might have zero (there are no matching elements), one, or more nodes. In this case, all of those nodes will be elements named "title."

As your paths get more complex, and potentially select wider sets—perhaps including attributes and elements at the same time, or text and elements—those paths still ultimately are just choosing node sets. Keeping that in mind is key to using XQuery properly. By using XPath, you select a set of nodes; and with XQuery, you then typically select a subset of those nodes with a search criteria, or potentially joining multiple sets of nodes and then applying a search criteria. By keeping in mind that a set can have more than one type (elements, text, or attributes), you'll be able to write those paths a lot better, and ensure they evaluate to what you want.

  • Becoming more selective with XPath

You've seen how to select sets of nodes based on the names of those nodes (in the case of elements and attributes) as well as the parents of those nodes (in the case of text, or when you select all child nodes of a given parent). On its own, that's pretty powerful; but XPath offers quite a bit more in terms of selectivity, all using what's called a  predicate .

Predicate Basics and Syntax

A predicate is a partial expression that can be applied to an existing node set. Predicates are placed with square brackets, [ and ]. They're applied to the node set indicated by the path to the left of the predicate. For example, consider the path /cds/cd; this selects all cd elements within the root element named "cds." Then supposed you want the first CD; you can use a predicate to get that CD, like this: /cds/cd[1]. This returns the first of the nodes selected by the path /cds/cd.

Predicates can be applied to any node set

Remember, a predicate applies to the node set to the left of the predicate itself. However, that doesn't mean that a predicate can only appear at the end of a complete XPath. Consider that an XPath itself is really a collection of paths, each returning a node set, and later portions of the path refining or acting on that set. So /cds/cd/title is really three paths:

  • /cds, which returns the root element, named "cds" (a set which contains one element node)
  • cd (relative to the previous node set), which returns all cd elements nested within the previous node set
  • title (again relative to the previous node set), which returns all title elements nested within the previous node set

A predicate must be applied to a node set, but it can be applied to  any  node set. So here's a completely legal path: /cds[1]/cd[2]/title[1]. This selects the first of the node set selected by /cds; the second of the nodes selected by /cds[1]/cd; and then the first of the nodes selected by /cds[1]/cd[2]/title.

Note:  Parts of this path are essentially meaningless; for example, selecting a root element using / and then applying the [1] predicate will always return the first (and only) element in the set. The only time this predicate won't return an element is if the node set itself is empty, when the root element indicated is not named the same as a document's actual root element. But, for illustration purposes—and from a technical standpoint—there's nothing wrong with the XPath itself, or the predicates used.

Going beyond numeric indices in a predicate

Of course, an API that only let you reference sites with numeric values would be pretty limited. You're forced in that model to always know exactly where in the set the items you want are. XPath offers a lot more than that, though. For starters, you can use the last() function in your predicates to select the last item in a set, no matter how many total items are in the set. So /cds/cd[last] selects the last cd in a document.

You can also select all the items that are less than a certain position, or greater than a certain position, using the position() function. The position() function returns the position in a set of a given node. For example, suppose you want the first 5 CDs; you could use the path /cds/cd[position()<6]. This selects all the nodes where position() evaluates to less than 6.

Selecting nodes based on data

Finally—in this short introduction to XPath, although not in a complete discussion of XPath—you can select nodes based on child elements of the nodes, or on attributes of the node. Just as each progressive portion of an XPath is based on the set of nodes determined by the preceding path, the predicate of a set is based on the set that you apply it to. Add to that a predicate's ability to use operators like less than (<) and greater than (>), and you can be quite selective based on data within selected nodes, not just the position of those nodes within an overall set.

So suppose you want all CDs that have an attribute named "style" with a value of "folk." You'd use an expression to first select all the CDs, and then compare the style attributes of those CDs to the value "folk." In XPath, that looks like /cds/cd[@style='folk']. This is pretty self-explanatory based on what you've seen so far. First, a set of nodes is selected through /cds/cd. Then, the attributes of each node named "style" are isolated using the partial predicate @style. Just as discussed earlier, preceding a name with @ indicates an attribute. And that attribute is assumed to be relative to the set of nodes already chosen (in this case, all the cd elements). Then the value of these attributes is compared to a string, "folk." The ones that have matching attributes are returned; everything else is tossed out of the result set.

The same can be done with nested elements of the set selected. Suppose you have a document structured like that in Listing 1.

Listing 1. Structure of a sample CD listing document <cds> <cd style="some-style"> <title>CD title</title> <track-listing> <track>Track title</track> <!-- More track elements... --> </track-listing> </cd> <!-- More CDs... --> </cds>

Now suppose you want all CDs with 10 or more tracks. What you want to do is select all the CD elements, which involves this path you've seen a number of times: /cds/cd. Then, using a predicate, you want to get a count of a particular node set relative to the set you've chosen; in this case, you want to select all of the track element nodes, which are nested in a track-listing element, nested within the node set you're actually wanting to have returned. Finally, you want to apply a count of those nodes, which XPath lets you conveniently do with the count() function. Last, but not least, you need to compare that count with a number, here, 10. Put all this together, and you get a path and predicate like this: /cds/cd[count(track-listing/track) >= 10].

A note on the contradictions within XPath predicates

If you've read carefully, you might note some inconsistencies in how XPath treats element text and attributes here. Earlier, I talked about an attribute node being both the attribute and its value, treated as a single unit of information. However, in a predicate, an expression like @type refers not to the entire type attribute node, but to just the value of that attribute. That allows you to compare that value to other values (as in @type='reggae').

In the same way, you can reference the text in an element within a predicate like this: /cds/cd[title='Revolver']. Here, the value of the type element, nested within cd, is compared to the value "Revolver." And, just as in the case of attribute nodes, some of the standard rules of thinking about elements are broken. In general, an element node is the parent of a text node; but here, the predicate essentially de-references the text within an element.

These slight aberrations in the rules aren't a problem, as long as you know they exist, and can switch between the two approaches to thinking about elements and attributes. You just need to always be clear when an attribute and its value are considered as one node, and when you reference the value of an attribute; similarly, know when an element contains other text nodes, versus when its text can be compared to another value.

  • Adding XQuery to the mix

XPath is incredibly powerful, but has some limitations. First and foremost, it's largely suited for static data. In other words, you construct an XPath query for a specific document, with a specific set of data that you're comparing elements, attributes, and text to using predicates and XPaths. Additionally, XPath doesn't have any control structures (like if/else statements) or the ability to perform processing beyond simply comparisons.

To be fair, these limitations aren't a big deal for most non-programmers. But take a Java (or C#, or Python) programmer, with the power of an entire programming language, and they'll quickly come up with ideas for searches in XML documents well beyond what XPath alone offers. That, of course, is where XQuery comes in.

Begin by selecting your document

One of XQuery's little-used, but most important features is its ability to indicate the document to apply an XPath to. So where, in XPath, you'd apply a path like /cds/cd[title='Revolver'] to a specific document, you can indicate the document in your actual XQuery using the doc() function. So if you wanted to search  catalog.xml , you'd use the XQuery expression doc("catalog.xml")/cds/cd[title='Revolver'].

The power of that little function is the ability to write code that selects a document programmatically (perhaps based on user input), or to loop through a set of documents (maybe all the iTunes catalogs on a network), and apply the statement to each easily.

  • XQuery and FLWOR

Of course, XQuery offers a lot more than simple runtime document selection. It's most powerful when you harness what's often called its FLWOR capabilities. FLWOR is an acronym for "for, let, where, order by, return." These are all clauses you can use in your XQuery expressions to get more precise results.

For SQL veterans, you should already begin to feel a little more comfortable. WHERE and ORDER BY are both common parts of SQL queries. And for programmers, the term for should look familiar. Here's the brief rundown on what FLWOR clauses do:

  • for: You can use for to take a node set and iterate over it. In many ways, for is the assignment of a variable to the current value in a node set, so you can operate on that variable.
  • let: You assign values to variable with let, although (as you'll soon see) you won't use let as often as you use the other FLWOR clauses.
  • where: where lets you apply selection criteria to a node set, beyond what XPath offers. Of course, in many queries, you'll see that where isn't doing more than XPath; it's just moving the predicate on an XPath to a different place.
  • order by: The order by clause doesn't change data, or filter it; it just applies an ordering to a result set, and allows you to sort values based on something other than the location used in the XPath itself.
  • return: Using a return clause lets you operate on a node set, but then return (in results) something other than that node set. You might want to select a set, order and filter it, and then return only the child elements of the results; return is the key that makes that possible.

Let's take a little more in-depth look at each of these clauses.

Using for clauses

The for clause is used almost identically as it is in programming languages like Java and C#. Here's the format of the clause:

for $variable-name in XPath ...

The variable name can be any normal identifier, like x. Normally, variables are best named by their use (like firstName or title), but as this variable is essentially a loop counter, using single letters is also fine.

The XPath can be anything you want. /cds/cd is a perfect example. So you might have something like this:

for $cd in doc("catalog.xml")/cds/cd ...

That's it. Now the variable $cd will take on the value of each node returned by the XPath /cds/cd. Here, the ... represents the rest of the XQuery expression, which I'll get to next.

For programmers, this statement is really no different from this:

for (int i = 0; i <cdArray.length; i++) { CD cd = cdArray[i]; // Process CD }

Or, for lists:

for (Iterator i = cdList.iterator(); i.hasNext(); ) { CD cd = (CD)i.next(); // Process each CD }

Assigning variables using let

Putting aside the XQuery above for a moment, the let clause is used to assign variables. You've already seen in XQuery that a variable is defined by putting a dollar sign ($) in front of an identifier name. You most often will use variables in XQuery as shown above, though, where the variable is created implicitly by a for clause, rather than explicitly with a let clause.

However, suppose you want to use an explicit variable. You could do something like this:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd ...

Here, the document to search within is assigned to a variable. Assignment in XQuery uses :=, which—unless you've used Pascal in your youth—might look a bit odd. Putting this in a more realistic context, though, you might have a function that iterates over a list of XML documents, and assigns to $docName each of those document names in turn. You can then select each cd element in  each  of the documents in that larger list, and process each in the same way.

Completing a query with the return clause

Let's jump out of the ordering imposed by FLWOR for a moment, in order to complete a query. So far, you've got:

Next up is returning something. This query selects all the cd elements, but returning that isn't very useful—even though it's exactly the node set that's desired. Instead of returning those elements, suppose you want something more identifiable; perhaps the title of each CD, stored in the title element. That's where return comes in.

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd return $cd/title/text()

Here, the selection of all cd elements is made. Then, each of those resulting nodes is assigned to $cd in turn. Finally, the return clause returns not that element itself, but a child element named "title," which contains the target data.

Be sure  not  to make a simple mistake and write your query like this:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd return /cds/cd/title/text()

This has three significant problems:

  • First, it defeats the purpose of XQuery; you just return an XPath location, rather than do any querying.
  • Second, you return data regardless of doc($docName), which indicates which document to select the CDs from.
  • Finally, and most importantly, this will ignore any filtering or ordering you perform on the node set returned by the for clause.

You're about to build some of that next, so this will become more obviously important shortly. For now, though, always ensure you have the variable defined in your for clause reappearing in your return clause. That simple rule of thumb will help you ensure your queries behave like you expect.

Get selective with where

Using where allows you be more selective with XQuery. Using a where clause in XQuery works just as it does in SQL; you add the where clause to your selection in order to refine the result set. Here's a very simple example:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd where $cd@type = 'reggae' return $cd/title/text()

This returns all the titles of the reggae CDs. There's little here to explain; the where clause is pretty straightforward. But you can apply more complex conditions with and:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd where $cd@type = 'reggae' and count($cd/track-listing/track) > 10 return $cd/title/text()

This returns all the reggae CDs with more than 10 tracks.

One more important type of where clause usage is where you' essentially perform a join. Suppose you have an XML file set up something like Listing 2.

Listing 2. Expanded structure of a CD listing document

<cds> <cd style="some-style"> <title>CD title</title> <artist id="289" /> <track-listing> <track>Track title</track> <!-- More track elements... --> </track-listing> </cd> <!-- More CDs... -->

<artists> <artist id="289"> <firstName>Bob</firstName> <lastName>Marley</lastName> </artist>

<!-- More artist elements --> </artists> </cds>

This expands on the XML structure shown in Listing 1. It adds artist elements, identified by an id attribute, and related to each CD by at least one artist element nested within each cd element.

With XQuery, it's possible to perform what amounts to a join between CDs and their artists. Here's an example:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd, $artist in doc($docName)/cds/artists/artist where $cd/artist/$id = $artist/$id and $artist/lastName = 'Marley' return $cd/title/text()

Two things go on here. For the first time, you see that a for clause can define more than one variable. Instead of just identifying CDs, this statement also defines $artist, so it's easy to work with the set of artist elements.

Then, the where clause essentially joins CDs with their artists with this line: where $cd/artist/$id = $artist/$id. Remember that this matches each CD with each artist, producing the equivalent with a SQL join. Then, further selection is defined: $artist/lastName = 'Marley'. So this selects all the artists who have a last name of "Marley." But remember, there's also a join here, and the return clause returns the CD titles. So you get all the titles of the CDs who have an artist whose last name is "Marley."

This is where XQuery really comes into its own. You can perform complex SQL-like joins and selections, all applied to XML documents (many of which probably weren't structured with advanced searching in mind).

Ordering your node sets

If where works  mostly  like its SQL counterpart, then order by works  exactly  like its SQL counterpart. You can order your results by anything you can reference using XPath:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd, $artist in doc($docName)/cds/artists/artist  where $cd/artist/$id = $artist/$id and $artist/lastName = 'Marley' order by $cd/release/@date return $cd/title/text()

Here, the returned CD titles are ordered by the date attribute on a child element of each CD, release. By default, sorting is done in ascending order; you can make that explicit if you want, though:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd, $artist in doc($docName)/cds/artists/artist where $cd/artist/$id = $artist/$id and $artist/lastName = 'Marley' order by $cd/release/@date ascending return $cd/title/text()

And of course you can sort in descending order. In this case, that would return the most recently released CDs first:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd, $artist in doc($docName)/cds/artists/artist where $cd/artist/$id = $artist/$id and $artist/lastName = 'Marley' order by $cd/release/@date descending return $cd/title/text()

Note:  If you don't use a schema or XQuery processor that knows that the date attribute is a date type, you can get errors with this statement. Worse, it might get ordered by treating the dates as textual data, and alphabetizing them. Almost all modern processors will handle dates, though, so this is rarely a concern.

You can also include more than one criteria for sorting. For example, the current expression returns all CDs by any artist with a last name of "Marley" (not just Bob), and interleaves them when it sorts by release date. You could refine the expression to sort by the artist's name, and then release date:

let $docName := 'catalog.xml' for $cd in doc($docName)/cds/cd, $artist in doc($docName)/cds/artists/artist where $cd/artist/$id = $artist/$id and $artist/lastName = 'Marley' order by $artist/firstName, $cd/release/@date return $cd/title/text()

Note that sorting by $artist/lastName before $artist/firstName is redundant, since the results all have the same last name value.

  • Adding Java technology to the mix

It might seem like you've read a lot of introduction just to get to the part on using XQuery from a Java environment. However, most programmers who pick up XQJ (the acronym frequently used for Java's XQuery API) are at best passingly familiar with XPath and XQuery. Now that you've learned a bit more than the basics, you're ready to use these expressions from your Java programs.

The XQuery spec is vendor-neutral

The XQuery for Java API is under Sun's auspices, being developed as part of the Java Community Process, JSR 225. The spec itself involves several different vendors (from Sun and Nokia to BEA, Oracle, and Intel), as well as a few key individuals (like Jason Hunter, of servlets, JDOM, and XML fame). As such, it's a pretty good hammering out of ideas in an environment that isn't going to be tied down to one particular database vendor or XML product-maker.

...but XQJ implementations are not

Unfortunately, there's no Sun-standard implementation of XQJ yet. Most of the vendors on the expert group work for companies that provide an XQJ implementation with their product, and that means you'll deal with some vendor-specific issues. Of course, for long-time XML veterans, this is no different than the XML parser and XSL processor wars that characterized much of the early 2000s. In time, XQJ will standardize, and Sun will almost certainly release its own version of XQJ, or a wrapper API for XQJ implementations that functions like JAXP does for XML parsers and XSL processors.

  • Getting an XQJ implementation

The easiest way to begin with XQJ is to download a free trial from DataDirect. You have to fill out a rather annoying form, but then you're set for plenty of time—certainly long enough to work through this article. Visit the DataDirect XQuery download site. You'll also have to enter a database you want to access—even if you select the XML Documents Only option. Wade through these options, and you'll get an e-mail with instructions about where to download the JAR file, named datadirectxquery.jar.

Expanding the JARred JAR

The installation process is a bit confusing; first, you need to expand the downloaded datadirectxquery.jar. You can do this using the jar command. But before you do that, you should create a directory for the installation, and expand the JAR file into that directory. Then, you can run the jar command:

[bdm0509:~/Desktop] mkdir xqj [bdm0509:~/Desktop] cd xqj [bdm0509:~/Desktop/xqj] jar xvf ../datadirectxquery.jar inflated: XQueryInstaller.jar inflated: ddxqj.jar inflated: ExtensionTool.jar inflated: Readme.txt inflated: 3rdPartySoftware.txt inflated: Fixes.txt inflated: installer.properties

Run the installer

Now, open up the new directory that you created and double-click on the XQueryInstaller.jar file. Assuming you installed Java on your system, this will launch the GUI installer.

You'll be prompted to select the trial or licensed version; select trial for now. Next, you'll need to select an installation directory. Make sure you have permissions to write files to the directory that you enter here. I selected /usr/local/java/xqj on my system, ensuring first that I could write to the /usr/local/java directory. The installation will create the last sub-directory for you—in this example, that's xqj —and then put the DataDirect XQuery files in that directory. Finally, let the installation run, and click Finish.

Once done, navigate to your new directory and check out its contents; they should look like the listing shown below:

Add the XQJ JAR to your classpath

Now you need to update your classpath to include the XQuery JAR with the XQJ classes, stored in the lib directory and named ddxq.jar. This is not the original JAR you downloaded, but the one that was installed by the JAR you expanded above (yes, DataDirect might have made things less confusing by using a ZIP or .tar.gz file for their main download). You can set your classpath manually, or you can use a shell script, .profile file, or an IDE to add the JAR to your classpath. Just make sure that ddxq.jar is available on your classpath.

Set up database connectivity

DataDirect's download offers you database connectivity as well, allowing you to run XQueries against relational databases. When you filled out the download form, you were forced to choose a database to (potentially) connect with. DataDirect then customized the download so that database setup is available. That goes quite a bit beyond the scope of this article, but if you're interested in using your DataDirect libraries to connect to databases alongside making XQueries against XML documents saved on disk. A lot of other JAR files are in the lib directory of your installation, but you don't need any of those for simple file querying. If you later use DataDirect for database connectivity, then you'll want to explore these other JARs, too.

  • Running an XQuery from Java

Once you have XPath and XQuery firmly in hand, and an XQJ implementation on your classpath, you're ready to write Java code and run your queries. There are two basic steps you'll follow in every program you write:

  • Create/Access an XQuery data source.
  • Execute your XQueries.

These are both fairly simple steps, and as long as you're not switching between different XQuery implementations, the first step stays the same in all your programs. In fact, you might want to bundle up the code you write to handle data source configuration and connection into a utility class (that's left for you as an exercise).

Working with XQuery data sources

If you've done much JDBC work, or written any n-tiered data-driven applications, you're probably familiar with the idea of a data source. In this context, a data source is a connection object that abstracts away the details of how that connection is made, and what the connection is connecting to. So a data source might represent a networked connection to a MySQL database, or a file-based connection to a static XML document. Once you have a data source, though, you can operate on it without regard to the connection semantics.

When you're just querying XML documents on a local disk (which is what this article focuses on), setting up a connection is pretty straightforward. Listing 3 shows a very basic Java program that creates a new data source, and gets ready for querying.

Listing 3. Setting up a data source for querying

This looks a lot longer and more complex than it really is. Much of that is because the test program is set up in a way that is pretty modular—with a constructor and init() method—so you can easily reuse this code for your own purposes without lots of changes.

This program gets a filename (from the command-line, which it passes into the class's constructor), and then executes the following code:

First, a new data source is created; the type of this object is com.ddtek.xquery3.xqj.DDXQDataSource. Use an empty constructor, and since you're not connecting to a database, you don't need any further configuration. Then, that data source is used to get a new com.ddtek.xquery3.XQConnection object. This object is the key to creating and executing new XQuery expressions; you haven't done that yet, but now your program is ready to take in a query string, and execute it.

Query a real XML document

You'll also need an XML file to actually query. In Download, you'll find a link to download a zipped, sample CD catalog library file; this is an XML document provided by the W3C for samples just like these. It's over 200 lines, so not printed here, but will give you a good document to query.

Listing 4 shows a small portion of the document to give you an idea of its structure.

Listing 4. A portion of cd_catalog.xml

Build the XQuery

Next, you need to create your actual query. This is easiest to do with a simple Java String. Create a new variable, and simply fill it with a string version of your query, as shown here (this code is all in the main() method) in the XQueryTester class:

The query itself selects all the CDs from 1981 on, recorded on a US label, orders them by year of release, and then returns XML that includes the title and year of release for each returned CD. There are a few things worth noting here:

  • The docName variable represents the document to search. The code will need to handle populating that variable with the document supplied to the program through the command line.
  • Instead of just returning a single value for each node in the result set, an XML string is returned. This XML could be dropped into another, larger XML document, displayed online, or passed into an XSL processor.
  • The XML element names in the source document— CD, TITLE, YEAR, and so on.—are discarded in the result set, and new XML element names are used: cd, title, and year.

None of these on their own are difficult, but they are just additional ways that XQuery provides flexibility in selecting and returning data from XML.

One thing that is worth noting: when you return a string of XML as your result set, you should surround the variables in your return string within curly braces:

These curly braces let the XQuery processor know to treat the enclosed data as variables that are evaluated and replaced with a value, rather than literal text.

Declare an external variable

The XQuery uses a variable, $docName, to represent the document. But you need to declare that variable explicitly, and let the query know that something external—in this case, the Java program—will define that variable for use. In XQuery, you use the declare syntax for this purpose. Here's the format of the declare syntax:

In this case, [variable-name] is $docName. [variable-type] should come from the XML Schema base data types. Most of the time, you'll use either xs:string for strings and xs:int for integers. There are several other types, but these are the most common.

So for the XQueryTester class, the query needs to be modified:

Now, all that's left is to build a function for executing this query.

Run the XQuery

To run a query, you need to follow these steps:

  • Create an XQExpression object from your XQConnection.
  • Bind any variables to the query using the bindXXX() methods on your XQExpression object.
  • Execute the query, and store the results in an XQSequence object.

The only step that's tricky here is to bind variables. In this example, the variable docName needs to be associated with the filename passed in to the program. Since you're binding a string variable, you use bindString. That method takes three arguments:

  • a javax.xml.namespace.QName instance (this class is from the JAXP package), with the name of the variable in your XQuery
  • The value to bind to that variable
  • The atomic type that the variable type should match up to

If you put all of this together, you'll get a method like this:

The first line, XQExpression expression = conn.createExpression();, creates a new expression object. Then, the filename of the document to query is bound to the docName variable: expression.bindString(new QName("docName"), filename, conn.createAtomicType(XQItemType.XQBASETYPE_STRING));. It's not worth worrying much about the mechanics of the QName object at this point; just give it the name of the variable in your XQuery (without the $ character). The next argument is the filename; the third is another fairly constant value, the type you want to ensure your value conforms to. Since in the query the variable was defined as xs:string, you want the type XQItemType.XQBASETYPE_STRING.

While some of this isn't intuitive, most of these are things you simply look up in the API docs. The other bindXXX() methods, like bindInt(), bindFloat(), and so forth, all work the same way.

Last, you execute the query, and get back a sequence of results. You can iterate through this result set, or even easier, convert it to a string and let your program work with the results as a long string of data. That's what's done in the query() method, as it doesn't require the calling program to know about the DataDirect XQuery API.

Listing 5 shows the completed XQueryTester code.

Listing 5. The completed XQueryTester class

Run your XQueryTester

Compile this program, and run it like this:

Note:  I've inserted the line breaks into this to make it fit the online article format. The actual results have no line breaks, and are "crammed" together all on one line.

Experiment!

The program is set up to handle queries and bind to your XML document. Now you can play with the query string, and really get a feel for both XQuery and running those queries from Java programs. Try to select all the CDs; then change the format of the returned results to formatted text. See if you can return all CDs, from the most current to the oldest; or all the CDs priced under ten dollars. Once you've a program like this, you can easily tweak your query, experiment, and even change the XML document that you feed to the program.

It's difficult to talk about XQJ without getting into the basics of XQuery; and you can't talk about XQuery without digging deeply into XPath. Connecting all these disparate parts often means that doing just one part—the Java program to execute a query, or the location within a document that you start a query from—is pretty easy. And that's the best way to think about using XQuery from Java: as a collection of individually simple parts that can be combined into a cool, powerful program.

Because you'll have to get comfortable with several different technologies, you should keep two components the same, and play with the third. So keep your Java program the same, and play with different queries and different input documents. Then, with a basic query, experiment with using more input variables declared in your query. You might want to toy with the XPaths in your return statement, and then the starting point for your searches. As you get better at each component, you'll find your queries are more complex, and your Java coding becomes more robust.

Connect any application to any data source anywhere

Explore all DataDirect Connectors

Need additional help with your product?

Get Customer Support

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Primary Expressions (XQuery)

  • 5 contributors

The XQuery primary expressions include literals, variable references, context item expressions, constructors, and function calls.

XQuery literals can be numeric or string literals. A string literal can include predefined entity references, and an entity reference is a sequence of characters. The sequence starts with an ampersand that represents a single character that otherwise might have syntactic significance. Following are the predefined entity references for XQuery.

A string literal can also contain a character reference, an XML-style reference to a Unicode character, that is identified by its decimal or hexadecimal code point. For example, the Euro symbol can be represented by the character reference, "&#8364;".

SQL Server uses XML version 1.0 as the basis for parsing.

The following examples illustrate the use of literals and also entity and character references.

This code returns an error, because the <' and '> characters have special meaning.

If you use an entity reference instead, the query works.

The following example illustrates the use of a character reference to represent the Euro symbol.

This is the result.

<a>€12.50</a>

In the following example, the query is delimited by apostrophes. Therefore, the apostrophe in the string value is represented by two adjacent apostrophes.

<a>I don't know</a>

The built-in Boolean functions, true() and false() , can be used to represent Boolean values, as shown in the following example.

The direct element constructor specifies an expression in curly braces. This is replaced by its value in the resulting XML.

<a>true</a>

Variable References

A variable reference in XQuery is a QName preceded by a $ sign. This implementation supports only unprefixed variable references. For example, the following query defines the variable $i in the FLWOR expression.

The following query will not work because a namespace prefix is added to the variable name.

You can use the sql:variable() extension function to refer to SQL variables, as shown in the following query.

<value>2500</value>

Implementation Limitations

These are the implementation limitations:

Variables with namespace prefixes are not supported.

Module import is not supported.

External variable declarations are not supported. A solution to this is to use the sql:variable() function .

Context Item Expressions

The context item is the item currently being processed in the context of a path expression. It is initialized in a not-NULL XML data type instance with the document node. It can also be changed by the nodes() method, in the context of XPath expressions or the [] predicates.

The context item is returned by an expression that contains a dot (.). For example, the following query evaluates each element < a > for the presence of attribute attr . If the attribute is present, the element is returned. Note that the condition in the predicate specifies that the context node is specified by single period.

<a attr="1">2</a>

Function Calls

You can call built-in XQuery functions and the SQL Server sql:variable() and sql:column() functions. For a list of implemented functions, see XQuery Functions against the xml Data Type .

Function declaration in the XQuery prolog is not supported.

Function import is not supported.

XML Construction (XQuery)

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

19 Transforming Data with XQuery

This chapter describes how to create, locate, edit, and delete XQuery Transformation resources using the Oracle Service Bus Console.

XQuery transformation maps can describe XML-to-XML, XML to non-XML, and non-XML to XML mappings.

This chapter includes the following topics:

Introduction to XQuery Transformations

XQuery Editors and Mappers

Creating XQuery Maps in JDeveloper

Testing Service Bus Projects Converted from XQuery 2004 to XQuery 1.0 in JDeveloper

Working with XQuery Resources in the Oracle Service Bus Console

Service Bus XQuery Functions

19.1 Introduction to XQuery Transformations

XQuery helps in querying XML data from XML documents. XQuery uses and extends XPath to help navigate and extract elements and attributes from an XML document.

Service Bus uses XQuery to implement its business logic. Service Bus makes use of XQuery resources for various activities, like transformations, data selection, condition evaluation, and data manipulation. Service Bus fully supports XQuery 1.0. This includes optional features such as modules. The older XQuery 2004 is also supported.

XQuery transformation maps describe the mapping between two data types. XQuery maps describe mappings between XML documents with different schemas. Using XQuery, Service Bus can process XML documents and transform document data from one XML schema to another, enabling data interchange among applications that use different schemas. You can perform complex data manipulation and transformation using XQuery. For example, you can map an incoming purchase order schema to an outgoing invoice schema.

You use XQuery expressions to create the data content for the message context variables (or part of a message context variable) during the execution of the message flow. You can use the Test Console directly in the XQuery Expression Editor to test the definition of the expression. Similarly, you use XQuery conditions to evaluate Boolean conditions in the message flow. You can use the Test Console directly in the XQuery Condition Editor to test the definition of the condition.

19.2 XQuery Editors and Mappers

JDeveloper provides both an Expression Builder, where you can script transformations using XQuery, and an XQuery Mapper, where you can create complex mappings.

The Oracle Service Bus Console provides an editor for scripting transformations using XQuery. The editor provides options to define an XQuery expression or to define an expression that evaluates at runtime to the name of an existing XQuery resource.

For both JDeveloper and the console, you access the editors from an action in either a pipeline or split-join.

19.2.1 JDeveloper Editors and Mappers

The XQuery mapper in JDeveloper is a graphical tool that lets you define mappings between schema root elements, WSDL message parts, or WSDL messages. Schema root elements can come from XSD schema files or WSDL files, but only those WSDL messages that contain a single message part can be mapped directly. Once you create an XSLT mapping in JDeveloper, you can upload the .xsl file generated by the mapper to an XSLT resource in the Oracle Service Bus Console.

JDeveloper also includes a variety of Expression Builders, where you can create expressions that specify an existing XSLT resource to use. For more information about the mapper and editors in JDeveloper, see the following topics:

"Creating Transformations with the XQuery Mapper" in Developing SOA Applications with Oracle SOA Suite

" Building XPath Expressions in the Expression Builder in Oracle JDeveloper " in Developing SOA Applications with Oracle SOA Suite

19.2.2 Oracle Service Bus Console Editors

In the Oracle Service Bus Console, the XQuery/XSLT Expression Editor lets you create expressions that specify an existing XQuery resource to use.

Before you can reference an XQuery resource, you need to create the resource in the console and upload an existing XQuery transformation file ( .xqy ) to the resource. This feature allows you to create complex mappings in JDeveloper that you can them import and use in the console. You can reuse an XQuery transformation in multiple pipelines and split-joins.

For information about the XQuery/XSLT Editor in the Oracle Service Bus Console, see Working With Expression Editors in Oracle Service Bus Console .

19.3 Creating XQuery Maps in JDeveloper

You can create XQuery maps in a Service Bus project in JDeveloper, and then use them in XQuery expressions in pipelines and split-joins to map objects between external systems.

When you create an XQuery mapping, you need to select the source XML schema elements or XML files to use for the source and target mappings.

19.3.1 How to Create XQuery Mappings in JDeveloper

See " Creating an XQuery Map File " in Developing SOA Applications with Oracle SOA Suite for details on creating an XQuery map.

See "Using the XQuery Mapper" in Developing SOA Applications with Oracle SOA Suite for details on using the XQuery mapper to build your XQuery.

19.4 Testing Service Bus Projects Converted from XQuery 2004 to XQuery 1.0 in JDeveloper

When converting a Service Bus project from XQuery 2004 to XQuery 1.0, all 2004 XQueries will be switched to run against the XQuery 1.0 engine. After converting from XQuery 2004 to XQuery 1.0, the XQuery Mapper tab in JDeveloper displays, but doesn’t display actual mapping.

  • Restart JDeveloper.
  • Ensure that the XQuery file that you want to test is open.
  • Click the XQuery Source tab to enter Source view.
  • Right click the source, and then select Run XQuery .

When testing converted XQueries:

Ensure that you make the namespace declaration correctly. This can be done in two ways:

Using an import statement from the XQuery specification:

Using Oracle’s annotation mechanism:

Ensure that you declare variables as schema-elements so that they are recognized by the JDeveloper mapper mechanism. For example:

19.5 Working with XQuery Resources in the Oracle Service Bus Console

You can add XQuery resources to your Service Bus project. XQuery files, created using JDeveloper or other editors, can be imported into your project as resources.

How to Create an XQuery Resource in the Console

How to Edit an XQuery Resource in the Console

How to Delete an XQuery Resource in the Console

How to Upgrade Your XQuery Resources to use XQuery 1.0

19.5.1 How to Create an XQuery Resource in the Console

Use the Oracle Service Bus Console to add XQuery resources to your Service Bus project. You can either import an XQuery file created in an editor like JDeveloper, or create a resource and edit the code inline.

To create an XQuery Resource in the console:

In the Project Navigator, right-click the project or folder to contain the XQuery resource, point to Create , and select Resource Click Transformations , click XQuery , and then click OK .

The Create XQuery dialog appears.

Do one of the following:

To create the resource from an existing XQuery file, click Choose File next to the File Upload field and then navigate to and select the file to use.

The Resource Name field is automatically populated with the file name minus the file extension. You can change this name.

To create an XQuery from scratch, enter a unique name for the XQuery resource.

Optionally, enter a brief Description of the resource.

Click Create .

The XQuery resource opens in the XQuery Definition Editor.

To modify the XQuery, do the following:

Click Edit XQuery Contents in the toolbar.

The View/Edit Source dialog appears.

  • To browse to and select a new XQuery file to upload, click Choose File .
  • To modify the contents of the file, update the code directly in the Contents section of the dialog.

Click Save . The XQuery is validated upon save.

  • In the XQuery Definition Editor toolbar, click Save .
  • To end the session and deploy the configuration to the runtime, click Activate .

19.5.2 How to Edit an XQuery Resource in the Console

Use the Oracle Service Bus Console to edit XQuery resources in your Service Bus project. You can either import an updated XQuery file created in an editor like JDeveloper, or edit the code inline.

To edit an XQuery Resource in the console:

  • In the Project Navigator, expand the project and folders containing the XQuery resource to edit.
  • Right-click the XQuery resource name, and select Open .
  • Click Save .

19.5.3 How to Delete an XQuery Resource in the Console

You can use the Oracle Service Bus Console to delete an XQuery resource from your Service Bus project. If the resource has any references, remove them before deleting it. Open the XQuery resource in the XQuery Definition Editor and click the Tools icon in the upper right, and then select References to find out whether there are any references.

To delete an XQuery resource in the console:

  • In the Application Navigator or Project Navigator, expand the project and folders containing the XQuery resource to delete.
  • Right-click the name of the XQuery resource, and select Delete . A confirmation dialog appears.
  • Click Yes to delete the resource.
  • Click Activate to end the session and deploy the configuration to the runtime.

19.5.4 How to Upgrade Your XQuery Resources to use XQuery 1.0

Service Bus supports XQuery 1.0. The older XQuery 2004 is also supported. Any new XQuery resource created in Service Bus uses the XQuery 1.0 version, by default.

If you have upgraded from a pre-12 g Service Bus project, all XQuery resources in the project are configured to use the XQuery 2004 version. The following line is present as the first line in all XQuery files:

You can choose to upgrade all XQuery 2004 resources in your project to use XQuery 1.0. The XQuery converter performs basic translation of XQuery 2004 files to XQuery 1.0. You need to manually verify and correct syntax errors that cannot be handled by the converter.

To upgrade the XQuery resources in a project:

  • In the Application Navigator or Project Navigator, right-click the project to upgrade.
  • Select Convert to XQ 1.0 from the context menu that appears. A confirmation dialog appears.

You can use the Test Console to test your XQuery resources. To use the test console, open the project by clicking the project name in the Project Navigator. Click the Launch Test Console icon, under the Actions column, corresponding to the XQuery resource that you wish to test.

19.6 Service Bus XQuery Functions

Service Bus supports these XQuery functions.

The standard XQuery functions described in the W3C specification:

http://www.w3.org/TR/xpath-functions/

Oracle function extensions and language keywords provided as part of the Oracle XQuery engine—with a small number of exceptions, as described in Supported Function Extensions from Oracle .

Service Bus-specific function extensions. See Function Extensions from Service Bus .

All of the Oracle function extensions use the following function prefix fn-bea: In other words, the full XQuery notation for an extended function is of this format:

19.6.1 Supported Function Extensions from Oracle

For descriptions of all Oracle function extensions, see Service Bus XQuery Functions .

Service Bus supports all Oracle function extensions to XQuery except for the following:

fn-bea:is-access-allowed

fn-bea:is-user-in-group

fn-bea:is-user-in-role

fn-bea:userid

fn-bea:async

fn-bea:timeout

fn-bea:get-property

fn-bea:execute-sql()

Oracle recommends that you do not use the following functions in Service Bus. They are better covered by other language features:

fn-bea:if-then-else

fn-bea:QName-from-string

fn-bea:sql-like

19.6.2 Function Extensions from Service Bus

Service Bus provides the following XQuery functions:

fn-bea:lookupBasicCredentials

fn-bea:isUserInGroup

fn-bea:isUserInRole

fn-bea: uuid

fn-bea:serialize()

fn-bea:binary-to-text

fn-bea:binary-to-xml

19.6.2.1 fn-bea:lookupBasicCredentials

The fn-bea:lookupBasicCredentials function returns the user name and unencrypted password from a specified service account. You can specify any type of service account (static, pass-through, or user-mapping). See Working with Service Accounts .

Use the fn-bea:lookupBasicCredentials function as part of a larger set of XQuery functions that you use to encode a user name and password in a custom transport header or in an application-specific location within the SOAP envelope. You do not need to use this function if you only need user names and passwords to be located in HTTP Authentication headers or as WS-Security user name tokens. Service Bus already retrieves user names and passwords from service accounts and encodes them in HTTP Authentication headers or as WS-Security user name tokens when required.

The function has the following signature:

where $service-account is the path and name of a service account in the following form:

The return value is an XML element of this form:

You can store the returned element in a user-defined variable and retrieve the user name and password values from this variable when you need them.

For example, your Service Bus project is named myProject . You create a static service account named myServiceAccount in a folder named myFolder1/myFolder2 . In the service account, you save the user name of pat with a password of patspassword .

To get the user name and password from your service account, invoke the following function:

The function returns the following element:

19.6.2.2 fn-bea:isUserInGroup

Returns whether or not a given user belongs to a given group (true or false). For example:

19.6.2.3 fn-bea:isUserInRole

Returns whether or not a given user belongs to a given role (true or false). For example:

19.6.2.4 fn-bea: uuid

The function fn-bea:uuid returns a universally unique identifier. The function has the following signature:

You can use this function in the proxy pipeline to generate a unique identifier. You can insert the generated unique identifier into an XML document as an element. You cannot generate a unique identifier to the system variable. You can use this to modify a message payload.

For example, suppose you want to generate a unique identifier to add to a message for tracking purposes. You could use this function to generate a unique identifier. The function returns a string that you can add it to the SOAP header.

19.6.2.5 fn-bea:execute-sql()

The fn-bea:execute-sql() function provides low-level database access from XQuery within Service Bus message flows--see Accessing Databases Using XQuery . The query returns a sequence of flat row elements with typed data.

$datasource is the JNDI name of the datasource

$rowElemName is the name of the row element—specify $rowElemName as whatever QName you want each element of the resulting element sequence to have

$sql is the SQL statement

$param1, ..., $paramk are 1 to k parameters

element()* represents the sequence of elements returned

The return value is a sequence of flat row elements with typed data and automatically translates values between SQL/JDBC and XQuery data models. Data Type mappings that the XQuery engine generates or supports for the supported databases can be found in the XQuery-SQL Mapping Reference .

When you execute the fn-bea:execute-sql() function from a Service Bus message flow, you can store the returned element in a user-defined variable.

Use the following examples to understand the use of the fn-bea:execute sql() function in Service Bus:

Example 1: Retrieving the URI from a Database for Dynamic Routing

Example 2: Getting XMLType Data from a Database

19.6.2.5.1 Example 1: Retrieving the URI from a Database for Dynamic Routing

Service Bus proxy services support specification of the URI to which messages are to be routed at runtime (dynamically)—see Using Dynamic Routing . The following is an example use of the fn-bea:execute-sql() function to retrieve the URI from a database in a dynamic routing scenario.

Example - Get the URI for a Business Service from a Database

In the example:

ds.myJDBCDataSource is the JNDI name to the data source

xs:string($body/m:Request/m:customer_pri/text()) interrogates the request message and populates customer_priority=? with the value of customer_pri in the message

/TARGETSERVICE/text() is the path applied to the result of the SQL statement, which results in the string (CDATA) contents of that element being returned

<ctx:route><ctx:service> ... </ctx:service></ctx:route> are required elements of the XQuery statement for a dynamic routing scenario

The following is the table definition for DISPATCH_MAPPING :

The DISPATCH_MAPPING table is populated as shown in the following example:

Example - DISPATCH_MAPPING Table

The third column in the table ( soapPayload ) is not used in this scenario.

Executing the fn-bea:execute-sql for Example 3

If the XQuery in the Get the URI for a Business Service from a Database example is executed as a result of a proxy service receiving the request message in the following example (note that the value of <customer_pri> in the request message is 0001) , the URI returned for the dynamic route scenario is

Example Request Message $body

19.6.2.5.2 Example 2: Getting XMLType Data from a Database

Data Type mappings that the XQuery engine generates or supports for the supported databases can be found in the XQuery-SQL Mapping Reference . Note that the XMLType column type in SQL is not supported. However, you can access the data in an XMLType column by using the getStringVal() method of the XMLType object to convert it to a String value.

The following scenario outlines a procedure you can use to select data from an XMLType column in an Oracle database.

Use an assign action in a proxy service message flow to assign the results of the following XQuery to a variable ( $result ).

Example - Get XMLType Data from a Database

Rec is the $rowElemName —therefore, Rec is the QName given to each element of the resulting element sequence

select a.purchase_order.getStringVal() ... is the SQL statement that uses the getStringVal() method of the XMLType object to convert it to a String value

datatypes is the table from which the value of the XML is read (the datatypes table in this case contains one row)

The following is the table definition for the dataty.pes table:

Use a replace action to replace the node contents of $body with the results of the fn-bea:execute-sql() query (assigned to $result in the preceding step):

The following listing shows $body after the replacement.

The datatypes table contains one row (with the purchase order data); the row contains the XML represented in the following example.

Example - $body After XML Content is Replaced with Result of fn-bea:execute-sql()

19.6.2.6 fn-bea:serialize()

You can use the fn-bea:serialize() function if you need to represent an XML document as a string instead of as an XML element. For example, you may want to exchange an XML document through an EJB interface and the EJB method takes String as argument. The function has the following signature:

19.6.2.7 fn-bea:binary-to-text

The fn-bea:binary-to-text function converts binary-content to text.

This function has the following signature: fn-bea:binary-to-text($arg0-anyType, $arg1-string)

19.6.2.8 fn-bea:binary-to-xml

The fn-bea:binary-to-xml function converts-binary content to inline XML.

This function has the following signature: fn-bea:binary-to-xml($arg-anyType)

19.6.3 Creating and Using Custom XPath Functions

You can create and use your own custom XPath functions in both inline XQuery expressions and in XQuery resources. For more information, see Creating Custom XPath Functions .

Scripting on this page enhances content navigation, but does not change the content in any way.

Informatica Documentation Portal

  • English English
  • Español Spanish
  • Deutsch German
  • Français French
  • 日本語 Japanese
  • Português Portuguese

Watch for changes to a guide or H2L that you’re interested in!

You can get email notifications when changes are made to content. Simply log in to the portal and click “Watch” from the Actions box.

  •        
  • Informatica ActiveVOS
  • Updated : January 2024
  • Informatica ActiveVOS 9.2.5
  • All Products

Rename Saved Search

Confirm Deletion

Are you sure you want to delete the saved search?

Table of Contents

  • About Informatica Process Developer
  • Working in the Eclipse Environment
  • Required Reset for Process Developer Perspectives
  • Migrating from Process Developer Versions Prior to 9.0
  • Migrating from Process Developer Versions Prior to 8.0.x
  • Opening and Using BPEL4WS 1.1 Processes
  • Migrating Processes from BPEL4WS 1.1 to WS-BPEL 2.0
  • Taking Advantage of SOAP 1.2 Port Binding Version 7.x
  • Saving From One Editing Style to Another (BPMN and Classic)
  • Converting Legacy Deployments to Contributions
  • Launching Process Developer
  • Using the Workspace to Store Projects
  • Changing the Default Location of a Workspace Project
  • Orchestration Project Templates
  • Adding or Removing a Project Orchestration Nature
  • About Project Orchestration and Validation Builders
  • Using Project References
  • Beginning a New Process
  • Selecting the BPMN-Centric or BPEL-Centric Palette
  • Importing an Existing BPEL Process
  • Importing a Visio XML Drawing File
  • Begin Your First Project with Process Developer Assistance
  • Setting Up the Embedded Process Server
  • Process Developer Orchestration File Resources
  • Using Source Control Systems
  • Navigating Through Process Developer
  • Windows Perspectives Views and Editors
  • Project Explorer
  • Participants
  • Outline View
  • Problems View
  • Thumbnail View
  • Bookmarks View
  • Relationships View
  • Servers and Console Views
  • Guide Developer Debug Perspective
  • What is BPMN-Centric Style
  • What is BPEL-Centric Style
  • Comparing the BPMN-Centric and BPEL-Centric Tool Palettes
  • Which Edit Style to Choose BPMN-Centric or BPEL-Centric
  • Using Swimlanes
  • What is Guide Developer Classic Style
  • Process Editor Process Activities Tab
  • Process Editor Fault Handlers Tab
  • Process Editor Event Handlers Tab
  • Process Editor Compensation and Termination Handler Tabs
  • Process Editor Source Tab
  • Setting Visual Properties and Using Your Own Library of Images
  • Adding Tasks and Bookmarks to the Process
  • Adding Comments to a Process
  • Adding Documentation to a Process
  • Tips for Designing on the Process Editor Canvas
  • Showing and Hiding Activities
  • Process Editor Keyboard Shortcuts
  • Process Developer Function Keys
  • Customizing the Process Developer Perspective
  • Go To Activity (Ctrl + l)
  • Open Operation (Ctrl + Shift + t o)
  • Open Port Type (Ctrl + Shift + t p)
  • Open Web Type (Ctrl + Shift + t w)
  • Optimize Parameters
  • Validate Process
  • Generate Process Report
  • Generate Process Image
  • Generate Deployment Image
  • B-Unit Preference
  • Cache and Timeout Preference
  • Colors and Fonts Preferences
  • Contribution Preference
  • Layout Preferences
  • Relationships View Preferences
  • Tasks and Problems Preferences
  • Identity Chooser Preference
  • Additional Preferences
  • Accessing Process Developer Help
  • Viewing Key Elements of a WSDL Tree
  • Editing a WSDL in the WSDL Editor
  • Deleting a WSDL from Your Project
  • Importing a Service Reference
  • Creating a New Interface
  • Setting up Your Java Project in Process Developer
  • Constraints for your Java Project
  • Generating WSDL and Schema from a Java Interface
  • Generating Argument Names for Schema Elements
  • Updating Your Java Project and Your BPEL Process Concurrently
  • Deployment Requirements for a Java (POJO) Endpoint
  • Deployment Requirements for Java (EJB) Endpoint
  • Running a BPEL Process with a POJO EJB Endpoint
  • Comparing the POJO EJB Interface to a Custom Java Invoke Handler
  • Interfaces Toolbar Options
  • Filtering the Interfaces View
  • System Services Interfaces
  • Creating a WSDL File with Extensions for BPEL
  • Adding or Editing a Sample Data Value for a Simple Type Message Part
  • Generating a Sample Data File
  • Adding a Sample Data File to a WSDL Message
  • Selecting a Default Sample Data File
  • Viewing the XML Structure of a Sample Data File
  • Removing a Sample Data File
  • Finding Where a WSDL Component is Used
  • Using Process Search
  • Using Top-Down or Bottom-Up Process Design
  • Creating WSDL Extensions for BPEL
  • Starting a Process by Dropping an Operation onto the Process Editor
  • Automatically Importing WSDL and Schema Locations
  • Manually Importing WSDL Schema and Other Resources
  • Refreshing Imports
  • Deleting an Import
  • Namespace Prefix and Declaration
  • Using the Process Developer Create XPath Extension
  • Using the Process Developer Disable Selection Failure Fault Extension
  • Declaring Extension Elements and Attributes
  • Process Element and Properties
  • Partner Links
  • Fault Handlers
  • Compensation Handlers
  • BPEL XML Source and Implicitly Added Activities
  • Understanding BPEL Process Lifecycle
  • Creating an Abstract Process
  • Tips for Working with Abstract Processes
  • Creating a BPEL Process as a Service for Another BPEL Process
  • Message Exchange Declaration
  • Using the Participants View
  • Creating a New Process Service Consumer Interface
  • Creating a New Partner Service Interface
  • Creating a New Callback Interface
  • Clearing a Service Interface from a Participant
  • Creating New Activities from the Participants View
  • Creating a New Variable From an Activities Property View
  • What are Partner Link Types and Partner Links
  • Adding a new Partner Link Type from a WSDL in Project Explorer
  • Adding a new Partner Link Type to a new WSDL using a Service Reference WSDL
  • Add a new Partner Link Type from Interfaces View
  • Partner Link
  • Using Scoped Partner Links
  • Partner Links and Endpoint References
  • BPMN-to-BPEL Implementation of Tasks and Events
  • Overview of BPEL Activities
  • Selecting Values for Activity Properties
  • Selecting Activity Labels
  • Standard Properties for Activities
  • Adding a Background Color to a Task Scope People Activity and Handlers
  • Understanding and Using Activity Sequences and Flows
  • Compensate Scope
  • Start End None
  • From Part to Variable
  • From Variable to Part
  • Input Variable
  • Output Variable
  • Tips for Copy Operations
  • Copy Operation Query and Expression Examples
  • Copy Operation Literal Contents Examples
  • Copy Operation Dynamic Endpoint Reference Example
  • Element to Element Copy Operation with Keep Source Element Name Attribute
  • Copy Operation with Ignore Missing From Data Attribute
  • Creating a Custom Activity
  • Creating an Activity by Starting with a WSDL Interface
  • BPMN-to-BPEL Implementation of Gateways and Control Flow
  • Overview of Control Flow Items
  • Ungrouping Selected Structured Activities
  • About Gateway Types
  • Building a Gateway
  • Mutually Exclusive Transitions
  • Repeat Until
  • Setting Isolated to Yes in a Scope
  • Using a Termination Handler for a Scope
  • Lifecycle of a Scope
  • Overview of Variables
  • WSDL Message Types
  • XML Schema Type
  • XML Schema Element
  • Adding Variable Properties and Property Aliases
  • Initializing a Variable
  • Quick View of Variables Used in Activities
  • Using the Process Variables View Options
  • Opening a Variable to View its Definition
  • Viewing Variable Properties
  • Understanding Icons Symbols and Descriptions of Variable Parts
  • Deleting a Variable
  • Editing a Single Sample Data Value for a Simple Type Message Part
  • Loading a Sample Data File in Process Variables View
  • Saving and Viewing Sample Data in Process Variables View
  • Using the XML Data Wizard
  • Finding Where Variables are Used
  • Creating a Copy Operation Using a Context Menu
  • Creating a Copy Operation Using Drag and Drop
  • Selecting a Copy Operation to Edit
  • Using Variables Based on WSDL Fault Messages
  • Mapping WSDL Message Parts in Web Service Interaction Activities
  • Validating Variables
  • Working with Variable Attachments
  • Adding an Attachment
  • Adding an Attachment for Simulation
  • Remote Debugging with Variable Attachments
  • Custom Functions for Manipulating Attachments
  • Attachment Custom Function Examples
  • What is a Link
  • Process Developer Extension for Links
  • Adding a Link with no Transition
  • Adding a Link with a Transition Condition
  • Link Examples
  • Execution Rules for Links
  • Designing With Links vs. Structured Activities
  • Links and the Join Condition
  • Link Properties
  • Overview of Data Manipulation in BPEL

Example XQuery Expressions

  • Example XPath Expressions
  • Using Content Assist
  • bpel doXslTransform(style-sheet-uri node-set)
  • bpel getVariableProperty(VariableName propertyName)
  • abx base64Encode(stringValue charSet )
  • abx elementToXMLString(element)
  • abx getAllHTTPHeaders(partnerLinkName)
  • abx getHTTPHeader(partnerLinkName headerName)
  • abx getInboundSOAPHeader(partnerLinkName)
  • abx getProcessId()
  • abx getProcessInitiator() (1)
  • abx getProcessName()
  • abx isVariableInitialized(variable)
  • abx resolveURN(string)
  • abx setProcessTitle(titleString)
  • abx xmlStringToElement(string)
  • Attachment Functions
  • boolean(object)
  • not(boolean)
  • lang(string)
  • abx getCatalogResource(location)
  • abx putCatalogResource(location typeURI document)
  • getFaultCode()
  • getFaultDetail()
  • getFaultString()
  • getSOAPFault()
  • I18N Functions
  • jsonToXml(jsonString)
  • xmlToJson(element)
  • count(node-set)
  • local-name( node-set )
  • name( node-set )
  • namespace-uri( node-set )
  • ceiling(number)
  • floor(number)
  • number(object)
  • round(number)
  • sum(node-set)
  • concat(string1 string2 string3... )
  • contains(string string)
  • starts-with(mainString lookForString)
  • string(object)
  • string-length(string)
  • substring(string number number )
  • substring-after(string string)
  • substring-before(string string)
  • translate(string string string)
  • Expected Expressions for Conditions Counters and Other Values
  • Using the Query Builder
  • Creating a Join Condition for an Incoming Link
  • Deadline and Duration Expressions
  • Default-Order Compensation Example
  • Specified Compensation Example
  • Adding a Compensation Handler to a Scope
  • Compensating an Invoke Activity
  • Correlation
  • What is Correlation
  • Property Aliases
  • WSDL Syntax and Example for Property Names and Aliases
  • Global and Local Correlation Sets
  • Creating a Property Definition
  • Creating a Property Alias
  • Correlation Sets: Required and Optional Properties
  • Deleting a Correlation Set
  • Adding Correlations to an Activity
  • Rules for Declaring and Using Correlation Sets
  • Correlation Sets and Engine-Managed Correlation
  • What is Event Handling
  • Adding an onEvent Event Handler
  • Adding an onAlarm Event Handler
  • Processing Rules for Events
  • Catch and Catch All Boundary Events and Compensate Compensate Scope and Rethrow
  • Using a Variable from a Catch or Interrupting OnEvent Boundary Event
  • What is BPEL Fault Handling
  • Defining Catch and CatchAll Fault Handlers
  • Fault Handling for Service Invocations
  • Adding a Fault Handler for the Process
  • Adding a Fault Handler for a Scope
  • Adding a Fault Handler as a Boundary Event for an Invoke Activity
  • Selecting a Fault Name
  • Adding a Fault Variable Definition
  • Fault Handling Processing Rules
  • Rules for Catching Faults in a Catch Activity
  • Tips on Fault Handling
  • Catching Undeclared and SOAP Faults
  • Opening the Process Developer Debug Perspective
  • Switching Between Process Developer Perspectives
  • Using the Process Developer Debug View
  • Using Breakpoints in BPEL Process Simulation
  • Using the Process Developer Debug Console
  • Prerequisites for Simulation
  • Starting and Ending Simulation of a BPEL Process
  • Running to a Breakpoint in a BPEL Process
  • Stepping to the Next Activity in a BPEL Simulation
  • Viewing the Execution State of an Activity or Link
  • Modifying a BPEL Process During Simulation
  • Terminating and Removing BPEL Process Simulations
  • Clearing the Process Execution State
  • Setting up Sample Data Values for Input Output and Fault Messages
  • Inspecting Process Variables during Simulation
  • Selecting an Invoke Subprocess for Simulation
  • Simulating Event Handlers
  • Simulating Fault Handlers
  • Inspecting Standard Faults During Simulation
  • Disable bpel selectionFailure Fault Example
  • Auto Create Target Path for Copy To Example
  • Disable bpel selectionFailure Fault and Auto Create Target Path for Copy To Example
  • Setting Debug Preferences
  • Configuring a Remote Process Connection
  • Selecting Processes for Remote Debugging
  • Setting Breakpoints on a Process for Remote Debugging
  • Using the Debug View Process Editor and Variable View for Remote Debugging
  • Remote Debugging Preferences
  • Selecting a Launch Configuration from the Toolbar
  • Checking for an Out of Sync Process
  • Server Interactions During a Remote Debugging Session
  • Setting Options for Console Output
  • Updating Variable Data in the Process Variables View
  • Updating Correlation Property Data
  • Updating Partner Link Address Information
  • Monitoring Client Message Traffic with TCP IP Monitor
  • Preparing BPEL Files for Deployment
  • Selecting a Server Platform for Deployed Processes
  • Endpoint References and WS-Addressing Considerations
  • Endpoint References Requiring Credentials for Access
  • Specifying a Replaceable URN URL for an Endpoint Reference
  • Endpoint References and WS-Policy
  • Overview of Process Deployment Steps
  • General Deployment Options
  • Partner Role Invoke Handlers
  • Partner Role Endpoint Types
  • My Role Binding Service Name and Allowed Roles Options
  • Selecting a Service for a Deployment Descriptor Partner Link
  • Using SOAP 1.1 or 1.2 Port Binding
  • Authentication
  • Engine-Managed Correlation
  • HTTP Transport
  • Invoke Recovery
  • JMS Delivery Options
  • Message Validation
  • REST Enabled
  • Run As User
  • Send WS-Addressing Headers
  • Suppress xsi type
  • Web Service Timeout
  • WS-Reliable Messaging
  • WSDL Binding Reference
  • Adding Indexed Properties
  • Viewing References
  • People tab of the PDD
  • Using the PDD Editor Source View
  • Deploying Project Dependencies and Viewing Excluded Dependencies
  • Deploying Additional Resources
  • Managing Deployment Contributions
  • Running a BPRD Ant Script from within Process Developer
  • Running a BPRD Ant Script from the Command Line
  • Deployment Complete
  • Starting the Server and Running a Process
  • How a BPEL Process is Instantiated
  • What is Process Versioning
  • What is BPEL Unit Testing
  • Creating a BPEL Unit Test File
  • Running a BPEL Unit Test in Process Developer
  • Prerequisite
  • Creating a B-unit Ant Script
  • Notes on Modifying a B-Unit Ant Script
  • Adding Multiple B-unit and B-suite to an Ant Script
  • Running a B-Unit Ant Script
  • Generating a Code Coverage Report
  • BPEL Unit (Root)
  • Extensions and Extension Activities
  • Debugging a B-unit Test
  • Tips on Using Assertions
  • Tips on Using Parameterized XSL for Input and Assert Data
  • Tips on Providing Partner Link Data
  • Example B-unit File
  • Custom Functions Overview
  • Implementing: Step 1
  • Implementing: Step 2
  • Implementing: Step3
  • Sample Custom Function
  • Adding Global Custom Functions to the Process Server
  • Using the XQuery Editor
  • Tips on Writing XQuery Functions
  • Testing XQuery Functions in the XQuery Editor
  • Creating a REST-based Receive or Invoke
  • BPEL REST Messages
  • Handling of Multipart HTTP Messages
  • Specifying Deployment Details for a REST-based Process
  • Creating an OAuth Service
  • Specifying Deployment Details for an OAuth Service Provider
  • Using a Java Messaging Service Invoke Handler
  • What is Process Exception Management
  • Making all Processes Eligible for Suspension on Uncaught Faults
  • Making Individual Processes Eligible for Suspension on Uncaught Faults
  • Suspending a Process Programmatically with a Suspend Activity
  • Creating the User Reports Orchestration Project
  • Using the Process Developer Report Template
  • Using the Process Developer Data Source
  • Creating a Data Set from the Process Developer Data Source
  • Understanding the Process Developer Data Model
  • Deploying a Process Developer Report
  • Updating or Deleting a Deployed Report
  • Reporting Service
  • Defining an Event in the Process Deployment Descriptor
  • Using System-Defined Events
  • Creating an Event-Action BPEL Process
  • Activity States Event Properties Task States and Task Event Types
  • What is Process Central
  • Understanding the Process Request Form Template
  • Editing HTML in Process Central Forms
  • Adding a New Service Operation for a Form or a Task
  • Customizing Task and Form Scripts An Introduction
  • Using the Process Developer SDK for Customizing Forms
  • Testing and Debugging Process Central Forms
  • Configuring Form Filters
  • Configuring Reports Filters
  • Including Your Own Styles Scripts and Meta Data for Process Central
  • Basic Task Roles Filter Configuration
  • Configuring Custom Columns for Task Roles Filtering
  • Filtering a Task List using a Show Filter
  • Filtering a Task List by Parameter using a WS-HT whereClause
  • Presentation Parameters
  • Using a getMyTasks orderBy Element
  • Configuring an RSS or Atom Feed Filter
  • Deploying Forms Reports and Configuration Files
  • Displaying Process Central in a Web Browsers Preferred Language
  • Adding Multilingual Support for Forms and Tasks
  • Adding Multilingual Support for an .avcconfig File
  • Adding Multilingual Support for Reports
  • Naming Conventions for .properties File
  • Process Central Advanced Configuration
  • Using a BPEL Template for a System Service-Based Process
  • Alert Service
  • Creating a BPEL Process that Executes Statements on a Data Source
  • Parameter-Based Request
  • Simulating the Data Access Invoke Output
  • Example-Response from an Insert Update or Delete Statement
  • Handling Binary Data
  • Mapping Data Returned in the Data Access Response
  • Simulating the Data Access Service
  • Email Service
  • Identity Service
  • Input and Output for Create Map
  • Input and Output for Migrate
  • Creating a BPEL Process That Migrates Process Instances to a New Version
  • Testing Your Migration Process
  • Using the Process Server Migration Web Service
  • Monitoring Alert Service
  • Retry-Policy Service
  • Server Log Service
  • Shell Command Invoke Service
  • About the BPEL4People Specification
  • Introducing Human Workflow into a BPEL Process
  • Routing Tasks to People at Run Time
  • About Task Life Cycle
  • Creating the Artifacts Needed for the People Activity
  • Creating a Human Task Participant
  • Using or Mapping Users or Groups From the Identity Service
  • Creating a Task for a Participant
  • Using BPEL4People Extension Elements and Activities
  • Human Interactions Extension Element
  • Creating a Logical People From the Outline View
  • Logical People Group Parameters and Arguments
  • Using a Logical People Group in an Assign Activity
  • Selecting Users or Groups for Logical People Groups During Deployment
  • Using Logical People Groups for Role Assignments
  • Using Literal Values for Role Assignments
  • Using Expressions for Role Assignments
  • Adding a Task or Notification to the Outline View for Process or Scope Use
  • Required and Optional Properties for a Task
  • Task Name Interface and Priority
  • Adding a Task Interface
  • Role Assignments for a Task or Notification
  • Adding Task or Notification Presentation Properties
  • Configuring Presentation Parameters for a Task or Notification Subject or Description
  • Adding MultiLingual Support for Task Subject Description and Display Name
  • Adding a Content Type for a Task or Notification Description
  • Using the All Tab of a Task
  • Using Expressions for Outcome and Search By
  • Adding Start and Completion Deadlines and Alarms
  • Selecting an Escalation Action to Occur When a Task Deadline is Triggered
  • Defining a Condition for an Escalation Action
  • Using Task Data or Mapped Data for a Notification
  • Creating an Inline or Local Notification Action for a Task Deadline
  • Using a Reassignment Action for a Task Deadline
  • Invoking a Process When a Task Deadline Occurs
  • Sending Email When a Task Deadline Occurs
  • Required and Optional Properties for a Notification
  • Notification Name Priority and Interface
  • Using the All Tab of a Notification
  • What is a People Activity
  • Conceptual Overview of the People Activity
  • Adding a People Activity from the BPMN Palette
  • Adding a People Activity Using the Participants View
  • Adding a People Activity Using the Create Activity Wizard
  • Adding a People Activity by Dragging a Guide
  • Required and Optional Properties of a People Activity
  • Creating an Inline Task or Notification
  • Selecting a Local Task or Notification
  • Selecting Overrides for Priority and People Assignments
  • Selecting Variables
  • Adding Scheduled Actions for Tasks
  • Sending and Receiving Attachments
  • Catching a Fault Thrown by the People Activity
  • Simulating Comments Returned from a Task
  • Viewing Task Input Data While Simulating
  • Adding a People Query
  • Using the Identity Chooser During Deployment
  • Running Your Process from the Process Server
  • About Task Presentation in Process Central
  • Rendering a Task Interface into a User Interface
  • Creating a Task Form
  • Merging Input and Output Fields in a Task Form
  • Working in Development Mode or Production Mode
  • Understanding the Task Form Template
  • Examples of Task Forms for End Users
  • Adding a New Service Operation to a Task Form
  • Providing Multilingual Support for Task Forms
  • Deploying a Task Form and Properties Files
  • Creating an Process Central Configuration File for Tasks
  • Creating a Custom Rendering
  • Contributing a Custom Task Rendering Hint Editor
  • Human Tasks Custom Functions
  • WS-HT (Human Task) Custom Functions
  • What is the Informatica Business Process Manager WS-HumanTask API
  • Using the WS-HT and Identity Service SDK
  • WS-HT Task Property List
  • Creating a Custom Task Property
  • Configuring Process Central Task Columns and Task Filters Using Properties
  • Creating Custom Escalation Actions
  • BPEL Standard Faults
  • User Reports Sample

xquery variable assignment

Are you sure you want to delete the comment?

Confirm Rejection

Enter the reason for rejecting the comment.

Are you sure to delete your comment?

xquery variable assignment

  •  » 
  • How to declare local variable in XML using XQuery

Local variable are those variables which are only accessible in the block in which they are declared. We can declare local variable in XQuery as well. Local variable can be declared  and assigned a value using the let clause in XQuery and unlike the global variables local variables can be accessed only within the scope in which they are declared. Here is the example to declare and use the Local variables in XQuery.

Here $x is the local variable.

Ask Your Question Got a programming related question? You may want to post your question here Programming Answers here

Related Articles

  • How to declare Global variable of XQuery in XML
  • How to declare the Concat function in XML using XQuery
  • How to declare the Contains function in XML using XQuery
  • Predicate of XQuery in XML
  • FLWOR Expressions of XQuery in XML
  • What is XQuery Conditional Statement in XML
  • How to add elements in XQuery Output
  • How to add attributes in XQuery Output
  • How to use For Clause with XQuery in XML
  • Example of XQuery in XML
  • XML Attributes
  • XML Editors
  • XML Elements
  • XML Products
  • XML Validation

More Articles

  • How to Introduce XQuery in XML
  • XQuery FLWOR Expressions with HTML in XML
  • How to use Let Clause with XQuery in XML
  • How to Use the XQuery Function in XML
  • What is Ceiling Function of XQuery
  • What is Round function of XQuery
  • What is Upper-Case function of XQuery
  • How to use string data type in XQuery
  • What is Date and Time data type in XQuery
  • How to use numeric data type in XQuery
  • What is XQuery data type in XML
  • What is miscellaneous XQuery data type
  • How to use String function in XML
  • What is XQuery Numeric function in XML
  • How to use XQuery Node function in XML
  • What is XQuery dateTime function in XML
  • How to use XQuery year-from-duration function in XML
  • What is months-from-duration function in XQuery
  • days-from-duration function of XQuery in XML
  • Use of XQuery boolean function in XML
  • What is XQuery minutes-from-duration function in XML
  • Define XQuery seconds-from-duration function in XML
  • How to define XQuery hours-from-duration function in XML
  • How to use XQuery fn:not(arg) function in XML
  • How to use XQuery context function in XML
  • How to use XQuery aggregate function in XML
  • TERMS & CONDITIONS
  • REPORT ABUSE

Using external variables with XQuery

When using an XQuery expression that uses external variables, supply (or bind) values for each variable using an XDynamicContext instance and optionally declare the types of the variables using an XStaticContext instance.

Variables declared in the XStaticContext are only visible to the main module. To make an external variable visible to a library module, it must be declared in the prolog of the library module with an external variable declaration.

Declaring the variable in the XStaticContext is optional. If a variable is not declared, the processor assumes that its type is item()*. In other words, the value of the variable can be a sequence of any length consisting of items of any type. Declaring a type for your variables can help the processor detect some usage errors statically during preparation.

The bindings for external variables will be available to the main module and to any library modules that have an external variable declaration in their prolog for that variable.

An error is raised if you do not supply a value for a variable that is used when executing the XQuery expression.

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adopt the coercion rules for variables in XQuery #189

@michaelhkay

michaelhkay commented Oct 7, 2022

  • 👍 1 reaction

@ChristianGruen

ChristianGruen commented Oct 7, 2022

Sorry, something went wrong.

@dnovatchev

dnovatchev commented Oct 7, 2022 • edited

@ChristianGruen

michaelhkay commented Feb 22, 2023

No branches or pull requests

@ChristianGruen

IMAGES

  1. XQuery Editor

    xquery variable assignment

  2. Find Out How to Use XQuery in SQL Server From This Sample

    xquery variable assignment

  3. Learn XQuery Function Tutorial Example

    xquery variable assignment

  4. [Solved] how to use if else in xquery assignment

    xquery variable assignment

  5. Learn XQuery in 10 Minutes, by Dr. Michael Kay

    xquery variable assignment

  6. XQuery Debugger

    xquery variable assignment

VIDEO

  1. Xquery

  2. 6 storing values in variable, assignment statement

  3. XQuery (Part 1)

  4. BaseX

  5. XQuery generation in LinkEHR

  6. R variable assignment

COMMENTS

  1. Updating variables in XQuery

    In answer to your first question about variables, and second question about if statements. You can't change the value of a variable (a stupid name isn't it, given they don't vary!). The magic pixie dust for using XQuery with any complex logic (and something like mutable variables) is recursion.

  2. XQuery Cheat Sheet

    The let clause allows variable assign ments and it avoids repeating the same expression many times. The let clause does not result in iteration. The Where Clause ... XQuery elements, attrib utes, and variables must be valid XML names An XQuery string value can be in single or double quotes An XQuery variable is defined with a $ followed by a ...

  3. 3.5. Variables

    One consequence of this is that you cannot assign a new value to the variable as you can in most procedural languages. Instead, you must use a new variable. Variables can be bound in several kinds of expressions: in global variable declarations, for or let clauses of a FLWOR, quantified expressions, or typeswitch expressions. For example ...

  4. XQuery Syntax

    XQuery Comparisons. In XQuery there are two ways of comparing values. 1. General comparisons: =, !=, <, <=, >, >= 2. Value comparisons: eq, ne, lt, le, gt, ge. The difference between the two comparison methods are shown below. The following expression returns true if any q attributes have a value greater than 10:

  5. 12.3. Variable Declarations

    Declaring variables in the prolog can also be a useful way to define constants, or values that can be calculated up front and used throughout the query. It's important to remember that global variables (prolog-declared variables) are immutable, just like other XQuery variables.

  6. sql:variable() Function (XQuery)

    A. Using the sql:variable () function to bring a Transact-SQL variable value into XML. The following example constructs an XML instance that made up of the following: A value ( ProductID) from a non-XML column. The sql:column () function is used to bind this value in the XML. A value ( ListPrice) from a non-XML column from another table.

  7. PDF XQuery

    XQuery is a declarative programming language that can be used to extract information from an XML document in much the same way as SQL extracts information from a relational ... of a variable. This symbol is the assignment operator in many programming languages. As in XSLT, variables may not have their values altered. ...

  8. Use XQuery from a Java Environment Example Tutorial

    Putting aside the XQuery above for a moment, the let clause is used to assign variables. You've already seen in XQuery that a variable is defined by putting a dollar sign ($) in front of an identifier name. You most often will use variables in XQuery as shown above, though, where the variable is created implicitly by a for clause, rather than ...

  9. Conditional Expressions (XQuery)

    For example, the following query is specified against the xml type variable. The if condition tests the value of the SQL variable (@v) inside the XQuery expression by using the sql:variable () function extension function. If the variable value is "FirstName", it returns the < FirstName > element. Otherwise, it returns the < LastName > element.

  10. Primary Expressions (XQuery)

    The XQuery primary expressions include literals, variable references, context item expressions, constructors, and function calls. Literals. XQuery literals can be numeric or string literals. A string literal can include predefined entity references, and an entity reference is a sequence of characters.

  11. Transforming Data with XQuery

    To browse to and select a new XQuery file to upload, click Choose File. To modify the contents of the file, update the code directly in the Contents section of the dialog. Click Save. In the XQuery Definition Editor toolbar, click Save. To end the session and deploy the configuration to the runtime, click Activate.

  12. Example XQuery Expressions

    Example XQuery Expressions. If you select the XQuery expression language, you can use the many functions that are supported by XQuery in addition to all XPath expression building. The additional XQuery function categories include Date, QName, Misc, and Constructor. You can then create expressions for the document, as the following example shows:

  13. XQuery tutorial

    XQuery is an XML language for querying XML that can handle the following XML document types (both single documents or collections): files. XML databases. XML fragments in memory. XQuery can express queries across all these kinds of data, whether physically stored in XML or viewed as XML via middleware.

  14. How to declare local variable in XML using XQuery

    We can declare local variable in XQuery as well. Local variable can be declared and assigned a value using the let clause in XQuery and unlike the global variables local variables can be accessed only within the scope in which they are declared. Here is the example to declare and use the Local variables in XQuery.

  15. Using external variables with XQuery

    The variable not declared in the XQuery expression itself can be optionally declared using an XStaticContext instance to provide the processor with type information. The following example shows how to prepare the previous XQuery expression, providing a type for the variable not declared in the XQuery expression itself. ...

  16. Adopt the coercion rules for variables in XQuery #189

    XQuery applies the coercion rules only for function arguments, and not for variable bindings. For variables, the supplied value must already be a value of the required type. ... Java allows more conversions on variable assignment than on method calling). In XQuery, however, I can see no rationale for the rules being different. ...

  17. (XQuery/Conditions) Is it possible to declare variables in an if

    XQuery is a declarative and functional language, which means that variables do not get assigned, but only bound within a certain scope. This is something that should be thought about in term of space, not time, as there is no elapse of time in an XQuery program, like a ticket allows you to visit a museum but not another.

  18. CAI: Help with XQuery expression

    The variable changeTo cannot be resolved. The variable changeFrom cannot be resolved. The variable arg cannot be resolved. Fairly new to informatica / xquery, so any help would be appreciated. thanks!

  19. Assign capture groups to variables in XQuery

    Plain XQuery 1.0 has no support for returning match groups. This shortcoming has been solved in the XQuery function library which provides functx:get-matches, but the implementation is not something to be considered efficient.. XQuery 3.0 knows the very powerful function fn:analyze-string.The function returns both matching and non-matching part, also split by match groups if such are defined ...