Reputation: 103
I have a problem with a Xquery.
I have this XML:
<peliculas>
<pelicula fechaEstreno='2007'>
<titulo>Los Otros</titulo>
<director>Alejandro Amenabar</director>
</pelicula>
<pelicula fechaEstreno='1986'>
<titulo>Sangre Facil</titulo>
<director>Ethan Coen</director>
</pelicula>
<pelicula fechaEstreno='1990'>
<titulo>No es pais para viejos</titulo>
<director>Ethan Coen</director>
<director>Joel Coen</director>
</pelicula>
<pelicula fechaEstreno='2007'>
<titulo>The Lovely Bones</titulo>
<director>Peter Jackson</director>
</pelicula>
</peliculas>
I need to show the "titulo" where "director" starts-with 'A'. So I tried something this:
for $c in doc('C:\...\pelis.xml') //pelicula
where starts-with($c/director, 'A')
return
<pelicula>
{$c/titulo}
</pelicula>
But I have this error:
Item expected, sequence found: (element director {...}, ...).
I've used "ends-with" before and I thought the syntax it was similar for "starts-with" too, but It doesn't work.
How could I do that?
Upvotes: 2
Views: 5260
Reputation: 4241
For the third pelicula
element the XPath $c/director
returns a sequence of two elements:
(
<director>Ethan Coen</director>,
<director>Joel Coen</director>
)
The function fn:starts-with(...)
on the other hand expects either the empty sequence or a single item as its first argument:
fn:starts-with($arg1 as xs:string?, $arg2 as xs:string?) as xs:boolean
Here is an example of what you can do instead:
for $c in doc('C:\...\pelis.xml')//pelicula
where
some $director in $c/director
satisfies starts-with($director, 'A')
return <pelicula>{
$c/titulo
}</pelicula>
Using some XPath trickery you can even make it somewhat concise:
for $c in doc('C:\...\pelis.xml')//pelicula[director[starts-with(., 'A')]]
return <pelicula>{
$c/titulo
}</pelicula>
Upvotes: 3