Introduction to XQuery Bun Yue Professor, CS/CIS UHCL.

Slides:



Advertisements
Similar presentations
XML Data Management 8. XQuery Werner Nutt. Requirements for an XML Query Language David Maier, W3C XML Query Requirements: Closedness: output must be.
Advertisements

XML: Extensible Markup Language
Bottom-up Evaluation of XPath Queries Stephanie H. Li Zhiping Zou.
XML May 3 rd, XQuery Based on Quilt (which is based on XML-QL) Check out the W3C web site for the latest. XML Query data model –Ordered !
XML, XML Schema, Xpath and XQuery Slides collated from various sources, many from Dan Suciu at Univ. of Washington.
XQuery John Annechino Steven Pow. Agenda What is XQuery? Uses of XQuery XQuery vs. XSLT Syntax –Built-In Functions –FLWOR –if-then-else –User-Defined.
XQUERY. What is XQuery? XQuery is the language for querying XML data The best way to explain XQuery is to say that XQuery is to XML what SQL is to database.
1 XQuery Web and Database Management System. 2 XQuery XQuery is to XML what SQL is to database tables XQuery is designed to query XML data What is XQuery?
Agenda from now on Done: SQL, views, transactions, conceptual modeling, E/R, relational algebra. Starting: XML To do: the database engine: –Storage –Query.
Friday, September 4 th, 2009 The Systems Group at ETH Zurich XML and Databases Exercise Session 6 courtesy of Ghislain Fourny/ETH © Department of Computer.
IS432: Semi-Structured Data Dr. Azeddine Chikh. 7. XQuery.
XQuery: 1 W3C (World Wide Web Consortium) What is W3C? –An industry consortium, best known for standardizing HTML and XML. –Working Groups create or adopt.
A Graphical Environment to Query XML Data with XQuery
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 357 Database Systems I Query Languages for XML.
XQL (XML Query Language) Jonathan Robie (Software AG) Eduard Derksen (CSCIO) Peter Fankhauser (GMD-IPSI) Ed Howland (DEGA) Gerald Huck (GMD-IPSI) Ingo.
1 COS 425: Database and Information Management Systems XML and information exchange.
XQuery – The W3C XML Query Language Jonathan Robie, Software AG Don Chamberlin, IBM Research Daniela Florescu, INRIA.
XML QUERY LANGUAGE Prepared by Prof. Zaniolo, Hung-chih Yang, Ling-Jyh Chen Modified by Fernando Farfán.
XML –Query Languages, Extracting from Relational Databases ADVANCED DATABASES Khawaja Mohiuddin Assistant Professor Department of Computer Sciences Bahria.
September 15, 2003Houssam Haitof1 XSL Transformation Houssam Haitof.
Processing of structured documents Spring 2003, Part 8 Helena Ahonen-Myka.
Overview of XPath Author: Dan McCreary Date: October, 2008 Version: 0.2 with TEI Examples M D.
Introduction to XPath Bun Yue Professor, CS/CIS UHCL.
XMLII XSchema XSchema XQuery XQuery. XML Schema XML Schema is a more sophisticated schema language which addresses the drawbacks of DTDs. Supports XML.
XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ capabilities allow you to write query expressions that retrieve.
Advisor: Prof. Zaniolo Hung-chih Yang Ling-Jyh Chen XML Query Language.
2005rel-xml-iii1  View forests and query composition The composition algorithm works for a (large) subset of XQuery, excluding : (see paper for details)
Lecture 21 XML querying. 2 XSL (eXtensible Stylesheet Language) In HTML, default styling is built into browsers as tag set for HTML is predefined and.
Lecture 6 of Advanced Databases XML Schema, Querying & Transformation Instructor: Mr.Ahmed Al Astal.
Introduction to XQuery Resources: Official URL: Short intros:
TDDD43 XML and RDF Slides based on slides by Lena Strömbäck and Fang Wei-Kleiner 1.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui SWEN 432 Advanced Database Design and Implementation An Introduction to XQuery.
XP New Perspectives on XML Tutorial 6 1 TUTORIAL 6 XSLT Tutorial – Carey ISBN
XP 1 CREATING AN XML DOCUMENT. XP 2 INTRODUCING XML XML stands for Extensible Markup Language. A markup language specifies the structure and content of.
WORKING WITH XSLT AND XPATH
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui SWEN 432 Advanced Database Design and Implementation An Introduction to XQuery.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 6 XSLT (Based on Møller and Schwartzbach,
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui SWEN 432 Advanced Database Design and Implementation eXist Update Lecturer.
Chapter 27 The World Wide Web and XML. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.27-2 Topics in this Chapter The Web and the Internet.
Processing of structured documents Spring 2002, Part 2 Helena Ahonen-Myka.
Lecture 22 XML querying. 2 Example 31.5 – XQuery FLWOR Expressions ‘=’ operator is a general comparison operator. XQuery also defines value comparison.
XQL, OQL and SQL Xia Tang Sixin Qian Shijun Shen Feb 18, 2000.
XPath. Why XPath? Common syntax, semantics for [XSLT] [XPointer][XSLT] [XPointer] Used to address parts of an XML document Provides basic facilities for.
1 XSLT An Introduction. 2 XSLT XSLT (extensible Stylesheet Language:Transformations) is a language primarily designed for transforming the structure of.
CITA 330 Section 6 XSLT. Transforming XML Documents to XHTML Documents XSLT is an XML dialect which is declared under namespace "
XSLT Kanda Runapongsa Dept. of Computer Engineering Khon Kaen University.
Unit 04 : XQuery COMP 5323 Web Database Technologies and Applications 2014.
Database Systems Part VII: XML Querying Software School of Hunan University
SDPL 2002Notes 9: XQuery1 9 Querying XML Data and Documents n XQuery, W3C XML Query Language –"work in progress", Working Draft, 30 April 2002 –joint work.
[ Part III of The XML seminar ] Presenter: Xiaogeng Zhao A Introduction of XQL.
Chapter 27 The World Wide Web and XML. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.27-2 Topics in this Chapter The Web and the Internet.
XML query. introduction An XML document can represent almost anything, and users of an XML query language expect it to perform useful queries on whatever.
XML Query: xQuery Reference: Xquery By Priscilla Walmsley, Published by O’Reilly.
Session II Chapter 3 – Chapter 3 – XPath Patterns & Expressions Chapter 4 – XPath Functions Chapter 15 – XPath 2.0http://
IS432 Semi-Structured Data Lecture 6: XQuery Dr. Gamal Al-Shorbagy.
Friday, September 4 th, 2009 The Systems Group at ETH Zurich XML and Databases Exercise Session 5 courtesy of Ghislain Fourny/ETH © Department of Computer.
XPath --XML Path Language Motivation of XPath Data Model and Data Types Node Types Location Steps Functions XPath 2.0 Additional Functionality and its.
Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type.
CSE 6331 © Leonidas Fegaras XQuery 1 XQuery Leonidas Fegaras.
Lecture 17: XPath and XQuery Wednesday, Nov. 7, 2001.
Querying XML, Part II Zachary G. Ives University of Pennsylvania CIS 455 / 555 – Internet and Web Systems February 5, 2008.
SEMI-STRUCTURED DATA (XML) 1. SEMI-STRUCTURED DATA ER, Relational, ODL data models are all based on schema Structure of data is rigid and known is advance.
1 XSL Transformations (XSLT). 2 XSLT XSLT is a language for transforming XML documents into XHTML documents or to other XML documents. XSLT uses XPath.
SDPL 2005Notes 7: XQuery1 7 Querying XML n How to access different sources (DBs, docs) as XML? n XQuery, W3C XML Query Language –"work in progress", (last.
XQUERY W3C Recommendation 14 December W3C Working.
XML: Extensible Markup Language
Querying and Transforming XML Data
8 Querying XML How to access different sources (DBs, docs) as XML?
{ XML Technologies } BY: DR. M’HAMED MATAOUI
XQuery Leonidas Fegaras.
Presentation transcript:

Introduction to XQuery Bun Yue Professor, CS/CIS UHCL

W3C Recommendations  W3C XQuery XQuery use cases.  XQuery and XPath functions.  XQuery 1.0 and XPath 2.0 Data Model.  XPath  XML Schema Part 1: Structures.  XML Schema Part 2: datatypes.

Introduction  XQuery is designed for effectively query and retrieve information from a diversified XML sources.  The XML sources can be one or more XML documents.  XQuery is derived from Quilt, and has borrowed features from XPath, XQL, SQL, etc.

Introduction  It is a functional language where a query is an expression.  There are three faces of the XQuery languages: A "surface" syntax that programmers may probably use. An XML-based syntax that machine may probably use (XQueryX). A formal semantic that XQuery engine implementators use.

Introduction.  XQuery 1.0 extends XPath 2.0.  The type system of XQuery is based on XML Schema.  A limitation of XQuery: No update or insert.  The basic building block of XQuery is expressions. (In this sense, like SQL, XQuery is not a full programming language.)

Comparing to SQL Relational DB: SQL XML DB: XQuery Basic unitsrelationscollections Recordstuples or rows of schema documents of same schema SchemaRelational Schema DTD, XML Schema Query resultsRelations: unordered list of rows Ordered sequences of nodes.

Review of XPath 2.0  The value of an expression is a sequence, which is an ordered list of items.  An item can be a node or of atomic value.  There are 7 node types: Document Element Attribute Comment Text Processing Instruction Namespace

XQueryX For the corresponding XQueryX can be: census.xml person job Athlete

Data Types  XQuery is strongly typed.  XQuery types are based on XML Schema: using the namespace prefix xs and url: XPath functions and operators: using the namespace prefix xdt and url: datatypes

Types

 xdt:untyped is used to denote element nodes not yet validated.  xdt:untypedAtomic is used to denote atomic types that has not been assigned a more specific type.

Query  A query in XQuery is an expression for reading XML documents or fragments and returning a sequence of well-formed XML fragments  Everything in XQuery is an expression that is evaluated to a value.

Query expressions  Some common forms of XQuery expressions are (these appear in most tutorials): path expressions element constructors FLWR or FLOWR (pronounced as "flower") expressions list expressions conditional expressions quantified expressions datatype expressions

More Queries  Examples of other expressions include: primary expressions sequence expressions arithmetic expressions logical expressions comparison expressions sorting expressions validate expressions

Comments  XQuery comments are embedded within (: and :).

Functions  Supports a collection of about 200 built-in operators and functions to be used within expressions.  Input functions in XQuery include doc() and collection(). They are used to identify the sources of the XML documents.

Input Functions  Input functions: doc() collection().

Prolog  XQuery may have prologs for declarations. Examples: Variable declarations Function declarations Base-URI declarations Version declarations Module import …

Variable Declarations  Format: declare variable $name = expression;  E.g. declare variable $a := doc("census.xml")//person ;

Path Expressions  XQuery 1.0 is a superset of XPath 2.0.  An XPath expression is also an XQuery expression

Editix  Use “View > Windows > XQuery Builder”  For XQ files, use “XSLT/XQuery > Transform using an XQuery Request…” Specify source xq file, xml file and output file. Use.xml extension. If you use.txt extension, only text node contents are output.

Examples declare base-uri "whatever-path"; doc("bib.xml")/* Return basically bib.xml.

Example doc("bib.xml")//* Return many nodes (in a sequence).  Results are not well-formed.

Examples count(doc("census.xml")//person)

Element Constructors  Element constructors can be used to construct XML elements.  If the name, attributes, and content of the element are all constants, the element constructor is based on standard XML notation and is called a direct element constructor (W3C).

Example The XQuery Bun Yue returns Bun Yue

Element Constructors  XQuery expressions can be embedded in the direct element constructors within a pair of curly braces, {}.  For the characters '{' and '}', use '{{' and '}}' respectively.  XQuery expressions may be separated by commas.

Example Bun Yue { doc("bib.xml")//author } Adds Bun Yue to the authors of bib.xml.

Computed Constructors  Computed constructors can also be used to declare nodes: Use the keywords element, attribute, document, text, processing-instruction, comment, or namespace to declare the type of the nodes. Specify the node names for those node types with names (element, attribute, processing instruction, and namespace nodes) Use a pair of braces to define the content expressions. Note the use of commas to separate expressions in the context.

Example (from W3C) element book { attribute isbn {"isbn " }, element title { "Harold and the Purple Crayon"}, element author { element first { "Crockett" }, element last {"Johnson" } }

Example (result) Harold and the Purple Crayon Crockett Johnson

Dynamic Element Names  Computed expressions can be used to create elements with dynamic names.

Example { for $author in doc("bib.xml")//author return element {$author/last/text()} { $author/first }

Example Result W. W. Serge Peter Dan

Example  Note that is a child element. See the difference of: { for $author in doc("bib.xml")//author return element {$author/last/text()} { $author/first/text() }

Example  This example may also result in a runtime error (as the value of may not be suitable for a QName.

FLWOR expressions  FLWOR expressions are one of the most important constructs in XQuery.  You may compare with the SELECT statement of SQL.

FLWOR (W3C) [42] FLWORExpr ::= (ForClause | LetClause)+ WhereClause? OrderByClause? "return" ExprSingle [43] ForClause ::= "for" "$" VarName TypeDeclaration? PositionalVar? "in" ExprSingle ("," "$" VarName TypeDeclaration? PositionalVar? "in" ExprSingle)* [45] LetClause ::= "let" "$" VarName TypeDeclaration? ":=" ExprSingle ("," "$" VarName TypeDeclaration? ":=" ExprSingle)* [123] TypeDeclaration ::= "as" SequenceType [44] PositionalVar ::= "at" "$" VarName [46] WhereClause ::= "where" Expr [47] OrderByClause ::= ("order" "by" | "stable" "order" "by") OrderSpecList [48] OrderSpecList ::= OrderSpec ("," OrderSpec)* [49] OrderSpec ::= ExprSingle OrderModifier [50] OrderModifier ::= ("ascending" | "descending")? (("empty" "greatest") | ("empty" "least"))? ("collation" StringLiteral)?

FLWOR  FLWOR expressions allow: For: Iteration through items in XPath 2.0 sequences. Create a tuple stream where each tuple contains a distinct binding for each variable to a distinct value. Let: Variables binding Where: Predicate application for inclusion in the iteration. Order by: Ordering data set for the iteration. Return: Constructing new result for returning.

For and Let  The for and let clauses produces a tuple stream.  A tuple consists of one or more bound variables.  A variable begins with the prefix $.  A bound variable is one that has been assigned a value.

Example declare base-uri “whatever”; let $a := doc("bib.xml")//author return { $a }

Example Results Stevens W. Stevens W. …

Example Note  In this example: The tuple stream is composed of only one tuple. The variable $b in this tuple is bound to the node sequence of 5 nodes.

Example for $a in doc("bib.xml")//author return { $a }

Example Result Stevens W. Stevens W. …

Example Notes  In this example: The tuple stream is composed of only five tuples. The variable $b in this tuple is bound to one node at a time.

Example for $a in doc("bib.xml")//author, $b in doc("bib.xml")//author return

Example Result … (: 25 counts :)

Example Note The tuple stream is composed of only 25 tuples. The 25 tuples are:  ($a: Stevens W., $b: Stevens W. )  ($a: Stevens W., $b: Abiteboul Serge )  …

Example for $a in doc("bib.xml")//author, $b in $a/last return

Example Result

Example Note The tuple stream is composed of only 5 tuples. The 5 tuples are:  ($a: Stevens W., $b: Stevens</last)  ($a: Abiteboul Serge, $b: Abiteboul</last)  …

Example for $a in doc("bib.xml")//author, $b in doc("bib.xml")//author where $a = $b return { $a/last/text() } { $b/last/text() }

Example Result Stevens … (: three more times. :) Abiteboul Buneman Suciu

Example Note The tuple stream is composed of only 7 tuples. The 7 tuples are:  ($a: Stevens W., $b: Stevens W. ) (: 4 times)  ($a: Abiteboul Serge, $b: Abiteboul Serge )  …

Example {for $f in doc("tree-data.xml")//figure return { } { $f/title } }

Example Result Traditional client/server architecture Graph representations of structures Examples of Relations

Example Note  There are three tuples in the tuple stream of the for clause. Each tuple has one variable: $f, which is bounded to each of the three elements in the input xml contents respectively.  { } returns the attributes of the original elements, which will be put as attributes of the output element.

Example { fn:string-join(for $a in doc("tree- data.xml")//author return $a/text(), ", ") }

Example Result Serge Abiteboul, Peter Buneman, Dan Suciu

Example Note  fn:string-join takes two arguments: A sequence of string, and A string join separator

Example {for $f in doc("tree-data.xml")//figure return { attribute size { * } } }

Example Result

Example { for $f in doc("tree-data.xml")//figure let $size := * order by $size return { attribute size { $size } } }

Example Result

Exercise #1  Use bib.xml, Show all books published by Addison Wesley. TCP/IP Illustrated Stevens W. Advanced Programming in the Unix environment Stevens W.

Exercise #2  All books by Addison-Wesley using different format: TCP/IP Illustrated Advanced Programming in the Unix environment

Exercise #3  All books written by W. Stevens ordered by years: Advanced Programming in the Unix environment TCP/IP Illustrated

Exercise #4  All books written by W. Stevens ordered by years in descending order: TCP/IP Illustrated Advanced Programming in the Unix environment

Exercise #5  Use ft2.xml, return every with its and child elements. Add a child element to include the number of addresses. Boris Becker 2 …

Exercise #6  Return all elements with all attributes. The body of the element should be the name of the person in the format of first name and then last name. For ft2.xml, it returns: Boris Becker Valerie Becker Chris Becker Julie Becker John Becker Mary Becker

Exercise #7  Return all pairs of elements of persons with the same last name, not including pairing with oneself. Each pair of result is embedded in an element with the last name of the persons as the element name. For ft2.xml, it returns: Boris Valerie Boris Chris Boris Julie Boris John Boris Mary Valerie Boris …

Exercise #8  Convert all text nodes to and all elements with name x to. For ft2.xml, it returns: …

Function Declarations  XQuery allows user-defined functions in the prolog. [26] FunctionDecl ::= "declare" "function" QName "(" ParamList? ")" ("as" SequenceType)? (EnclosedExpr | "external")FunctionDecl QNameParamList SequenceTypeEnclosedExpr [27] ParamList ::= Param ("," Param)*ParamListParam [28] Param ::= "$" QName TypeDeclaration?ParamQName TypeDeclaration [118] TypeDeclaration ::= "as" SequenceTypeTypeDeclaration SequenceType

Example: factorial($i) declare function local:factorial($i as xs:integer) as xs:integer { if ($i < 0) then 0 else if ($i = 0) then 1 else $i * local:factorial($i - 1) }; local:factorial(6)

Functions  There is a ; after the function declaration.  The namespace prefix local is used for user-defined functions. XQuery predefines the namespace prefix local to the namespace functions, and reserves this namespace for use in defining local functions.  The types of the arguments and return values should be sequence types.

Types  Sequence type can be: empty(), or ItemType OccurrenceIndicator?  OccurrenceIndicator can be +, ? or *.  Item type can be: item() atomic type, or kind test.

Kind Tests  Important kind tests include node() text() comment() processing-instruction(): with optional name argument. element test attribute test

Element Tests  Example of element tests are: element(*) element(familytree) element(man, personType)

Functions  Writing XQuery functions: Functional programming. Many are recursive in nature. Beware of types of parameters and return values.

Example from W3C declare function local:depth($e as node()) as xs:integer { (: A node with no children has depth 1 :) (: Otherwise, add 1 to max depth of children :) if (fn:empty($e/*)) then 1 else fn:max(for $c in $e/* return local:depth($c)) + 1 }; { local:depth(doc("ft2.xml")) }

Exercise #9  Write an XQuery function to count the number of elements in an element node (including itself). Try to use a recursive solution.

Exercise #10 For XML document such as ft2.xml, write a function that returns all child person nodes with parent of social security number $ssn.

Questions