XML

Processing XQuery Results

Thus far I've focused solely on tweaking queries and returning the raw result, which is a collection of nodes. Realistically, you will often want to further process the results of a query to extract information from the nodes and transform it for display purposes or to pass along to another application or service. It's very straightforward to further process query results and package them within other surrounding XML code to effectively create transformed data. You can even transform query results into HTML code that can be viewed as a web page.

The key to incorporating query results into surrounding code is curly braces ({}), which you use to surround query data. Before you can do that, however, you need to know how to access the content within a node. You do this by calling the XQuery data() function and supplying it with the node in question. Following is an example of formatting a query result:

for $c in //color
return <p>Vehicle color: {data($c)}</p>

When executed on the vehicle sample document, this code results in the following:

<?xml version="1.0" encoding="UTF-8"?>
<p>Vehicle color: green</p>
<p>Vehicle color: white</p>
<p>Vehicle color: white</p>

As you can see, the value of each color element is extracted and included in a <p> tag that would be suitable for inclusion within an HTML document.

You can also process attributes directly from a query string to get more interesting results, as in the following query:

xquery version "1.0";
<p>
Following are all of the white vehicles:<br />
{ for $v in //vehicle[color='white']
return <div>{data($v/@year)} - {data($v/@make)} - {data($v/@model)}</div>
}
</p>

This code demonstrates how a query can be placed within other XML (XHTML) code by enclosing it in {}. The resulting XHTML code is then readily viewed within a web browser:

<?xml version="1.0" encoding="UTF-8"?>
<p>
Following are all of the white vehicles:<br/>
   <div>2005 - Acura - 3.2TL</div>
   <div>2004 - Acura - 3.2TL</div>
</p>

One last trick for formatting queries involves the XQuery order by statement, which allows you to set the order of query results. Following is the same query you just saw, except this time the query results are ordered by price:

xquery version "1.0";
<p>
Following are all of the white vehicles:<br />
{ for $v in //vehicle[color='white']
order by $v/price
return <div>{data($v/@year)} - {data($v/@make)} - {data($v/@model)}</div>
}
</p>

Because the price isn't shown in the output, this ordering isn't quite so meaningful in this particular example, but it will be as you explore more interesting examples a little later in the tutorial.

by BrainBellupdated
Advertisement: