SlideShare une entreprise Scribd logo
1  sur  51
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances (20)

CS8080 INFORMATION RETRIEVAL TECHNIQUES - IRT - UNIT - I PPT IN PDF
CS8080 INFORMATION RETRIEVAL TECHNIQUES - IRT - UNIT - I  PPT  IN PDFCS8080 INFORMATION RETRIEVAL TECHNIQUES - IRT - UNIT - I  PPT  IN PDF
CS8080 INFORMATION RETRIEVAL TECHNIQUES - IRT - UNIT - I PPT IN PDF
 
The semantic web
The semantic web The semantic web
The semantic web
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Model of information retrieval (3)
Model  of information retrieval (3)Model  of information retrieval (3)
Model of information retrieval (3)
 
Xpath presentation
Xpath presentationXpath presentation
Xpath presentation
 
Information Retrieval Models
Information Retrieval ModelsInformation Retrieval Models
Information Retrieval Models
 
CS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdfCS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdf
 
Information retrieval (introduction)
Information  retrieval (introduction) Information  retrieval (introduction)
Information retrieval (introduction)
 
Introduction to RDF
Introduction to RDFIntroduction to RDF
Introduction to RDF
 
Xml schema
Xml schemaXml schema
Xml schema
 
Information retrieval 9 tf idf weights
Information retrieval 9 tf idf weightsInformation retrieval 9 tf idf weights
Information retrieval 9 tf idf weights
 
RDF, linked data and semantic web
RDF, linked data and semantic webRDF, linked data and semantic web
RDF, linked data and semantic web
 
Inverted index
Inverted indexInverted index
Inverted index
 
web service technologies
web service technologiesweb service technologies
web service technologies
 
Querying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQLQuerying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQL
 
Json
JsonJson
Json
 
Data mining tasks
Data mining tasksData mining tasks
Data mining tasks
 
XQuery
XQueryXQuery
XQuery
 
jstl ( jsp standard tag library )
jstl ( jsp standard tag library )jstl ( jsp standard tag library )
jstl ( jsp standard tag library )
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
 

En vedette

XQuery - a technical overview
XQuery -  a technical overviewXQuery -  a technical overview
XQuery - a technical overviewLoren Cahlander
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xqueryAmol Pujari
 
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) languagejimfuller2009
 
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 XMLDBMarco Gralike
 
Processamento consultas-xml-v2
Processamento consultas-xml-v2Processamento consultas-xml-v2
Processamento consultas-xml-v2Luiz Matos
 
Querying rich text with XQuery
Querying rich text with XQueryQuerying rich text with XQuery
Querying rich text with XQuerylucenerevolution
 
Xml Presentation-1
Xml Presentation-1Xml Presentation-1
Xml Presentation-1Sudharsan S
 
Xml Presentation-3
Xml Presentation-3Xml Presentation-3
Xml Presentation-3Sudharsan S
 
XML.ppt
XML.pptXML.ppt
XML.pptbutest
 
XML - Data Modeling
XML - Data ModelingXML - Data Modeling
XML - Data ModelingJoel Briza
 
Jms deep dive [con4864]
Jms deep dive [con4864]Jms deep dive [con4864]
Jms deep dive [con4864]Ryan Cuprak
 
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 DataMarek Maśko
 
XPath - XML Path Language
XPath - XML Path LanguageXPath - XML Path Language
XPath - XML Path Languageyht4ever
 

En vedette (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 - 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
 
XPath - XML Path Language
XPath - XML Path LanguageXPath - XML Path Language
XPath - XML Path Language
 

Similaire à 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
 

Similaire à 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
 

Plus 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
 

Plus 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
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Dernier (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

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/