Week 13 Code Examples
Example 1
This XQuery uses a FLOWR expression to find players in the national league who have 500 or more at bats(AB) for the season.
**********
xquery version "3.0";
declare variable $xml:=doc("national.xml");
for $person in $xml/LEAGUE/PLAYER
let $qualify := 500
where $person/AB >=$qualify
order by $person/AVG
return $person
***********
Example 2
This XQuery will show the same thing, but with comments.
***********
(:this is the prolog:)
xquery version "3.0";
declare variable $xml:=doc("national.xml");
(: this is the body:)
for $person in $xml/LEAGUE/PLAYER
let $qualify := 500
where $person/AB >=$qualify
order by $person/AVG
return $person
***********
Example 3
This XQuery adds up using sum all of the homeruns(HR) by all national league players.
***********
(:this is the prolog:)
xquery version "3.0";
declare variable $xml:=doc("national.xml");
(: this is the body:)
let $number := sum($xml//HR)
return $number
***********
Example 4
This XQuery searches PLAYER for those that have more that 500 at-bats(AB), then orders PLAYER by batting average(AVG), from highest to lowest.
(:this is the prolog:)
xquery version "3.0";
declare variable $xml:=doc("national.xml");
(: this is the body:)
for $person in $xml/LEAGUE/PLAYER
let $qualify :=500
where $person/AB >= $qualify
order by $person/AVG descending
return $person
Example 5a
This XQuery searches PLAYER as above. But, before the variable $person is return, it does an if/then statement. If $person is less than or equal to 25 homeruns(HR), then the player is considered "disqualified". If the test doesn't meet the condition, then Else, it prints NAME. Both conditions will be printed inside of new XML tags.
***********
(:this is the prolog:)
xquery version "3.0";
declare variable $xml:=doc("national.xml");
Name | AVG | K/BB | WALKS | |
---|---|---|---|---|
{data($person/NAME)} | {data($person/AVG)} | {data($person/HR)} | {data($ktowalk)} | {data($person/WALK)} |