|
Home >Online Product Documentation >Table of Contents >XQuery and XPath XQuery and XPath
We can access the actors section of videos.xml using this expression:
That was our first "real" query. If you are familiar with XPath, you might recognize that all the queries so far have been valid XPath expressions. We have used a couple of functions - This means we can write more complex XPath expressions like this one: which gives us this output: Different systems might display this output in different ways. Technically, the result of this query is a sequence of two element nodes in a tree representation of the source XML document, and there are many ways a system might choose to display such a sequence on the screen. Stylus Studio gives you the choice of a text view, like the one shown above, and a tree view: you use the buttons next to the Preview window to switch from one to the other. Here is what the tree view looks like:
This example used another function -
The " XPath is capable of doing some pretty powerful selections, and before we move on to XQuery proper, let us look at a more complex example. Suppose we want to find the titles of all the videos featuring an actor whose first name is Lisa. If we look at the videos.xml file, we see that each video in the file is represented by a video element like this one: The query required to provide the results we desire is written like this: Again, this is pure XPath (and therefore a valid XQuery). You can read it from left-to-right as:
l Start at the implicitly-selected document (videos.xml)
l Select all the <video> elements at any level
l Choose those that have an actorRef element whose value is equal to one of the values of the following:
n Select all the <actors> elements at any level
n Select all their <actor> child elements
n Select the element only if its value ends with `Lisa'
n Select the value of the id attribute
l Select the <title> child element of these selected <video> elements
When run against our source document, the result of this XQuery is: Many people find that at this level of complexity, XPath syntax gets rather mind-boggling. In fact, this example just about stretches XPath to its limits. For this kind of query, and for anything more complicated, XQuery syntax comes into its own. But it is worth remembering that there are many simple things you can do with XPath alone, and that every valid XPath expression is also valid in XQuery. XPath Query EditorStylus Studio provides a built-in XPath Query Editor in its XML Editor that allows you to visually edit and test complex XPath expressions, and it supports both version 1.0 and 2.0. See Using the XPath Query Editor to learn more about using this tool. |