Database Reference
In-Depth Information
<plays>
{
for $ resource in collection ( "/db/apps/exist101/data" )
return <play uri = "{ base-uri ( $ resource )}" />
}
</plays>
This should return:
<plays>
<play uri= "/db/apps/exist101/data/hamlet.xml" />
<play uri= "/db/apps/exist101/data/macbeth.xml" />
<play uri= "/db/apps/exist101/data/r%20and%20j.xml" />
</plays>
Now let's tweak this a little more. Later on we're going to present a list of available
plays to the user, and it would be nice if we could display the name of the document
(without a collection path) and, more importantly, the name of the play.
To get the name of the file, we have to do some string munging on the URI we
already have. For this, XPath's regular expressions come in handy. Regular expres‐
sions are expressions to parse and work with strings. We won't explain them here
because that would take too much ink (in fact, there are whole topics devoted to
them). For now, just accept that the following expression returns the part of a file‐
name after the last / character:
replace ( base-uri ( $ resource ), '.+/(.+)$' , '$1' )
There is one more thing about the name: we don't want the URI encodings, like %20 ,
to show up in them. For this, we use a native eXist function from one of its extension
modules (extension modules are covered in Chapter 7 ): util:unescape-uri . It needs
two parameters: the name to unescape and the character encoding, which is nowa‐
days almost always UTF-8 . With this, the full code to get a nicely formatted filename
becomes:
util:unescape-uri (
replace ( base-uri ( $ resource ), '.+/(.+)$' , '$1' ),
'UTF-8'
)
To get the name of the play, we have to dive into the XML of the play itself. It's
always in the /PLAY/TITLE element, and since we already have the root document-
node , retrieving this is a piece of cake:
$ resource / PLAY / TITLE / text ()
Using the /text function will ensure we get the result as a text node. If we didn't use
this, the TITLE element itself would be returned (try it out if you want to).
With all this, our full code becomes what you see in Example 3-1 .
Search WWH ::




Custom Search