0% found this document useful (0 votes)
115 views

Xquery

This document provides an overview of XPath and XQuery. It begins by defining XPath terminology such as nodes, relationships, and node selectors. It then demonstrates how to use XPath to select nodes through examples and exercises. Next, it covers additional XPath concepts like axes, predicates, and functions. Finally, it shows an example of using XQuery to create a new document by selecting nodes from an existing XML document using XPath expressions. In under 3 sentences, this document introduces XPath and XQuery concepts and provides examples and exercises to demonstrate how to select nodes from an XML document using XPath.

Uploaded by

jarostig
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Xquery

This document provides an overview of XPath and XQuery. It begins by defining XPath terminology such as nodes, relationships, and node selectors. It then demonstrates how to use XPath to select nodes through examples and exercises. Next, it covers additional XPath concepts like axes, predicates, and functions. Finally, it shows an example of using XQuery to create a new document by selecting nodes from an existing XML document using XPath expressions. In under 3 sentences, this document introduces XPath and XQuery concepts and provides examples and exercises to demonstrate how to select nodes from an XML document using XPath.

Uploaded by

jarostig
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Tutorial XPath,XQuery

CSCC43 IntroductiontoDatabases

CSCC43: Intro. to Databases

XPathTerminology
Node
documentroot,element,attribute,text,comment,...

Relationship
parent,child,sibling,ancestor,descendent, Exercise:Identifynodesandrelationshipsinfollowingxmldocument
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <!-- a bookstore database --> <book isbn= isbn=111111 111111 cat=fiction> cat= fiction > <!-- a particular book --> <title lang=chn>Harry Potter</title> <price unit=us>79.99</price> </book> / <book isbn=222222 cat=textbook> <title lang=eng>Learning XML</title> <price unit=us>69.95</price> </book> <book isbn isbn="333333" "333333" cat="textbook"> cat "textbook"> <title lang="eng">Intro. to Databases</title> <price unit="usd">39.00</price> </book> </bookstore>
CSCC43: Intro. to Databases

document root does not correspond to anything i the in th d document t

Nodeselector
Expression / node // . .. @ Description Selects the document root node (absolute path) Selects the node (relative path) Selects all descendent nodes of the current node that match the selection Selects the current node Selects the parent of the current node Selects attribute nodes

CSCC43: Intro. to Databases

Nodeselector:exercise
Result S l t th Selects the document d t root t node d Selects the bookstore element node Selects all book element nodes Selects all price element nodes S l t all Selects ll lang l attribute tt ib t nodes d ? ? ? Path Expression ? ? ? ? ? ? ? ? ? ././. /bookstore//@lang/../.. @ g ./book/tilte/@lang
CSCC43: Intro. to Databases 4

Nodeselector:exercisesol
Result Selects the document root node Selects the bookstore element node Selects all book element nodes Selects all price element nodes Selects all lang attribute nodes Selects the document root node Selects all the book element nodes Selects the empty set Path Expression / /. /bookstore ./bookstore /bookstore/book //book bookstore/book/price //price //@lang ././. /bookstore//@lang/../.. ./book/tilte/@lang

CSCC43: Intro. to Databases

Nodeselector:moreexercise
Result Selects text nodes of all price element nodes Select all child nodes of book element nodes Select all comment nodes Select all nodes except attribute nodes Select all attribute nodes ? ? Path Expression ? ? ? ? ? /bookstore/book/text() /bookstore/book/title/..//@*

CSCC43: Intro. to Databases

Nodeselector:moreexercisesol
Result Selects text nodes of all price element nodes Select all child nodes of book element nodes Select all comment nodes Select all nodes except attribute nodes Select all attribute nodes Selects empty set Select all attribute nodes which are descendant of book element nodes Path Expression //price/text() /bookstore/book/* //comment() //node() //@* /bookstore/book/text() /bookstore/book/title/..//@*

CSCC43: Intro. to Databases

XPathSyntaxandSemantics
Syntax S t
locationStep1/locationStep2/
locationStep=axis::nodeSelector[predicate]

Semantics
Findallnodesspecified p by ylocationStep1 p
Findallnodesspecifiedbyaxis::nodeSelector Selectonlythosethatsatisfypredicate

ForeachsuchnodeN:
FindallnodesspecifiedbylocationStep2 usingNasthecurrent node Takeunion

ForeachnodereturnedbylocationStep2 dothesame usinglocationStep3,


CSCC43: Intro. to Databases 8

CompletesetofAxes
self thecontextnodeitself child thechildrenofthecontextnode descendant alldescendants(children+) parent theparent(emptyifattheroot) ancestor allancestorsfromtheparenttotheroot descendantorself theunionofdescendantandself ancestororself theunionofancestorandself f following gsibling g siblings g totheright g precedingsibling siblingstotheleft following allfollowingnodesinthedocument,excludingdescendants preceding allprecedingnodesinthedocument, document excludingancestors attribute theattributesofthecontextnode

CSCC43: Intro. to Databases

Axes:exercise
Result Selects book element nodes Select all isbn attribute nodes Select title and price element nodes ? ? ? ? Path Expression ? ? ? / hild b k /child::book /bookstore/book/followingsibling::book /bookstore/node()/descendant-orself::node() /descendant::title/@*/parent::title/f ollowing::node()

CSCC43: Intro. to Databases

10

Axes:exercise(sol)
Result Selects book element nodes Select all isbn attribute nodes Select title and price element nodes S l t empty Selects t set t Path Expression /descendant::book //book/attribute::isbn //book/title | //book/price / hild b k /child::book

Selects the second book element node /bookstore/book/followingsibling::book Select all nodes (except attributes) that are descendants of the bookstore element l t node d Select all nodes (except attributes) after the first title node /bookstore/node()/descendant-orself::node() /descendant::title/@*/parent::title/f ollowing::node()
11

CSCC43: Intro. to Databases

Predicate:summary
[position()op#], [last()]
op: p =, ,!=, ,<, ,>, ,<=, ,>= testpositionamongsiblings

[attribute::nameopvalue"] value ]
op:=,!=,<,>,<=,>= testequalityofanattribute

[axis:nodeSelector]
test t tpattern tt

CSCC43: Intro. to Databases

12

Predicate:exercise
Result Selects the first book element that is the child of the bookstore element. Select book element nodes which has a child title element with lang attribute value no equal to eng. S Selects the second to last book element Selects all nodes which have an attr Path Expression ? ? ?

? ?

Selects nodes with an attribute named ? lang or has a child element named price. Selects all the title element of all book elements with a price greater than 35 35.00 00 ? ? /bookstore/book[price>35.00]/title /bookstore/book[position()>1 and attribute::isbn="111111"] /bookstore/book/title[last()]
CSCC43: Intro. to Databases 13

Predicate:exercisesol
Result Selects the first book element that is the child of the bookstore element. Select book element nodes which has a child title element with lang attribute value no equal to eng. S Selects the second to last book element Selects all nodes which have an attr Path Expression /bookstore/book[1] /bookstore/book[position()=1] /bookstore/book[child::title/attri bute::lang!="eng"] / /bookstore/book[last()-1] / () //node()[@*]

Selects nodes with an attribute named //node()[@lang or child::price] lang or has a child element named price. Selects all the title element of all book elements with a price greater than 35 35.00 00 Select the empty set /bookstore/book[price>35.00]/title /bookstore/book[position()>1 and attribute::isbn="111111"]
14

Select the last title element node of all /bookstore/book/title[last()] book element nodes CSCC43: Intro. to Databases

XPath:exercise
Question: find the title and price of non fiction books with a price more than 50 USD. USD
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <!-- a bookstore database --> <book isbn= isbn=111111 111111 cat=fiction> cat= fiction > <!-- a particular book --> <title lang=chn>Harry Potter</title> <price unit=us>79.99</price> </book> <book isbn=222222 cat=textbook> <title lang=eng>Learning XML</title> <price unit=us>69.95</price> </book> <book isbn="333333" cat="textbook"> <title lang="eng">Intro. to Databases</title> <price unit="usd">39.00</price> </book> </bookstore>

Answer: /bookstore/book[attribute::cat!="fiction" [ and price>50.00]/title p ] | /bookstore/book[attribute::cat!="fiction" and price>50.00]/@isbn


CSCC43: Intro. to Databases 15

XPath:exercise
Question: find average price of textbooks.
<?xml version= version="1 1.0 0" encoding="ISO encoding= ISO-8859-1 8859 1"?> ?> <bookstore> <!-- a bookstore database --> <book isbn=111111 cat=fiction> <! a particular book --> <!-> <title lang=chn>Harry Potter</title> <price unit=us>79.99</price> </book> <book isbn=222222 isbn= 222222 cat=textbook> cat= textbook > <title lang=eng>Learning XML</title> <price unit=us>69.95</price> </book> <book isbn= isbn="333333" 333333 cat="textbook"> cat= textbook > <title lang="eng">Intro. to Databases</title> <price unit="usd">39.00</price> </book> </bookstore>

Answer: sum(/bookstore/book[attribute::cat="textbook"]/price/number(text())) div count(/bookstore/book[attribute::cat (/bookstore/book[attribute::cat="textbook"]/price) textbook ]/price)


CSCC43: Intro. to Databases 16

XPath:exercise
Question: find the titles of textbooks on XML.
<?xml version= version="1 1.0 0" encoding="ISO encoding= ISO-8859-1 8859 1"?> ?> <bookstore> <!-- a bookstore database --> <book isbn=111111 cat=fiction> <! a particular book --> <!-> <title lang=chn>Harry Potter</title> <price unit=us>79.99</price> </book> <book isbn=222222 isbn= 222222 cat=textbook> cat= textbook > <title lang=eng>Learning XML</title> <price unit=us>69.95</price> </book> <book isbn= isbn="333333" 333333 cat="textbook"> cat= textbook > <title lang="eng">Intro. to Databases</title> <price unit="usd">39.00</price> </book> </bookstore>

Answer:
/bookstore/book[attribute::cat="textbook" and contains(title, "XML")]/title/text()

CSCC43: Intro. to Databases

17

XQueryExample
Q1:Createanewdocumentwhichcontainonlytheisbnandtitleoftextbooks.
<textbooks> {for $book indoc("bookstore.xml")//book where $ $book/@ /@cat="textbook" return <textbookisbn="$book/@isbn">{$book/title}</textbook> } </textbooks> Result:

<textbooks> <textbookisbn= isbn="222222"> 222222 > <titlelang="eng">LearningXML</title> </textbook> <textbookisbn isbn="333333"> 333333 > <titlelang="eng">Intro.toDatabases</title> </textbook> </textbooks> /
CSCC43: Intro. to Databases 18

XQuerySyntaxandSemantics
Syntax(FLWR)
for let where return variablebindings variablebindings condition document (likefrom inSQL) (likefrom inSQL) (like where inSQL) (like select in SQL)

Semantics
The for and let clause binds variables to elements specified by an XQuery expression.
for: bind a variable to each element in the returned set let: bind a variable to the whole set of elements

Filter out nodes that do not satisfy the condition of the where clause . For each retained tuple of bindings, bindings instantiate the return clause. clause

CSCC43: Intro. to Databases

19

XQueryExampleAgain
<textbooks> {for $book indoc("bookstore.xml")//book where $book/@cat="textbook" return <textbookisbn="$book/@isbn">{$book/title}</textbook> } </textbooks> / b k <?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <!-- a bookstore database --> <! > <book isbn=111111 cat=fiction> <!-- a particular book --> <title lang=chn>Harry Potter</title> <price unit=us>79.99</price> </book> <book isbn=222222 cat=textbook> <title lang=eng>Learning XML</title> <price unit=us>69.95</price> </book> <book isbn="333333" cat="textbook"> <title lang="eng">Intro. to Databases</title> <price unit="usd">39.00</price> </book> </bookstore>

<textbooks> <textbook isbn="222222"> <title lang="eng">Learning XML</title> </textbook> <textbook isbn="333333"> isbn= 333333 > <title lang="eng">Intro. to Databases</title> </textbook> </textbooks>

CSCC43: Intro. to Databases

20

XQueryExampleModified
Q2: <textbooks> {let $book :=doc("bookstore.xml")//book where $book/@cat="textbook" return <textbookisbn="$book/@isbn">{$book/title}</textbook> } </textbooks> <?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <!-- a bookstore database --> <book isbn=111111 cat=fiction> <!-- a particular book --> <title lang=chn>Harry Potter</title> <price unit=us>79.99</price> </book> <book isbn=222222 cat=textbook> <title lang=eng>Learning XML</title> <price unit=us>69.95</price> </book> <book isbn="333333" cat="textbook"> <title lang lang="eng">Intro. "eng">Intro to Databases</title> <price unit="usd">39.00</price> </book> </bookstore>

<textbooks> <textbook isbn="111111 222222 333333"> <title lang="chn">Harry Potter</title> <title lang="eng">Learning XML</title> <title lang="eng">Intro lang= eng >Intro. to Databases</title> </textbook> </textbooks>

CSCC43: Intro. to Databases

21

XQueryExercise Basic
Q3:Findthetitleandpriceofthebookwithisbn222222 222222 for$bookindoc("bookstore.xml")//book where$book[@isbn="222222"] $book[@isbn= 222222 ] return<book>{$book/title,$book/price}</book>

Result:

<book> <titlelang="eng">Learning g g gXML</title> <priceunit="usd">69.95</price> </book>

CSCC43: Intro. to Databases

22

XQueryExercise Ordering
Q4:Producealistofnonfictionswiththeirtitleandprice, price sortedbyprice. price <nonfictionlist> {for$bookindoc("bookstore.xml")//book,$titlein$book/title,$pricein$book/price where$book/@cat!= $book/@cat!="fiction" fiction orderby$price/text() return<nonfiction>{$title,$price}</nonfiction> } </nonfictionlist>
Result:

<nonfictionlist> <nonfiction> <titlelang="eng">Intro.toDatabases</title> <priceunit="usd">39.00</price> </nonfiction> <nonfiction> <titlelang="eng">LearningXML</title> <priceunit="usd">69.95</price> </nonfiction> </nonfictionlist>
CSCC43: Intro. to Databases 23

XQueryExercise Aggregation
Q5:Findtitleofthethetextbookwithhighestprice. price

<textbooks> {let$prices:=doc("bookstore.xml")//book[@cat="textbook"]/price let$ $max:=max($prices) ($p ) return <maxpricetextbookprice="{$max}"> {for$bookindoc("bookstore.xml")//book where$book/price=$max return$book/title } </maxpricetextbook> } </textbooks> /
Result:

<textbooks> <maxpricetextbookprice="69.95"> <titlelang= lang="eng">Learning eng >LearningXML</title> </maxpricetextbook> </textbooks>

CSCC43: Intro. to Databases

24

XQuery Q yExercise Restructuring g


Q6:Restructurethedocumenttoorganizebooksbycategories. <summarybycategory> {let$categories:= for$categoryindoc("bookstore.xml")//book/@cat return t $category $ t for$catindistinctvalues($categories) return <categoryid="{$cat}"> {for$bookindoc("bookstore.xml")//book where$book[@cat=$cat] return$book} </category> } </summarybycategory>
Result:

<bookstore> <book isbn=111111 cat=fiction> <title lang=chn>Harry Potter</title> <price unit=us>79.99</price> </book> <book isbn=222222 cat=textbook> <title lang=eng>Learning XML</title> <price unit=us>69 unit= us >69.95</price> 95</price> </book> <book isbn="333333" cat="textbook"> <title lang="eng">Intro. to Databases</title> <price unit="usd">39.00</price> </book> /b k </bookstore>

<summary-by-category> <category id="fiction"> <book isbn="111111" cat="fiction"> <title lang="chn">Harry Potter</title> <price unit="usd">79.99</price> </book> </category> <category id="textbook"> <book isbn="222222" cat="textbook"> <title lang="eng">Learning XML</title> <price unit="usd">69.95</price> </book> </category> </summary-by-category>

CSCC43: Intro. to Databases

25

XQuery Q y Exercise Restructuring g


Q7:Restructurethedocumenttoproducethetotalpriceandcountofbooksineachcategory. <pricebycategory> {let$categories:= for$categoryindoc("bookstore.xml")//book/@cat return$category for$catindistinctvalues($categories) return <categoryid="{$cat}"> {let$pricesincat:=doc("bookstore.xml")//book[@cat=$cat]/price return<pricetotal="{sum($prices total= {sum($pricesincat)} cat)}"count= count="{count($prices {count($pricesincat)} cat)}"/> /> } </category> } </pricebycategory>
Result:

<price-by-category>
<bookstore> <b k t > <category id="fiction"> <book isbn=111111 cat=fiction> <title lang=chn>Harry Potter</title> <price total="79.99" count="1" /> <price unit=us>79.99</price> </category> </book> <category id="textbook"> <book isbn=222222 cat=textbook> <title lang=eng>Learning <price total="108.95" count="2" /> XML</title> </category> <price unit=us>69.95</price> </book> </price-by-category> <book isbn="333333" cat="textbook"> <title lang= lang="eng">Intro eng >Intro. to Databases</title> <price unit="usd">39.00</price> </book> CSCC43: Intro. to Databases </bookstore>

26

You might also like