Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Returning Results

Neither assignment nor iteration by itself can produce output—they are used only to define variables or iterate through sets of variables, in a manner similar to the SQL SET and SELECT statements, respectively. The key to working with XQuery is to use these statements to choose the nodes with which you're going to work, and then pass those nodes onto the relevant output format. This is where the return keyword comes into play.

The purpose of return is to take the sets defined by the previous for and let statements and turn them into some form of result. It's important to realize that the result of an XQuery expression does not have to be XML. It could be a sequence of values, a single string expression, or a host of any other possible results, although the language is optimized to produce XML preferentially.

Notice, for instance, that the result in the previous sample is not, strictly speaking, an XML document:

<filter>
    <name>phone</name>
    <regex>\(\d{3}\)\d{3}-\d{4}</regex>
  </filter>
  <filter>
    <name>zipcode</name>
    <regex>\d{5}(-\d{4})?</regex>
  </filter>
  <filter>
    <name>email</name>
    <regex>\w+@\w+\.\w </regex>
  </filter>

Instead, it is a sequence of such documents. The output of an XQuery is a sequence of something, whether of XML document nodes, strings, numbers, or some combination. For instance,

for $a in (1 to 10) return $a

produces the following numeric sequence output

1,2,3,4,5,6,7,8,9,10

as distinct nodes.

This raises an interesting question. What is an output node? In essence, when an XQuery generates a result, the implementation of the result is application-specific. The result is, as mentioned, a sequence of items. Internally, what is returned usually is a DOM XMLNode object, although it might be subclassed as an element, attribute, text node, or some other resource. Typically, a non-XML result (anything that can't immediately be translated into an XML element or attribute) is returned as a text node, regardless of the data type of the variables being returned.

The expression after the return syntax can be a little confusing, especially if you are used to working with XSLT. You can introduce new elements into the output directly through the use of traditional XML-bracketed elements. For instance, you could in theory generate XML output from the list of numbers by placing an arbitrary XML element (such as a <number> tag) around the variable:

for $a in (1 to 3) return <number>$a</number>

Unfortunately, this will likely not give you the result you expect. The previous XQuery produces this result:

<number>$a</number>
<number>$a</number>
<number>$a</number>

Because any time you introduce an XML tag (opening and closing) into a result, the XQuery processor treats anything within those tags as being more markup and doesn't evaluate the result. Consequently, to do such an evaluation, you need to use the evaluation operators: {}. Such operators instruct the XQuery engine to treat the content within the brackets as XQuery expressions.

So, to get the expected result (a set of three numbers within tags), you change the XQuery to incorporate the evaluation operators:

for $a in (1 to 3)
return <number>{$a}</number>

This can lead to some interesting conditions. In any XQuery, there is an implicit assumption that the expression starts in evaluation mode—in other words, there is an implicit return statement at the highest level. That's why expressions such as

for $a in (1 to 3)
return <number>{$a}</number>

are evaluated in the first place. However, if you place arbitrary elements around the XQuery expression, the mode of operation switches into static mode:

<numbers><!-- now in static mode -->
for $a in (1 to 3)
return <number>{$a}</number>
</numbers>

In this case, the text is treated as if it is just that—text—until the evaluation brackets are reached. At that point, you ask the XQuery expression to evaluate a variable that has not been previously defined ($a), and it should fail. Indeed, using eXcelon Stylus Studio, the error received when this script ran was specifically "Variable a does not exist".

Consequently, to evaluate the text as if it were an XQuery expression, you must encompass the text within the <numbers> element with the evaluation operators {}:

<numbers>
{
for $a in (1 to 3)
return <number>{$a}</number>
}
</numbers>

This returns the expected results:

<numbers>
   <number>1</number>
   <number>2</number>
   <number>3</number>
</numbers>

This example also illustrates a second principal about evaluating XQuery expressions: You can have multiple nested {} elements, as long as they are used within elements in static context. For instance, in the example, the <numbers> tag puts the XQuery into static mode, and you have to place evaluation operators around the whole expression. Similarly, the <number> element puts the XQuery expression back into static mode, so you once again have to place the expression to be evaluated (in this case, the $a element) into the braces.

This can be seen in a slightly more sophisticated XQuery:

<numbers>
{for $a in (1 to 3) return
   <set>{for $b in (1 to $a)
      return <item>{$b}</item>
   }</set>
}
</numbers>

In this case, the $a variable iterates through the values from 1 to 3, producing <number> elements as a child. Each number element in turn evaluates from 1 to $a (whatever it happens to be for that loop) and performs its own internal return to produce <item> elements. This produces the following result:

<numbers>
   <set>
      <item>1</item>
   </set>
   <set>
      <item>1</item>
      <item>2</item>
   </set>
   <set>
      <item>1</item>
      <item>2</item>
      <item>3</item>
   </set>
</numbers>

These evaluated expressions can, of course, be more complex than simply returning the value of a variable. For instance, you can create a table in HTML that sums up sequences of varying lengths, as follows:

<html>
<head>
   <title>Summations</title>
</head>
<body>
<h1>Summations</h1>
<table>
   <tr>
      <th>Index</th>
      <th>Sum From 1 to Index</th>
   </tr>
{for $a in (1 to 10) return
   <tr>
      <td>{$a}</td>
      {
      let $b := (1 to $a)
      return
          <td>{sum($b)}</td>
      }
   </tr>
}
</table>
</body>
</html>

This example points out several salient lessons. First, you can use XQuery to generate HTML, which makes it a particularly potent tool for creating reports—an avenue we'll explore in greater depth in Chapter 4, "XQuery and XSLT." Second, you can use XQuery functions in the result blocks, such as the use of the sum() function to add up each successive $b list (that is, the lists (1), (1,2), (1,2,3), (1,2,3,4), and so on). Finally, any variable that is defined in an outside expression (such as the $a variable) is available for use within the inside expression, such as

let $b := (1 to $a)

You can similarly perform such evaluated expressions within attributes. For instance, suppose you want to create a table of colors in HTML. To do so, you need both the name of the table and a rectangle of the appropriate color illustrating the shade, set using the Cascading Style Sheets background-color property, as follows (see Figure 3.1):

<html>
<head>
   <title>Summations</title>
</head>
<body>
<h1>Summations</h1>
{let $colors :=("white","red","blue","green","yellow","purple","orange","black")
return
<table border="1">
   <tr>
      <th>Color</th>
      <th>Example</th>
   </tr>
{for $color in $colors return
   <tr>
      <td>{$color}</td>
       <td style="background-color:{$color}">&#160;</td>
   </tr>
}
</table>
}
</body>
</html>
Figure 3.1Figure 3.1 You can use XQuery to generate more than just textual data, as this color sample illustrates.

The entity &#160; is a nonbreaking space—within an HTML <td> element, it ensures that the background color will always be rendered. What's most important here is the use of the evaluated expression in the style attribute:

<td style="background-color:{$color}">&#160;</td>

This basically replaces the indicated expression {$color} with its associated values: "white", "red", "blue", and so on, and as with elements, the expression within the attribute block could be a full XQuery expression (whitespace, including carriage returns, doesn't count in the way the attribute is handled).

The tag notation is useful in certain circumstances, but sometimes it can get in the way. The element and attribute operators perform the same purpose, but they don't require the use of the closing tag. The previous XQuery could be rewritten using these operators as follows:

<html>
<head>
   <title>Summations</title>
</head>
<body>
<h1>Summations</h1>
{let $colors :=("white","red","blue","green","yellow","purple","orange","black")
return
<table border="1">
   <tr>
      <th>Color</th>
      <th>Example</th>
   </tr>
{for $color in $colors return
   element tr {
      element td {$color},
       element td {
         attribute style {'background-color:',$color},
         '&#160;'
         }
      }
}
</table>
}
</body>
</html>

The non-XML usage for listing elements, attributes, and text content can make your code easier to read. The element constructor, for instance, takes the name of the element as the first parameter, and the value of the element (possible as an evaluated expression) as the second element. Thus,

element td {$color},

creates a new element <td> and places the text value of $color into it.

You can create sibling nodes (attribute, element, or text) with the comma separator (,) operator. Thus, in the definition of the second td element, the expression

element td {
   attribute style {'background-color:',$color},
   '&#160;'
   }

includes a new attribute node named style that in turn creates two child text nodes: the literal 'background-color' and the result of evaluating the $color variable. Because the content of an attribute must be a string, the XQuery engine concatenates these two values together into a single string value.

The same type of action is at work with the encompassing td element, which not only generates the style attribute, but also includes the literal '&#160;', the nonbreaking space character, as a text node. There is no direct concatenation here of the two nodes, by the way, because they are of a differing type—the attribute node attaches to an element as an attribute, whereas the text node is attached in a different way as part of the set of text nodes.

This can be given in a slightly simpler form. This expression

element a {
   element b {
      attribute b1 {t1},
      element c,
      'strD'
      }
   }

is the same as this tagged expression:

<a>
   <b b1="t1">
   <c/>
   strD
   </b>
</a>

The two formats are equivalent in their application, so you should use the format that works best for your needs.

Given the richness of possible output, there is always more to say about the return keyword, but the examples given here are sufficient to lay the groundwork for complex tasks.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020