SlideShare uma empresa Scribd logo
1 de 51
Baixar para ler offline
Querying XML: XPath and XQuery
Lecture 8a
2ID35, Spring 2013
24 May 2013
Katrien Verbert
George Fletcher
Slides based on lectures of Prof. T. Calders
and Prof. H. Olivié
Table of Contents
1.  Introduction to XML
2.  Querying XML
a)  XPath
b)  XQuery
1. Introduction to XML
•  Why is XML important?
•  simple open non-proprietary widely accepted data
exchange format
•  XML is like HTML but
•  no fixed set of tags
−  X = “extensible”
•  no fixed semantics (c.q. representation) of tags
−  representation determined by separate ‘style sheet’
−  semantics determined by application
•  no fixed structure
−  user-defined schemas
<?xml version ="1.0"?>
<university>
<department>
<dept_name>Comp. Sci.</dept_name>
<building>Taylor</building>
<budget>100000</budget>
</department>
<course>
<course_id>CS-101</course_id>
<title>Intro to Comp. Science</title>
<dept_name>Comp. Sci.</dept_name>
<credits>4</credits>
</course>
. . .
XML-document – Running example 1 (1/2)
XML-document – Running example 1 (2/2)
. . .
<instructor Id=“10101”>
<name>Srinivasan</name>
<dept_name>Comp. Sci.</dept_name>
<salary>65000</salary>
<teaches>CS-101</teaches>
</instructor>
</university>
Elements of an XML Document
•  Global structure
•  Mandatory first line
<?xml version ="1.0"?>
•  A single root element
<university>
. . .
</university>
•  Elements have a recursive structure
•  Tags are chosen by author;
<department>, <dept_name>, <building>
•  Opening tag must have a matching closing tag
<university></university>, <a><b></b></a>
Elements of an XML Document
•  The content of an element is a sequence of:
−  Elements
<instructor> … </instructor>
−  Text
Jan Vijs
−  Processing Instructions
<! . . . !>
−  Comments
<!– This is a comment --!>
•  Empty elements can be abbreviated:
<instructor/> is shorthand for
<instructor></instructor>
Elements of an XML Document
•  Elements can have attributes
<Title Value="Student List"/>
<PersonList Type="Student" Date="2004-12-12">
. . .
</Personlist>
Attribute_name = “Value”
Attribute name can only occur once
Value is always quoted text (even numbers)
Elements of an XML Document
•  Text and elements can be freely mixed
<Course ID=“2ID45”>
The course <fullname>Database
Technology</fullname> is lectured
by <title>dr.</title>
<fname>George</fname>
<sname>Fletcher</sname>
</Course>
•  The order between elements is considered important
•  Order between attributes is not
Well-formedness
•  We call an XML-document well-formed iff
•  it has one root element;
•  elements are properly nested;
•  any attribute can only occur once in a given opening
tag and its value must be quoted.
•  Check for instance at:
http://www.w3schools.com/xml/xml_validator.asp
Table of Contents
1.  Introduction to XML
2.  Querying XML
a)  Xpath
b)  XQuery
12
Querying and Transforming XML Data
•  XPath
•  Simple language consisting of path expressions
•  XQuery
•  Standard language for querying XML data
•  Modeled after SQL (but significantly different)
•  Incorporates XPath expressions
13
Tree Model of XML Data
•  Query and transformation languages are based on a tree
model of XML data
•  An XML document is modeled as a tree, with nodes
corresponding to elements and attributes
−  Element nodes have children nodes, which can be
attributes or subelements
−  Text in an element is modeled as a text node child of
the element
−  Children of a node are ordered according to their
order in the XML document
−  Element and attribute nodes (except for the root
node) have a single parent, which is an element node
−  The root node has a single child, which is the root
element of the document
Tree Model of XML Data (Cont)
ROOT
university
department
Taylor
Comp. Sci.
instructor
_123456789
id
M
university
Comp. Sci.
Element node
Text node
dept_name
building
name
id Attribute node
15
XPath
•  XPath is used to address (select) parts of documents
using path expressions
•  A path expression is a sequence of steps separated by “/”
•  Think of file names in a directory hierarchy
•  Result of path expression: set of values that along with
their containing elements/attributes match the specified
path
XPath example
/university/instructor
ROOT
university
instructor
Id
_333445555
instructor
Id
_123456789
instructor
Id
_999887777
XPath (example)
/university/instructor
ROOT
university
instructor
Id
_333445555
instructor
Id
_123456789
Instructor
Id
_999887777
XPath (example)
/university/
instructor
ROOT
university
Instructor
id
_333445555
instructor
Id
_123456789
instructor
Id
_999887777
19
XPath (example)
/university/instructor
ROOT
university
instructor
Id
_333445555
instructor
Id
_123456789
instructor
Id
_999887777
XPath (example)
/university/instructor
<instructor Id="_123456789”>
<name>Paul De Bra</name>
....
</instructor>
<instructor Id="_333445555”>
<name>George Fletcher</name>
…..
</instructor>
<instructor Id="_999887777”>
<name>Katrien Verbert</name>
.....
20
ROOT
university
instructor
Id
_333445555
instructor
Id
_123456789
instructor
Id
_999887777
21
XPath (Cont.)
•  The initial “/” denotes root of the document (above the
top-level tag)
•  Path expressions are evaluated left to right
•  Each step operates on the set of instances produced by the
previous step
•  Selection predicates may follow in [ ]
•  E.g. /university/instructor[salary > 40000]
−  returns instructor elements with a salary value greater than 40000
•  Attributes are accessed using “@”
•  E.g. /university/instructor[salary > 40000]/@Id
−  returns the Ids of the instructors with salary greater than 40000
Q1: give XPath expression
Retrieve instructor
with Id _123456789
/university/
instructor
[@Id=“_123456789”]
22
ROOT
university
instructor
Id
_333445555
instructor
Id
_123456789
instructor
Id
_999887777
23
Functions in XPath
•  XPath provides several functions
The function count() takes a nodeset as its argument and returns the
number of nodes present in the nodeset.
E.g. /university/instructor[count(teaches) = 3]
Returns instructors who are involved in 3 courses
•  Function not() can be used in predicates
•  //instructor[not(teaches)]
24
More XPath Features
•  Operator or used to implement union
•  E.g. //instructor[count(teaches) = 1 or not
(teaches)]
gives instructors with either 0 or 1 courses
•  “//” can be used to skip multiple levels of nodes
•  E.g. /university//name
−  finds any name element anywhere under the /university element,
regardless of the element in which it is contained.
•  A step in the path can go to:
parents, siblings, ancestors and descendants of the
nodes generated by the previous step, not just to the
children
•  “//”, described above, is a short from for specifying “all
descendants”
•  “..” specifies the parent.
−  e.g. : /university//name/../salary
Q2: Give XPath Expression
Give a list of courses
that are lectured at the
computer science
department and that
have at least 4 credits.
university
department
Taylor
Comp. Sci.
course
Comp. Sci.
4
dept_name
building
credits
ROOT
dept_name
XPath as a Query Language for XML
•  XPath can be used directly as a retrieval language
•  Select and return nodes in an XML document
•  However, XPath cannot:
−  Restructure,
−  Reorder,
−  Create new elements
•  Therefore, there are other query languages that use
XPath as a component
•  E.g., XQuery à Does allow restructuring
Where to find more information?
•  XPath reference by 3WC:
http://www.w3.org/TR/xpath/
•  Try out some queries yourself:
http://en.wikipedia.org/wiki/XML_database
•  BaseX is nice for educational purposes
http://www.inf.uni-konstanz.de/dbis/basex/
XQuery
•  Allows to formulate more general queries than XPath
•  General expression: FLWOR expression
FOR < for-variable > IN < in-expression >
LET < let-variable > := < let-expression>
[ WHERE < filter-expression> ]
[ ORDER BY < order-specification > ]
RETURN < expression>
−  note: FOR and LET can be used together or in
isolation
Example: retrieve the name of instructors who
have a salary that is higher than 30000
for $x in doc(”university.xml")/university/instructor
where $x/salary>30000
return <instr> {$x/name} </instr>
Q3: Give XQuery Expression
Give a list of courses that are
lectured at the computer
science department and that
have at least 4 credits.
Syntax:
FOR < for-variable > IN < in-expression >
LET < let-variable > := < let-expression>
[ WHERE < filter-expression> ]
[ ORDER BY < order-specification > ]
RETURN < expression>
university
department
Taylor
Comp. Sci.
course
Comp. Sci.
4
dept_name
building
credits
ROOT
dept_name
Joins
for $c in /university/course,
$i in /university/instructor
where $c/course_id=$i/teaches
return <course_instructor> { $c $i } </course_instructor>
FLWOR Expression
•  A FLWOR expression binds some variables, applies
a predicate and constructs a new result.
for var in expr
let var := expr
where expr
order by expr return expr
FLWOR Expression
•  A FLWOR expression binds some variables, applies
a predicate and constructs a new result.
for var in expr
let var := expr
where expr
order by expr return expr
Anything that
creates a sequence
of items
Anything that
creates true or false
Anything that
creates a sequence
atomic values
Any XQuery
Expression
FLWOR Expression
•  FOR clause
for $c in document(“university.xml”)
//courses,
$i in document(“university.xml”)
//instructor
−  specify documents used in the query
−  declare variables and bind them to a range
−  result is a list of bindings
•  LET clause
let $id := $i/@Id,
$cn := $c/name
−  bind variables to a value
FLWOR Expression
•  WHERE clause
where $c/@CrsCode =
$t/CrsTaken/@CrsCode and
$c/@Semester =
$t/CrsTaken/@Semester
−  selects a sublist of the list of bindings
•  RETURN clause
return
<CrsStud>
{$cn} <Name> {$sn} </Name>
</CrsStud>
−  construct result for every selected binding
Nested queries
<university-1>
{
for $d in /university/department
return
<department>
{ $d/* }
{for $c in /university/course[dept_name=
$d/dept_name] return $c}
</department>
}
</university-1>
Aggregate functions
for $d in /university/department
return
<department_total_salary>
<dept_name>{$d/dep_name}</dept_name>
<total_salary>{fn:sum(
for $i in /university/instructor[dept_name=$d/dept_name]
return $i/salary
)} </total_salary>
</department_total_salary>
Q4: Retrieve the total budget of the university.
for $i in /university/
department
return fn:sum($i/budget)
university
department
100000
Comp. Sci.
course
Comp. Sci.
4
dept_name
budget
credits
ROOT
dept_name
Sorting
for $i in /university/instructor
order by $i/name descending
return <instructor>{$i/*}</instructor>
XQuery Expressions: Operators
• = compares the content of an item
•  Content of an element = concatenation of all its text-
descendants in document order
•  Content of an atomic value = the atomic value
•  Content of an attribute = its value
Examples:
<a/> = <b/>,
<d><a/><c>2</c></d> = <b>2</b>,
<a></a>=<c>3</c>
Result:
true, true, false
XQuery Expressons: Built-in Functions
•  Functions on sequences of nodes; result in doc.
order without dupl.
•  union intersect except
•  Functions returning values
•  empty() true if empty sequence
•  count() number of items in the sequence
•  data() sequence of the values of the nodes
•  distinct-values() sequence of the values of the
nodes, without duplicates
XQuery Expressons: Built-in Functions
•  On nodes
•  string() value of the node
•  On strings
•  contains() true if first string contains second
•  ends-with() true if second string is suffix of first
•  On sequences of integers:
•  min(), max(), avg()
XQuery Expressions: Choice
• if (condition) then expression else
expression
• if (not(empty(./author[3])))
then “et al.”
else “.”
User-defined functions
•  Body can be any XQuery expression, recursion is
allowed
declare function local:fname
($var1, …, $vark) {
XQuery expression
possibly involving fname itself again
};
User-defined functions
•  Count number of descendants
declare function local:countElemNodes($e) {
if (empty($e/*)) then 0
else local:countElemNodes($e/*)+count($e/*)
};
local:countElemNodes(<a><b/><c>Text</c></a>)
•  Result : 2
Existential and universal quantification
•  existential quantification
some $e in path satisfies P
•  universal quantification
every $e in path satisfies P
Example. Find departments where every instructor has a
salary greater than $50,000
for $d in /university/department
where every $i in /university/instructor[dept_name=$d/
dept_name]
satisfies $i/salary>50000
return $d
Q5: Give for every course the id and title of the
course and the names of the lecturers
for $i in //course
return <course> {$i/course_id} {$i/title}
{for $j in //instructor
where $i/course_id=$j/teaches
return $j/name}
</course>
Q6: Give the names of instructors at the
university, not including duplicates.
for $i in //instructor
return <inst> {distinct-values($i/name)}</inst>
Q5: Give the name of the instructor who is
involved in most courses.
for $inst in //instructor
let $i:=max(/count(//instructor/teaches))
where count($inst/teaches)=$i
return $inst/name
More Information?
•  Many many examples: XML XQuery Use Case
http://www.w3.org/TR/xquery-use-cases/
k.verbert@tue.nl
g.h.l.fletcher@tue.nl

Mais conteúdo relacionado

Mais procurados (20)

Xpath presentation
Xpath presentationXpath presentation
Xpath presentation
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
XML
XMLXML
XML
 
Xml
XmlXml
Xml
 
Xml ppt
Xml pptXml ppt
Xml ppt
 
XML, DTD & XSD Overview
XML, DTD & XSD OverviewXML, DTD & XSD Overview
XML, DTD & XSD Overview
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Object Oriented Programming Principles
Object Oriented Programming PrinciplesObject Oriented Programming Principles
Object Oriented Programming Principles
 
XSLT
XSLTXSLT
XSLT
 
Json
JsonJson
Json
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Xml presentation
Xml presentationXml presentation
Xml presentation
 
Web ontology language (owl)
Web ontology language (owl)Web ontology language (owl)
Web ontology language (owl)
 
Adbms 17 object query language
Adbms 17 object query languageAdbms 17 object query language
Adbms 17 object query language
 
XML
XMLXML
XML
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Xml
Xml Xml
Xml
 

Destaque

Destaque (20)

XQuery - a technical overview
XQuery -  a technical overviewXQuery -  a technical overview
XQuery - a technical overview
 
Xpath
XpathXpath
Xpath
 
Xpath
XpathXpath
Xpath
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xquery
 
X Query
X QueryX Query
X Query
 
XQuery
XQueryXQuery
XQuery
 
XQuery - The GSD (Getting Stuff Done) language
XQuery - The GSD (Getting Stuff Done) languageXQuery - The GSD (Getting Stuff Done) language
XQuery - The GSD (Getting Stuff Done) language
 
XML In The Real World - Use Cases For Oracle XMLDB
XML In The Real World - Use Cases For Oracle XMLDBXML In The Real World - Use Cases For Oracle XMLDB
XML In The Real World - Use Cases For Oracle XMLDB
 
Processamento consultas-xml-v2
Processamento consultas-xml-v2Processamento consultas-xml-v2
Processamento consultas-xml-v2
 
XSL, XSL-FO e XSLT + XPath
XSL, XSL-FO e XSLT + XPathXSL, XSL-FO e XSLT + XPath
XSL, XSL-FO e XSLT + XPath
 
Querying rich text with XQuery
Querying rich text with XQueryQuerying rich text with XQuery
Querying rich text with XQuery
 
Xml Presentation-1
Xml Presentation-1Xml Presentation-1
Xml Presentation-1
 
Xml100 1
Xml100 1Xml100 1
Xml100 1
 
Xml Presentation-3
Xml Presentation-3Xml Presentation-3
Xml Presentation-3
 
XSLT for Web Developers
XSLT for Web DevelopersXSLT for Web Developers
XSLT for Web Developers
 
XML.ppt
XML.pptXML.ppt
XML.ppt
 
Xquery
XqueryXquery
Xquery
 
XML - Data Modeling
XML - Data ModelingXML - Data Modeling
XML - Data Modeling
 
Jms deep dive [con4864]
Jms deep dive [con4864]Jms deep dive [con4864]
Jms deep dive [con4864]
 
SQL Server - Querying and Managing XML Data
SQL Server - Querying and Managing XML DataSQL Server - Querying and Managing XML Data
SQL Server - Querying and Managing XML Data
 

Semelhante a Querying XML: XPath and XQuery

Deep dive formatting
Deep dive formattingDeep dive formatting
Deep dive formattingThomas Lee
 
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year csUNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year csjaved75
 
XML on SQL Server
XML on SQL ServerXML on SQL Server
XML on SQL Servertorp42
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Getachew Ganfur
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)Rathod Shukar
 
CONSIDERING STRUCTURAL AND VOCABULARY HETEROGENEITY IN XML QUERY: FPTPQ AND H...
CONSIDERING STRUCTURAL AND VOCABULARY HETEROGENEITY IN XML QUERY: FPTPQ AND H...CONSIDERING STRUCTURAL AND VOCABULARY HETEROGENEITY IN XML QUERY: FPTPQ AND H...
CONSIDERING STRUCTURAL AND VOCABULARY HETEROGENEITY IN XML QUERY: FPTPQ AND H...ijdms
 
Considering Structural and Vocabulary Heterogeneity in XML Query: FPTPQ and H...
Considering Structural and Vocabulary Heterogeneity in XML Query: FPTPQ and H...Considering Structural and Vocabulary Heterogeneity in XML Query: FPTPQ and H...
Considering Structural and Vocabulary Heterogeneity in XML Query: FPTPQ and H...ijdms
 
SQL/XML on Oracle
SQL/XML on OracleSQL/XML on Oracle
SQL/XML on Oracletorp42
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpAlena Holligan
 
Approaches to document/report generation
Approaches to document/report generation Approaches to document/report generation
Approaches to document/report generation plutext
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Xml and webdata
Xml and webdataXml and webdata
Xml and webdataFraboni Ec
 
Xml and webdata
Xml and webdataXml and webdata
Xml and webdataJames Wong
 

Semelhante a Querying XML: XPath and XQuery (20)

Deep dive formatting
Deep dive formattingDeep dive formatting
Deep dive formatting
 
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year csUNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year cs
 
XML on SQL Server
XML on SQL ServerXML on SQL Server
XML on SQL Server
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
 
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
 
CONSIDERING STRUCTURAL AND VOCABULARY HETEROGENEITY IN XML QUERY: FPTPQ AND H...
CONSIDERING STRUCTURAL AND VOCABULARY HETEROGENEITY IN XML QUERY: FPTPQ AND H...CONSIDERING STRUCTURAL AND VOCABULARY HETEROGENEITY IN XML QUERY: FPTPQ AND H...
CONSIDERING STRUCTURAL AND VOCABULARY HETEROGENEITY IN XML QUERY: FPTPQ AND H...
 
Considering Structural and Vocabulary Heterogeneity in XML Query: FPTPQ and H...
Considering Structural and Vocabulary Heterogeneity in XML Query: FPTPQ and H...Considering Structural and Vocabulary Heterogeneity in XML Query: FPTPQ and H...
Considering Structural and Vocabulary Heterogeneity in XML Query: FPTPQ and H...
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
SQL/XML on Oracle
SQL/XML on OracleSQL/XML on Oracle
SQL/XML on Oracle
 
1 xml fundamentals
1 xml fundamentals1 xml fundamentals
1 xml fundamentals
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
Approaches to document/report generation
Approaches to document/report generation Approaches to document/report generation
Approaches to document/report generation
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Xml and webdata
Xml and webdataXml and webdata
Xml and webdata
 
Xml and webdata
Xml and webdataXml and webdata
Xml and webdata
 
Xml and webdata
Xml and webdataXml and webdata
Xml and webdata
 
Xml and webdata
Xml and webdataXml and webdata
Xml and webdata
 

Mais de Katrien Verbert

Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Katrien Verbert
 
Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Katrien Verbert
 
Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?Katrien Verbert
 
Explaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspectiveExplaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspectiveKatrien Verbert
 
Explaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learnedExplaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learnedKatrien Verbert
 
Designing Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons LearnedDesigning Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons LearnedKatrien Verbert
 
Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...Katrien Verbert
 
Explainable AI for non-expert users
Explainable AI for non-expert usersExplainable AI for non-expert users
Explainable AI for non-expert usersKatrien Verbert
 
Towards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methodsTowards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methodsKatrien Verbert
 
Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...Katrien Verbert
 
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...Katrien Verbert
 
Learning analytics for feedback at scale
Learning analytics for feedback at scaleLearning analytics for feedback at scale
Learning analytics for feedback at scaleKatrien Verbert
 
Interactive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learningInteractive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learningKatrien Verbert
 
Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”Katrien Verbert
 
Interactive Recommender Systems
Interactive Recommender SystemsInteractive Recommender Systems
Interactive Recommender SystemsKatrien Verbert
 
Web Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTMLWeb Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTMLKatrien Verbert
 
Information Visualisation: perception and principles
Information Visualisation: perception and principlesInformation Visualisation: perception and principles
Information Visualisation: perception and principlesKatrien Verbert
 
Web Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: IntroductionWeb Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: IntroductionKatrien Verbert
 
Information Visualisation: Introduction
Information Visualisation: IntroductionInformation Visualisation: Introduction
Information Visualisation: IntroductionKatrien Verbert
 

Mais de Katrien Verbert (20)

Explainability methods
Explainability methodsExplainability methods
Explainability methods
 
Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?
 
Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?
 
Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?
 
Explaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspectiveExplaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspective
 
Explaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learnedExplaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learned
 
Designing Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons LearnedDesigning Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons Learned
 
Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...
 
Explainable AI for non-expert users
Explainable AI for non-expert usersExplainable AI for non-expert users
Explainable AI for non-expert users
 
Towards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methodsTowards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methods
 
Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...
 
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
 
Learning analytics for feedback at scale
Learning analytics for feedback at scaleLearning analytics for feedback at scale
Learning analytics for feedback at scale
 
Interactive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learningInteractive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learning
 
Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”
 
Interactive Recommender Systems
Interactive Recommender SystemsInteractive Recommender Systems
Interactive Recommender Systems
 
Web Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTMLWeb Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTML
 
Information Visualisation: perception and principles
Information Visualisation: perception and principlesInformation Visualisation: perception and principles
Information Visualisation: perception and principles
 
Web Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: IntroductionWeb Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: Introduction
 
Information Visualisation: Introduction
Information Visualisation: IntroductionInformation Visualisation: Introduction
Information Visualisation: Introduction
 

Último

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Último (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

Querying XML: XPath and XQuery

  • 1. Querying XML: XPath and XQuery Lecture 8a 2ID35, Spring 2013 24 May 2013 Katrien Verbert George Fletcher Slides based on lectures of Prof. T. Calders and Prof. H. Olivié
  • 2. Table of Contents 1.  Introduction to XML 2.  Querying XML a)  XPath b)  XQuery
  • 3. 1. Introduction to XML •  Why is XML important? •  simple open non-proprietary widely accepted data exchange format •  XML is like HTML but •  no fixed set of tags −  X = “extensible” •  no fixed semantics (c.q. representation) of tags −  representation determined by separate ‘style sheet’ −  semantics determined by application •  no fixed structure −  user-defined schemas
  • 4. <?xml version ="1.0"?> <university> <department> <dept_name>Comp. Sci.</dept_name> <building>Taylor</building> <budget>100000</budget> </department> <course> <course_id>CS-101</course_id> <title>Intro to Comp. Science</title> <dept_name>Comp. Sci.</dept_name> <credits>4</credits> </course> . . . XML-document – Running example 1 (1/2)
  • 5. XML-document – Running example 1 (2/2) . . . <instructor Id=“10101”> <name>Srinivasan</name> <dept_name>Comp. Sci.</dept_name> <salary>65000</salary> <teaches>CS-101</teaches> </instructor> </university>
  • 6. Elements of an XML Document •  Global structure •  Mandatory first line <?xml version ="1.0"?> •  A single root element <university> . . . </university> •  Elements have a recursive structure •  Tags are chosen by author; <department>, <dept_name>, <building> •  Opening tag must have a matching closing tag <university></university>, <a><b></b></a>
  • 7. Elements of an XML Document •  The content of an element is a sequence of: −  Elements <instructor> … </instructor> −  Text Jan Vijs −  Processing Instructions <! . . . !> −  Comments <!– This is a comment --!> •  Empty elements can be abbreviated: <instructor/> is shorthand for <instructor></instructor>
  • 8. Elements of an XML Document •  Elements can have attributes <Title Value="Student List"/> <PersonList Type="Student" Date="2004-12-12"> . . . </Personlist> Attribute_name = “Value” Attribute name can only occur once Value is always quoted text (even numbers)
  • 9. Elements of an XML Document •  Text and elements can be freely mixed <Course ID=“2ID45”> The course <fullname>Database Technology</fullname> is lectured by <title>dr.</title> <fname>George</fname> <sname>Fletcher</sname> </Course> •  The order between elements is considered important •  Order between attributes is not
  • 10. Well-formedness •  We call an XML-document well-formed iff •  it has one root element; •  elements are properly nested; •  any attribute can only occur once in a given opening tag and its value must be quoted. •  Check for instance at: http://www.w3schools.com/xml/xml_validator.asp
  • 11. Table of Contents 1.  Introduction to XML 2.  Querying XML a)  Xpath b)  XQuery
  • 12. 12 Querying and Transforming XML Data •  XPath •  Simple language consisting of path expressions •  XQuery •  Standard language for querying XML data •  Modeled after SQL (but significantly different) •  Incorporates XPath expressions
  • 13. 13 Tree Model of XML Data •  Query and transformation languages are based on a tree model of XML data •  An XML document is modeled as a tree, with nodes corresponding to elements and attributes −  Element nodes have children nodes, which can be attributes or subelements −  Text in an element is modeled as a text node child of the element −  Children of a node are ordered according to their order in the XML document −  Element and attribute nodes (except for the root node) have a single parent, which is an element node −  The root node has a single child, which is the root element of the document
  • 14. Tree Model of XML Data (Cont) ROOT university department Taylor Comp. Sci. instructor _123456789 id M university Comp. Sci. Element node Text node dept_name building name id Attribute node
  • 15. 15 XPath •  XPath is used to address (select) parts of documents using path expressions •  A path expression is a sequence of steps separated by “/” •  Think of file names in a directory hierarchy •  Result of path expression: set of values that along with their containing elements/attributes match the specified path
  • 20. XPath (example) /university/instructor <instructor Id="_123456789”> <name>Paul De Bra</name> .... </instructor> <instructor Id="_333445555”> <name>George Fletcher</name> ….. </instructor> <instructor Id="_999887777”> <name>Katrien Verbert</name> ..... 20 ROOT university instructor Id _333445555 instructor Id _123456789 instructor Id _999887777
  • 21. 21 XPath (Cont.) •  The initial “/” denotes root of the document (above the top-level tag) •  Path expressions are evaluated left to right •  Each step operates on the set of instances produced by the previous step •  Selection predicates may follow in [ ] •  E.g. /university/instructor[salary > 40000] −  returns instructor elements with a salary value greater than 40000 •  Attributes are accessed using “@” •  E.g. /university/instructor[salary > 40000]/@Id −  returns the Ids of the instructors with salary greater than 40000
  • 22. Q1: give XPath expression Retrieve instructor with Id _123456789 /university/ instructor [@Id=“_123456789”] 22 ROOT university instructor Id _333445555 instructor Id _123456789 instructor Id _999887777
  • 23. 23 Functions in XPath •  XPath provides several functions The function count() takes a nodeset as its argument and returns the number of nodes present in the nodeset. E.g. /university/instructor[count(teaches) = 3] Returns instructors who are involved in 3 courses •  Function not() can be used in predicates •  //instructor[not(teaches)]
  • 24. 24 More XPath Features •  Operator or used to implement union •  E.g. //instructor[count(teaches) = 1 or not (teaches)] gives instructors with either 0 or 1 courses •  “//” can be used to skip multiple levels of nodes •  E.g. /university//name −  finds any name element anywhere under the /university element, regardless of the element in which it is contained. •  A step in the path can go to: parents, siblings, ancestors and descendants of the nodes generated by the previous step, not just to the children •  “//”, described above, is a short from for specifying “all descendants” •  “..” specifies the parent. −  e.g. : /university//name/../salary
  • 25. Q2: Give XPath Expression Give a list of courses that are lectured at the computer science department and that have at least 4 credits. university department Taylor Comp. Sci. course Comp. Sci. 4 dept_name building credits ROOT dept_name
  • 26. XPath as a Query Language for XML •  XPath can be used directly as a retrieval language •  Select and return nodes in an XML document •  However, XPath cannot: −  Restructure, −  Reorder, −  Create new elements •  Therefore, there are other query languages that use XPath as a component •  E.g., XQuery à Does allow restructuring
  • 27. Where to find more information? •  XPath reference by 3WC: http://www.w3.org/TR/xpath/ •  Try out some queries yourself: http://en.wikipedia.org/wiki/XML_database •  BaseX is nice for educational purposes http://www.inf.uni-konstanz.de/dbis/basex/
  • 28. XQuery •  Allows to formulate more general queries than XPath •  General expression: FLWOR expression FOR < for-variable > IN < in-expression > LET < let-variable > := < let-expression> [ WHERE < filter-expression> ] [ ORDER BY < order-specification > ] RETURN < expression> −  note: FOR and LET can be used together or in isolation
  • 29. Example: retrieve the name of instructors who have a salary that is higher than 30000 for $x in doc(”university.xml")/university/instructor where $x/salary>30000 return <instr> {$x/name} </instr>
  • 30. Q3: Give XQuery Expression Give a list of courses that are lectured at the computer science department and that have at least 4 credits. Syntax: FOR < for-variable > IN < in-expression > LET < let-variable > := < let-expression> [ WHERE < filter-expression> ] [ ORDER BY < order-specification > ] RETURN < expression> university department Taylor Comp. Sci. course Comp. Sci. 4 dept_name building credits ROOT dept_name
  • 31. Joins for $c in /university/course, $i in /university/instructor where $c/course_id=$i/teaches return <course_instructor> { $c $i } </course_instructor>
  • 32. FLWOR Expression •  A FLWOR expression binds some variables, applies a predicate and constructs a new result. for var in expr let var := expr where expr order by expr return expr
  • 33. FLWOR Expression •  A FLWOR expression binds some variables, applies a predicate and constructs a new result. for var in expr let var := expr where expr order by expr return expr Anything that creates a sequence of items Anything that creates true or false Anything that creates a sequence atomic values Any XQuery Expression
  • 34. FLWOR Expression •  FOR clause for $c in document(“university.xml”) //courses, $i in document(“university.xml”) //instructor −  specify documents used in the query −  declare variables and bind them to a range −  result is a list of bindings •  LET clause let $id := $i/@Id, $cn := $c/name −  bind variables to a value
  • 35. FLWOR Expression •  WHERE clause where $c/@CrsCode = $t/CrsTaken/@CrsCode and $c/@Semester = $t/CrsTaken/@Semester −  selects a sublist of the list of bindings •  RETURN clause return <CrsStud> {$cn} <Name> {$sn} </Name> </CrsStud> −  construct result for every selected binding
  • 36. Nested queries <university-1> { for $d in /university/department return <department> { $d/* } {for $c in /university/course[dept_name= $d/dept_name] return $c} </department> } </university-1>
  • 37. Aggregate functions for $d in /university/department return <department_total_salary> <dept_name>{$d/dep_name}</dept_name> <total_salary>{fn:sum( for $i in /university/instructor[dept_name=$d/dept_name] return $i/salary )} </total_salary> </department_total_salary>
  • 38. Q4: Retrieve the total budget of the university. for $i in /university/ department return fn:sum($i/budget) university department 100000 Comp. Sci. course Comp. Sci. 4 dept_name budget credits ROOT dept_name
  • 39. Sorting for $i in /university/instructor order by $i/name descending return <instructor>{$i/*}</instructor>
  • 40. XQuery Expressions: Operators • = compares the content of an item •  Content of an element = concatenation of all its text- descendants in document order •  Content of an atomic value = the atomic value •  Content of an attribute = its value Examples: <a/> = <b/>, <d><a/><c>2</c></d> = <b>2</b>, <a></a>=<c>3</c> Result: true, true, false
  • 41. XQuery Expressons: Built-in Functions •  Functions on sequences of nodes; result in doc. order without dupl. •  union intersect except •  Functions returning values •  empty() true if empty sequence •  count() number of items in the sequence •  data() sequence of the values of the nodes •  distinct-values() sequence of the values of the nodes, without duplicates
  • 42. XQuery Expressons: Built-in Functions •  On nodes •  string() value of the node •  On strings •  contains() true if first string contains second •  ends-with() true if second string is suffix of first •  On sequences of integers: •  min(), max(), avg()
  • 43. XQuery Expressions: Choice • if (condition) then expression else expression • if (not(empty(./author[3]))) then “et al.” else “.”
  • 44. User-defined functions •  Body can be any XQuery expression, recursion is allowed declare function local:fname ($var1, …, $vark) { XQuery expression possibly involving fname itself again };
  • 45. User-defined functions •  Count number of descendants declare function local:countElemNodes($e) { if (empty($e/*)) then 0 else local:countElemNodes($e/*)+count($e/*) }; local:countElemNodes(<a><b/><c>Text</c></a>) •  Result : 2
  • 46. Existential and universal quantification •  existential quantification some $e in path satisfies P •  universal quantification every $e in path satisfies P Example. Find departments where every instructor has a salary greater than $50,000 for $d in /university/department where every $i in /university/instructor[dept_name=$d/ dept_name] satisfies $i/salary>50000 return $d
  • 47. Q5: Give for every course the id and title of the course and the names of the lecturers for $i in //course return <course> {$i/course_id} {$i/title} {for $j in //instructor where $i/course_id=$j/teaches return $j/name} </course>
  • 48. Q6: Give the names of instructors at the university, not including duplicates. for $i in //instructor return <inst> {distinct-values($i/name)}</inst>
  • 49. Q5: Give the name of the instructor who is involved in most courses. for $inst in //instructor let $i:=max(/count(//instructor/teaches)) where count($inst/teaches)=$i return $inst/name
  • 50. More Information? •  Many many examples: XML XQuery Use Case http://www.w3.org/TR/xquery-use-cases/