XQuery was designed to query XML data.
XQuery is a language for finding and extracting elements and attributes from XML documents.
XQuery uses path expressions to navigate through elements in an XML document.
example: Xpath
/bookstore/book/title
XQuery uses predicates to limit the extracted data from XML documents.
example:
/bookstore/book[price<30]
/bookstore/book[price>30]/title
The expression above will select all the title elements under the book elements that are under the bookstore element that have a price element with a value that is higher than 30.
FLWOR expression
The following FLWOR expression will select exactly the same as the path expression above:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
return $x/title
With FLWOR you can sort the result:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
The for clause selects all book elements under the bookstore element into a variable called $x.
The where clause selects only book elements with a price element with a value greater than 30.
The order by clause defines the sort-order. Will be sort by the title element.
The return clause specifies what should be returned. Here it returns the title elements.
XQuery is case-sensitive and XQuery elements, attributes, and variables must be valid XML names.
An XQuery string value can be in single or double quotes
XQuery Conditional Expressions
If-Then-Else
for $x in doc("books.xml")/bookstore/book
return if ($x/@category="CHILDREN")
then <child>{data($x/title)}</child>
else <adult>{data($x/title)}</adult>
Comparisons
1. General comparisons: =, !=, <, <=, >, >=
2. Value comparisons: eq, ne, lt, le, gt, ge
The for Clause
The for clause binds a variable to each item returned by the in expression.
The for clause results in iteration. There can be multiple for clauses in the same FLWOR expression.
Example:
for $x in (1 to 5)
return <test>{$x}</test>
The at keyword can be used to count the iteration:
Example::
for $x at $i in doc("books.xml")/bookstore/book/title
return <book>{$i}. {data($x)}</book>
It is also allowed with more than one in expression in the for clause. Use comma to separate each in expression:
Example:
for $x in (10,20), $y in (100,200)
return <test>x={$x} and y={$y}</test>
The let Clause
The let clause allows variable assignments and it avoids repeating the same expression many times. The let clause does not result in iteration.
let $x := (1 to 5)
return <test>{$x}</test>
The where clause is used to specify one or more criteria for the result:
where $x/price>30 and $x/price<100
The order by clause is used to specify the sort order of the result.
for $x in doc("books.xml")/bookstore/book
order by $x/@category, $x/title
return $x/title
The return clause specifies what is to be returned.
for $x in doc("books.xml")/bookstore/book
return $x/title
No comments:
Post a Comment