xmlii xschema xschema xquery xquery. xml schema xml schema is a more sophisticated schema language...

21
XMLII XMLII XSchema XSchema XQuery XQuery

Upload: neal-day

Post on 24-Dec-2015

253 views

Category:

Documents


1 download

TRANSCRIPT

XMLIIXMLII

XSchemaXSchema XQueryXQuery

XML SchemaXML Schema

XML Schema is a more sophisticated schema language XML Schema is a more sophisticated schema language which addresses the drawbacks of DTDs. Supportswhich addresses the drawbacks of DTDs. Supports Typing of valuesTyping of values

E.g. integer, string, etcE.g. integer, string, etc Also, constraints on min/max valuesAlso, constraints on min/max values

User-defined, complex typesUser-defined, complex types Many more features, includingMany more features, including

uniqueness and foreign key constraints, inheritance uniqueness and foreign key constraints, inheritance XML Schema is itself specified in XML syntax, unlike DTDsXML Schema is itself specified in XML syntax, unlike DTDs

More-standard representation, but verboseMore-standard representation, but verbose XML Scheme is integrated with namespaces XML Scheme is integrated with namespaces BUT: XML Schema is significantly more complicated than BUT: XML Schema is significantly more complicated than

DTDs.DTDs.

XML Schema Version of Bank DTDXML Schema Version of Bank DTD<xs:schema xmlns:xs=<xs:schema xmlns:xs=http://www.w3.org/2001/XMLSchema>><xs:element name=“bank” type=“BankType”/><xs:element name=“bank” type=“BankType”/>

<xs:element name=“account”><xs:element name=“account”><xs:complexType><xs:complexType> <xs:sequence> <xs:sequence> <xs:element name=“account_number” type=“xs:string”/> <xs:element name=“account_number” type=“xs:string”/> <xs:element name=“branch_name” type=“xs:string”/> <xs:element name=“branch_name” type=“xs:string”/> <xs:element name=“balance” type=“xs:decimal”/> <xs:element name=“balance” type=“xs:decimal”/> </xs:squence> </xs:squence></xs:complexType></xs:complexType>

</xs:element></xs:element>…….. definitions of customer and depositor …... definitions of customer and depositor ….<xs:complexType name=“BankType”><xs:complexType name=“BankType”>

<xs:squence><xs:squence><xs:element ref=“account” minOccurs=“0” <xs:element ref=“account” minOccurs=“0”

maxOccurs=“unbounded”/>maxOccurs=“unbounded”/><xs:element ref=“customer” minOccurs=“0” <xs:element ref=“customer” minOccurs=“0”

maxOccurs=“unbounded”/>maxOccurs=“unbounded”/><xs:element ref=“depositor” minOccurs=“0” <xs:element ref=“depositor” minOccurs=“0”

maxOccurs=“unbounded”/>maxOccurs=“unbounded”/></xs:sequence></xs:sequence>

</xs:complexType></xs:complexType></xs:schema></xs:schema>

XML Schema Version of Bank DTDXML Schema Version of Bank DTD

Choice of “xs:” was ours -- any other namespace prefix Choice of “xs:” was ours -- any other namespace prefix could be chosencould be chosen

Element “bank” has type “BankType”, which is defined Element “bank” has type “BankType”, which is defined separatelyseparately xs:complexType is used later to create the named xs:complexType is used later to create the named

complex type “BankType”complex type “BankType” Element “account” has its type defined in-lineElement “account” has its type defined in-line

More features of XML SchemaMore features of XML Schema

Attributes specified by xs:attribute tag:Attributes specified by xs:attribute tag: <xs:attribute name = “account_number”/><xs:attribute name = “account_number”/> adding the attribute use = “required” means value must adding the attribute use = “required” means value must

be specifiedbe specified

Querying and Transforming XML Querying and Transforming XML DataData

Translation of information from one XML schema to anotherTranslation of information from one XML schema to another Querying on XML data Querying on XML data Above two are closely related, and handled by the same Above two are closely related, and handled by the same

toolstools Standard XML querying/translation languagesStandard XML querying/translation languages

XPathXPath Simple language consisting of path expressionsSimple language consisting of path expressions

XSLTXSLT Simple language designed for translation from XML to Simple language designed for translation from XML to

XML and XML to HTMLXML and XML to HTML XQueryXQuery

An XML query language with a rich set of featuresAn XML query language with a rich set of features

XQueryXQuery

XQuery is a general purpose query language for XML data XQuery is a general purpose query language for XML data Currently being standardized by the World Wide Web Consortium Currently being standardized by the World Wide Web Consortium

(W3C)(W3C) The textbook description is based on a January 2005 draft of the The textbook description is based on a January 2005 draft of the

standard. The final version may differ, but major features likely standard. The final version may differ, but major features likely to stay unchanged.to stay unchanged.

XQuery is derived from the Quilt query language, which itself XQuery is derived from the Quilt query language, which itself borrows from SQL, XQL and XML-QLborrows from SQL, XQL and XML-QL

XQuery uses a XQuery uses a for … let … where … order by …resultfor … let … where … order by …result … … syntaxsyntax forfor SQL SQL fromfrom wherewhere SQL SQL wherewhere order by order by SQL SQL order byorder by

resultresult SQL SQL selectselect letlet allows temporary variables, and has no equivalent in SQL allows temporary variables, and has no equivalent in SQL

FLWOR Syntax in XQuery FLWOR Syntax in XQuery For clause uses XPath expressions, and variable in for For clause uses XPath expressions, and variable in for

clause ranges over values in the set returned by XPathclause ranges over values in the set returned by XPath Simple FLWOR expression in XQuery Simple FLWOR expression in XQuery

find all accounts with balance > 400, with each result find all accounts with balance > 400, with each result enclosed in an <account_number> .. enclosed in an <account_number> .. </account_number> tag</account_number> tag forfor $x in /bank-1/customer/account $x in /bank-1/customer/account let let $acctno := $x/account_number/text()$acctno := $x/account_number/text()

wherewhere $x/balance > 400 $x/balance > 400 return return <account_number> { $acctno } <account_number> { $acctno } </account_number></account_number>

Items in the Items in the returnreturn clause are XML text unless enclosed clause are XML text unless enclosed in {}, in which case they are evaluatedin {}, in which case they are evaluated

Let clause not really needed in this query, and selection can Let clause not really needed in this query, and selection can be done In XPath. Query can be written as:be done In XPath. Query can be written as:

for $x in /bank-1/customer/account[balance>400]for $x in /bank-1/customer/account[balance>400]return { $x/account_number } return { $x/account_number }

JoinsJoins Joins are specified in a manner very similar to SQLJoins are specified in a manner very similar to SQL

for for $a $a inin /bank/account, /bank/account, $c $c inin /bank/customer,/bank/customer, $d $d inin /bank/depositor /bank/depositor

where where $a/account_number = $d/account_number $a/account_number = $d/account_number and and $c/customer_name = $d/customer_name$c/customer_name = $d/customer_name

return return <cust_acct> { $c $a } </cust_acct><cust_acct> { $c $a } </cust_acct> The same query can be expressed with the selections The same query can be expressed with the selections

specified as XPath selections:specified as XPath selections: forfor $a $a inin /bank/account /bank/account $c $c inin /bank/customer /bank/customer

$d $d inin /bank/depositor[ /bank/depositor[ account_number = $a/account_number account_number = $a/account_number andand customer_name = $c/customer_name customer_name = $c/customer_name]] return return <cust_acct> { $c $a } </cust_acct><cust_acct> { $c $a } </cust_acct>

Nested QueriesNested Queries The following query converts data from the flat structure for The following query converts data from the flat structure for

bankbank information into the nested structure used in information into the nested structure used in bank-1bank-1 <bank-1> {<bank-1> {

forfor $c $c inin /bank/customer /bank/customer returnreturn

<customer><customer> { $c/* }{ $c/* } { { for for $d $d inin /bank/depositor[customer_name = /bank/depositor[customer_name =

$c/customer_name],$c/customer_name], $a $a inin

/bank/account[account_number=$d/account_number]/bank/account[account_number=$d/account_number] returnreturn $a } $a }

</customer></customer> } </bank-1>} </bank-1> $c/*$c/* denotes all the children of the node to which denotes all the children of the node to which $c$c is is

bound, without the enclosing top-level tagbound, without the enclosing top-level tag $c/text()$c/text() gives text content of an element without any gives text content of an element without any

subelements / tagssubelements / tags

Sorting in XQuery Sorting in XQuery TheThe order by order by clause can be used at the end of any expression. E.g. clause can be used at the end of any expression. E.g.

to return customers sorted by nameto return customers sorted by name for for $c in /bank/customer$c in /bank/customer order by order by $c/customer_name $c/customer_name

return return <customer> { $c/* } </customer><customer> { $c/* } </customer> Use Use order by order by $c/customer_name to sort in descending order$c/customer_name to sort in descending order Can sort at multiple levels of nesting (sort by customer_name, and Can sort at multiple levels of nesting (sort by customer_name, and

by account_number within each customer)by account_number within each customer) <bank-1> {<bank-1> {

for for $c in /bank/customer $c in /bank/customer order by order by $c/customer_name$c/customer_namereturnreturn <customer> <customer> { $c/* } { $c/* } { for { for $d$d in in

/bank/depositor[customer_name=$c/customer_name],/bank/depositor[customer_name=$c/customer_name], $a$a in in

/bank/account[account_number=$d/account_number] }/bank/account[account_number=$d/account_number] }order by order by $a/account_number$a/account_number

return return <account> $a/* </account> <account> $a/* </account> </customer> </customer>

} </bank-1>} </bank-1>

Oracle XML-SQL UtilityOracle XML-SQL Utility

Transform data from o-r tables/views into XMLTransform data from o-r tables/views into XML Extract relevant data from an XML documentExtract relevant data from an XML document Insert data into database tablesInsert data into database tables

Using a canonical mappingUsing a canonical mapping Available as Available as

Java command-line front endJava command-line front end Java APIJava API PL/SQL APIPL/SQL API

SQL-to-XML MappingSQL-to-XML Mapping

For each SQL query Q, will get the XML file with the For each SQL query Q, will get the XML file with the following DTDfollowing DTD <!DOCTYPE ROWSET[<!DOCTYPE ROWSET[

<!ELEMENT ROWSET (ROW*)><!ELEMENT ROWSET (ROW*)>

<!ELEMENT ROW (attribute-list returned by Q)><!ELEMENT ROW (attribute-list returned by Q)>

]>]> If some attribute is of nested table type, then the If some attribute is of nested table type, then the

element will have sub-element corresponding to the element will have sub-element corresponding to the attributes of the nested tableattributes of the nested table

Example of SQL-to-XML Example of SQL-to-XML

We first create a table countryWe first create a table country CREATE TABLE countryCREATE TABLE country

(name char(50),(name char(50),

region char(60),region char(60),

area decimal(10),area decimal(10),

population decimal(11),population decimal(11),

gdp decimal(14),gdp decimal(14),

primary key (name)primary key (name)

););

Example of SQL-to-XMLExample of SQL-to-XML

CREATE TYPE CountriesType AS OBJECT (CREATE TYPE CountriesType AS OBJECT ( country_name char(50),country_name char(50), area decimal(10),area decimal(10), population decimal(11),population decimal(11), gdp decimal(14)gdp decimal(14)););//CREATE TYPE CountriesTableType AS TABLE OF CountriesType;CREATE TYPE CountriesTableType AS TABLE OF CountriesType;//CREATE TABLE Regions (CREATE TABLE Regions ( region_name char(60),region_name char(60), countries CountriesTableType,countries CountriesTableType, area decimal(10),area decimal(10), population decimal(11),population decimal(11), gdp decimal(14)gdp decimal(14)))NESTED TABLE Countries STORE AS CountriesTable;NESTED TABLE Countries STORE AS CountriesTable;

Example of SQL-to-XMLExample of SQL-to-XML

INSERT INTO Regions(region_name,area,population,gdp)INSERT INTO Regions(region_name,area,population,gdp)

SELECT region, SUM(area), SUM(population), SUM(gdp)SELECT region, SUM(area), SUM(population), SUM(gdp)

FROM countryFROM country

GROUP BY region;GROUP BY region;

UPDATE RegionsUPDATE Regions

SET countries =SET countries =

CAST(MULTISET(CAST(MULTISET(

SELECT * SELECT *

FROM country FROM country

WHERE region = Regions.region_name) WHERE region = Regions.region_name)

AS CountriesTableType );AS CountriesTableType );

Example of SQL-to-XMLExample of SQL-to-XML

Root – ROWSET elementRoot – ROWSET element Each row – ROW elementEach row – ROW element Each simple attribute – sub-element of ROW elementEach simple attribute – sub-element of ROW element Each nested table attribute – sub-element with sub-Each nested table attribute – sub-element with sub-

elementelement Each ROW element has a num attribute Each ROW element has a num attribute Null values are left outNull values are left out

XMLTypeXMLType

A system defined objectA system defined object With built in member functions With built in member functions

Create, extract, and index XML dataCreate, extract, and index XML data Can be used as column typeCan be used as column type

Define a table with XMLTypeDefine a table with XMLType

CREATE TABLE addrbook(CREATE TABLE addrbook(

name varchar(20),name varchar(20),

card SYS.XMLTYPE,card SYS.XMLTYPE,

creationDate DatecreationDate Date

););

Address book has a name, a creationData, and a XMLType Address book has a name, a creationData, and a XMLType attribute to contain the contact information structured in attribute to contain the contact information structured in XML formatXML format

XMLType InsertionXMLType Insertion

Use member function createXML(‘xml data’); Example:Use member function createXML(‘xml data’); Example:insert into addrbook valuesinsert into addrbook values ('Roger', sys.XMLType.createXML(('Roger', sys.XMLType.createXML( '<ACARD CREATEDBY="raj">'<ACARD CREATEDBY="raj"> <EMAIL>[email protected]</EMAIL><EMAIL>[email protected]</EMAIL> <WPHONE>111-5678</WPHONE><WPHONE>111-5678</WPHONE> <ADDRESS><ADDRESS> <LINE1>123 Main Street</LINE1><LINE1>123 Main Street</LINE1> <CITY>Atlanta</CITY><CITY>Atlanta</CITY> <STATE>GA</STATE><STATE>GA</STATE> <ZIP>33333</ZIP><ZIP>33333</ZIP> </ADDRESS></ADDRESS></ACARD>'), sysdate);</ACARD>'), sysdate); Non-well-formed XML

will be rejected

Querying XML DataQuerying XML Data

Use member function:Use member function: getClobVal CLOB (Character Large Object)getClobVal CLOB (Character Large Object) getStringValgetStringVal GetNumberValGetNumberVal Extract(‘Xpath expression’)Extract(‘Xpath expression’)

Example:Example:

select a.card.extract('/ACARD').getstringVal()select a.card.extract('/ACARD').getstringVal()

from addrbook afrom addrbook a

where name = 'Roger';where name = 'Roger';