XQuery speeds up the process of finding information contained in an XML document, which is very handy when dealing with long XML documents. This article, the first of two parts, will teach you how to write XQuery expressions. It is excerpted from chapter nine of the book XML DeMYSTiFieD, written by Jim Keogh and Ken Davidson (McGraw-Hill/Osborne, 2005; ISBN: 0072262109).
XQuery - A Walkthrough of an XQuery (Page 4 of 5 )
Let’s take a closer look at the catalog.xq now that you have an understanding of how clauses work. The catalog.xq is basically an HTML document that has XQuery clauses embedded in it. (Our example is converting to HTML, but it can be to any language you like.)
You probably recognized the first part of the XQuery because it’s HTML. The <body> tag contains text that’s displayed on the screen followed by an unordered list.
<html> <body> List of titles in this catalog: <br/> <ul>
Next is the meat of the XQuery. This is where you tell Saxon-B the information that you want returned from the XML document. It begins with an open French brace ({) and ends with a closed French brace (}).
{ for $x in doc("catalog.xml")/catalog/cd/title order by $x return <li>{data($x)}</li> }
The first line within the French brace is the for clause, which you learned about previously in this chapter. The for clause tells Saxon-B to look for something within the XML document. In this case the something is the title tag.
You must tell Saxon-B to retrieve the XML document and then specify all the parent tags, if any, of the tag that you want returned. Retrieving the XML document is a task. You have Saxon-B do this by calling the doc() function and passing it the name of the XML document. The parent tags are catalog and cd.
Each time Saxon-B encounters the title tag in the XML document it assigns the title tag to variable $x. Once the end of the XML document is reached, Saxon-B sorts titles contained in variable $x.
The return clause is then called to return all the titles to the output.html file. Notice that the <li> HTML tag is part of the return value, which causes titles to be displayed on a bulleted list.
The last part of the XQuery is also familiar because it contains the closing HTML tags for the tags opened in the first part of the XQuery.