Guest lesson I've given twice in Fall 2014 and Spring 2015 for a graduate XML class in the UAlbany Information Science program. Here I tried to get the class to understand how to make use of their XML data in mass, and how that can inform them how to better structure their data in the first place.
Simple For/Return:
for $player in doc("national.xml")/LEAGUE/PLAYER
return $player
Declare variable in prolog:
declare variable $xml := doc (‘national.xml');
Let
let $qualify := 500
Return player names in order of AB
order by $player/AB descending
difference between integers and strings
order by $player/NAME
Which players led the league in SO?
order by number($player/SO) descending
Return players with over 500 AB
where $player/AB > 500
where $player/AB >= $qualify
(: comments :)
How many players play in the league?
let $number := count($xml/LEAGUE/PLAYER)
return $number
How many home runs were his last season?
let $number := sum($xml/LEAGUE/PLAYER)
return $number
Return the names of players who hit more than 25 home runs
for $player in doc("national.xml")/LEAGUE/PLAYER
return
if ($player/HR >= 25)
then $player/NAME
else ()
Need a root node just like an XML file
for $player in doc("national.xml")/LEAGUE/PLAYER
let $qualify := 500
where $player/AB > $qualify
order by number($player/AVG) descending
return
<batter>
<name>{$player/NAME}</name>
<average>{$player/AVG}</average>
</batter>
```
* return only the data not nodes
<name>{data($player/NAME)}</name>
<average>{data($player/AVG)}</average>
```
Return with one element per batter
<batter avg="{data($player/AVG)}">{data($player/NAME)}</batter>
}</leaders>
Return a list of AVG leaders but disqualify players wh * hit 25 or more HR
```
for $player in doc("national.xml")/LEAGUE/PLAYER
let $qualify := 500
where $player/AB > $qualify
order by number($player/AVG) descending
return
if ($player/HR >= 25)
then <batter avg="DISQUALIFIED">{data($player/NAME)}</batter>
else <batter avg="{data($player/AVG)}">{data($player/NAME)}</batter>
}</leaders>
```
Let’s not show the disqualified players at all ()
Return an HTML table of qualified leaders(AB<500) that lists: NAME, AVG, HR, SO/BB, WAR sort by SO/BB
xquery version "3.0";
declare variable $xml := collection('baseball');
<html>
<head>
<link rel="stylesheet" type="text/css" href="table.css"/>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>AVG</th>
<th>HR</th>
<th>K/BB</th>
<th>WAR</th>
</tr>
{
for $player in $xml/LEAGUE/PLAYER
let $qualify := 100
where $player/AB > $qualify
let $k := $player/SO
let $walk := $player/BB
let $ktowalk := $walk div $k
order by $ktowalk descending
return
<tr>
<td>{data($player/NAME)}</td>
<td>{data($player/AVG)}</td>
<td>{data($player/HR)}</td>
<td>{data($ktowalk)}</td>
<td>{data($player/WAR)}</td>
</tr>
}</table>
</body>
</html>