return all based on a condition.

Hi I am new to XQuery and want to know whether I can return all the nodes in the xml file based on a condition.
For eg:

FOR $b IN document(“bib.xml”)/bib/book
WHERE $b/publisher = “Addison-Wesley”

{ $b/title }


This XQuery returns only the book node and its child node. What I need is that it should return all the nodes in bib.xml based on the condition.

Thank You

I missed a thing, what I am expecting from the return statement is all the node/text pair values.
For eg: JK Rowling
then XQuery should return author and JK Rowling
Is it possible to get the node/text values of the childnodes of each node if it has any?

Thank You

I’m not 100% sure what your expecting to be returned. If you just want all the elements which match your criteria - plus the full tree structure below them, then you can just do:-

FOR $b IN document(“bib.xml”)/bib/book
WHERE $b/publisher = "Addison-Wesley"

Hope that helps

Mike Ball

Hi Thanx for the reply, thats the part of the answer I required, Thanx. But can I just the get the element name and the text for each node/child node in the document?

JK Rowling

author = JK Rowling

If you want to return all the books that satisfy the condition, write:

for $b in document(“bib.xml”)/bib/book
where $b/publisher = “Addison-Wesley”
return $b

I hope I’ve interpreted your requirements correctly, if not, it helps if you explain what you want the output to be.

Michael Kay

Actually there’s a simpler way of writing this:

[publisher = “Addison-Wesley”]

Hello there,

to get a result like “author = JK Rowling” you could use something like this in the query:

         {local-name($b/author)} = {$b/author/text()}

I hope that helps (rather than confuses matters!),

Thanx Trevor,
I used your code snippet and I was able to see
author = JK Rowling
as the output.
The snippet displays only the author element, Can you please tell me how I can get all the elements in a document including the child elements along with the text?
And without the tag. Thanx again for ur solution.
for eg:

TCP/IP Illustrated



title = TCP/IP Illus…
Author =
last = Stevens
first W.

If you want to do this completely generically, you need to write a recursive function. That’s beyond the subset Tamino currently offers. The function would look something like this:

define function show($e as element()) as xs:string {
string-join (
(name($e), “=”,
if ($e/)
then for $c in $e/
else string($e)
), “”)

You would need some refinement on that to get all the spacing and indentation right.

XQuery isn’t really designed for presentation tasks such as this, it’s more of a job for XSLT really. Use XQuery to get the data you want from the XML database, use XSLT to format it for display.

Michael Kay