| [ directory ] |
|
8.3 Selecting Data from an XML DocumentIf the beans from Chapter 6 were used in a JSP to navigate through a collection of cds, the page might use an expression such as collection.artist[0].album[2].track[5] A similar but more powerful expression language for navigating XML documents is XPath, which plays a major role in the way JSPs use XML. Syntactically, XPath resembles traversing a set of beans except that the separator is a slash (/) instead of a dot (.), and arrays start counting from 1, not 0. Therefore, the XPath expression that does the same thing as the preceding bean expression would be /collection/artist[1]/album[3]/track[6] Note that the expression also starts with a leading slash. XPath and beans diverge beyond the simple mechanism used to select a specific element. One powerful feature of XPath is its ability to specify only part of an expression, and such a partial expression will retrieve all elements that match. The simplest example of this would be to leave off the last set of square brackets, as in /collection/artist[1]/album[3]/track This specifies all tracks on the third album of the first artist. This idea can be extended by leaving off more array specifiers. The following, for example, would return all tracks on all albums by the first artist: /collection/artist[1]/album/track Indexed and nonindexed elements can be freely mixed. The following would return the second track on each album: /collection/artist[1]/album/track[2] Portions of a path can even be omitted entirely by using two slashes, as in //track, which would return all tracks from albums by all artists. Attributes can be specified by prefacing the name with an at sign (@), so in order to get the name of the first artist, the expression would be /collection/artist[1]/@name. Attributes can also be used in brackets to restrict the set of returned data. The expression //album[@name='Wishfire']/track would return all tracks from all albums named "Wishfire," of which there happens to be only one. Much more could be said about XPath, but this will be sufficient for the remainder of this book. Readers interested in the full specification can find it at http://www.w3.org/TR/xpath; a nice tutorial is online at http://www.zvon.org/xxl/XPathTutorial/General/examples.html. |
| [ directory ] |
|