0% found this document useful (0 votes)
119 views72 pages

Clase XML Oracle

The document discusses the history and features of XML support in Oracle databases. It describes how XML data can be stored natively as XMLType or shredded into relational tables. It provides details on Oracle's XML database, including XMLType storage options, registering XML schemas, and using SQL and XML APIs to query and process XML data.

Uploaded by

seb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views72 pages

Clase XML Oracle

The document discusses the history and features of XML support in Oracle databases. It describes how XML data can be stored natively as XMLType or shredded into relational tables. It provides details on Oracle's XML database, including XMLType storage options, registering XML schemas, and using SQL and XML APIs to query and process XML data.

Uploaded by

seb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 72

Practical Applications of XML

Technologies
XML Support in Oracle
Persistence of XML Data
 Native XML databases
 Data structures, indices, etc. suitable for
hierarchical data
 XML-enabled (relational / object-relational)
databases
 Shredding of XML data into relations
 XMLType
 Native support
 SQL/XML
 Examples: Oracle Database, Microsoft SQL
Server, IBM DB2
Oracle XML Database (XML DB)
 Collection of XML technologies built into
Oracle 10g
 XML-enabled database
 Storage, retrieval, processing of XML data
 Types:
 Shredding into relational tables
 Storing intact into a CLOB XMLType column
 Storing XML Schema-based XMLType column
 Object-relational storage
History of XML Support in Oracle
 Oracle 8i
 XML SQL Utility (XSU) – storing XML documents into
tables, retrieval of SQL data in XML format
 XMLPARSER, XMLDOM, XSLPROCESSOR
 Problem: Java
 Oracle 9i Release 1
 XMLType – native XML data type
 extract(), extractValue(), existNode() + XPath
expressions
 SYS_XMLGEN(), SYS_XMLAGG() – SQL functions for
creating XMLTypes
 Problem: Stored in CLOBs + necessity to built DOM tree
before processing
 XML full text (XPath)
History of XML Support in Oracle
 Oracle 9i Release 2
 XML Schema-based storage for XML Type
 Registering of XSDs → set of object types and object
tables → shredding of XML documents
 Avoidance of DOM parsing
 Rewriting XPath queries to SQL
 New index and member functions for XMLType
 Document-centric XML DB repository
 Interfaces for document management and access
(HTTP, FTP)
 SQL/XML functions
 UPDATEXML(), XMLSEQUENCE()
 C and PL/SQL packages for processing XML data
 Parsing, DOM operations, XML Schema validation, XPath
extraction, indexing, XSLT, …
History of XML Support in Oracle
 Oracle 10g Release 1
 XML Schema evolution
 Update of XML schemas without performing
export/import
 Unified DOM interface for XMLTypes
 Oracle 10g Release 2
 XQuery support – SQL functions XMLQuery(),
XMLTable()
 Updating XML – SQL functions insertChildXML(),
appendChildXML(), insertXMLbefore(), deleteXML()
 XMLPI(), XMLComment(), XMLRoot(), XMLSerialize(),
XMLCDATA(), XMLParse()
History of XML Support in Oracle
 Oracle 11g Release 1
 Binary storage model for XMLType
 XML Schemas: in place evolution, recurion, XLink and
XInclude,
 SQL/XML: XMLExists and XMLCast
 XMLIndex – XPath-based predicates and fragment
extraction
 XML Schema annotations: storeVarrayAsTable = "true"
by default
 Ordered XML Collections can use heap
 Oracle XML DB Repository: listeners with handlers for
events, Content Repository API for Java, new privileges
 XQuery and XSLT performance enahncements
History of XML Support in Oracle
 Oracle 11g Release 2
 Enhancements in access control, repository read and
write, binary XMLType, XMLIndex
 Cost-based optimization of XQuery expressions
 Deprecated XML constructs: extract, extractValue,
existNode, XMLSequence, ora:instanceof,
ora:instanceof-only, getStringVal, getCLOBVal,
getBLOBVal, getNamespace, getRootElement
Oracle XML Database
XML DB Repository
C-based PL/SQL Packages
SQL/XML
XMLType
Native XML Support

C External Procedures
Java Stored Procedures
XDK XML APIs
Extensible XML Support
Oracle XML Database
 XMLType tables, columns and views
 Storage of XML data
 XML DB Repository Procedural
Language/Structured
 Handling XML documents Query Language
 SQL/XML and PL/SQL
 Operations on XML (and SQL) data
 Java and C programming APIs in XDK
 Adding functionality by building external
procedures
XML Developer’s KIT
XMLType
Storage
XMLType
 Native data type for storing XML data
 Similar to, e.g. DATE data type
 Define table columns
 Use as parameter, return values or variables in PL/SQL
procedures
 Content must be well-formed
 Built-in member functions
 Operating XML content
 Creating an XMLType instance from various resources
 Extracting XML content
 Validating against XSDs
 XSL transformations
XMLType – CLOB storage
 Advantages:
 Best preserves original format
 Maximum flexibility for XML schema
evolution
 Disadvantages:
 Expensive querying and updates
 Require building a DOM tree
XMLType – CLOB storage
CREATE TABLE product (
id VARCHAR(10),
name VARCHAR2(100),
description XMLType)
XMLTYPE COLUMN description STORE AS CLOB;

INSERT INTO product (id, name, description)


VALUES ('XDK', 'XML Developer''s Kit',
XMLTYPE('<DESCRIPTION><KEYWORD>xdk</KEYWORD> is a
set of standards-based utilities that help to build XML
applications.</DESCRIPTION>'));
XMLType – XML Schema-based
 Object-relational structure specified by an XSD
 Defines how to shred XML document into SQL objects
 Advantages:
 Speeding up queries and updates
 Each XSD must be registered under a unique URL
 To be referenced from XML Schema-based XMLTypes
 Registration:
 Creating SQL objects
 (Optional) generation of a default table
 XML DB Repository
Registration of an XSD (1)
BEGIN
DBMS_XMLSCHEMA.registerSchema(
SCHEMAURL=>'http://xmlns.oracle.com/xml/content.xsd',
SCHEMADOC=>'<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="DESCRIPTION">
<xs:complexType mixed="true">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="KEYWORD" type= "xs:string"

maxOccurs="unbounded"/>
</xs:choice> Current user
</xs:complexType>
</xs:element>
</xs:schema>', Generate types
LOCAL=>TRUE,
GENTYPES=>TRUE, Generate tables
GENTABLES=>FALSE);
Registration of an XSD (2)
 Load from file (stored at server):
CREATE DIRECTORY XMLDIR AS '/mydata';
BEGIN
DBMS_XMLSCHEMA.registerSchema(
SCHEMAURL => 'http://xmlns.oracle.com/xml/content.xsd',
SCHEMADOC => bfilename('XMLDIR','purchaseOrder.xsd'),
CSID => nls_charset_id('AL32UTF8'));
END;

 SCHEMADOC – can be VARCHAR,


CLOB, BLOB, BFILE, XMLType, or
URIType
During Registration
 SQL objects to store XMLType are
generated
 Default tables are created
SELECT object_name, object_type FROM user_objects;
OBJECT_NAME OBJECT_TYPE

-------------------------
KEYWORD209_COLL TYPE

DESCRIPTION208_T TYPE

describe KEYWORD209_COLL;
"KEYWORD209_COLL" AS VARRAY(2147483647) OF VARCHAR2(4000 CHAR)
XMLType – XML Schema-based
CREATE TABLE product (
id VARCHAR(10),
name VARCHAR2(100),
description XMLType )
XMLType COLUMN description
XMLSCHEMA "http://xmlns.oracle.com/xml/content.xsd"
ELEMENT "DESCRIPTION"

INSERT INTO product (id, name, description)


VALUES ('XDK', 'XML Developer''s Kit',
XMLTYPE('<DESCRIPTION><KEYWORD>xdk</KEYWORD> is a set of
standards-based utilities that help to build XML
applications.</DESCRIPTION>').createSchemaBasedXML
('http://xmlns.oracle.com/xml/content.xsd'));
XMLType Tables
CREATE TABLE product2 OF XMLType;

CREATE TABLE product2 OF XMLType


XMLSCHEMA "http://xmlns.oracle.com/xml/content.xsd"
ELEMENT "DESCRIPTION";

INSERT INTO product2 VALUES (


XMLTYPE(
bfilename('XMLDIR', 'productdata1.xml'),
nls_charset_id('AL32UTF8')));
sqlldr mlynkova/<password>@desitka load_data.ctl direct=y

XML Loader file load_data.ctl

LOAD DATA
INFILE *
INTO TABLE foo TRUNCATE
XMLType(xmldata) file person.dat
FIELDS(fill filler CHAR(1),
xmldata LOBFILE (CONSTANT person.dat)
TERMINATED BY '<!-- end of record -->')
BEGINDATA
0 <person xmlns="http://www.oracle.com/person.xsd"
0 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/person.xsd
http://www.oracle.com/person.xsd">
<name>xyz name 2</name>
</person>
<!-- end of record -->
<person xmlns="http://www.oracle.com/person.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/person.xsd
http://www.oracle.com/person.xsd">
<name> xyz name 2</name>
</person>
<!-- end of record -->
Default XML Schema-based DB
Structure
 complexType → SQL type
 Element/attribute defined by the complexType → SQL
attribute of the SQL type
 By default inlined
 47 XML Schema data types → 19 scalar SQL data
types
 Element with maxOccurs > 1 → collection attribute
 By default VARRAY stored in a LOB
 SQL type/attribute names are generated
automatically from XML Schema
type/element/attribute names
XML Schema
Annotations
XML Schema Annotations
 To control the mapping between XSD and storage
methods
 Namespace: http://xmlns.oracle.com/xdb, prefix: xdb
 Attribute types:
 Default table – name and storage options of the
default XMLType table
 SQL names – SQL names for element in the schemas
 SQL types – SQL data types for simple and complex
XML Schema types
 Maintain DOM – whether to preserve DOM fidelity of
an element
 XML DB adds position descriptor for comments, PIs,
sibling element order, … → increases storage overhead
 Storage options – for optimizing storage
Annotating Attributes (1)
 Element schema:
 xdb:storeVarrayAsTable
 true = store collection elements (maxOccurs > 1)
in nested object tables
 false = collection is serialized as a varray and
stored in a LOB column
 xdb:mapUnboundedStringToLob
 true = unbounded strings/binary data are stored
to BLOB/CLOB
 Default: false → VARCHAR2(4000) / RAW(2000)
Annotating Attributes (2)
 Global complex types:
 xdb:SQLType
 Name of the SQL type
 To avoid XML DB generated names for complex
types
 To change storage from object-relational to
VARCHAR2, RAW, CLOB, BLOB
 xdb:maintainDOM
 true = the complex type should maintain DOM
fidelity
Annotating Attributes (3)
 XML elements:
 xdb:SQLName
 Specifies the name of the attribute within the SQL
object that maps to this XML element
 xdb:SQLType
 Name of SQL type corresponding to the element
 xdb:SQLColType
 The name of the SQL collection type (for elements
with maxOccurs > 1)
 xdb:maintainDOM
Annotating Attributes (3)
 xdb:SQLInline
 true = embedded attribute
 false = a REF value is stored (or a collection of REF
values, if maxOccurs>1)
 xdb:maintainOrder
 true = collection is mapped to VARRAY
 false = collection is mapped to a nested table
 xdb:defaultTable
 Name of the table into which XML instances are stored
 A link from XML DB repository is created to this table
 xdb:tableProps, xdb:columnProps
 Default table properties in SQL appended to the CREATE
TABLE
<xs:complexType name="LineItemsType" xdb:SQLType="LINEITEMS_T">
<xs:sequence>
<xs:element name="LineItem" type="LineItemType" maxOccurs="unbounded"
xdb:SQLName="LINEITEM" xdb:SQLCollType="LINEITEM_V"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="LineItemType" xdb:SQLType="LINEITEM_T">


<xs:sequence>
<xs:element name="Description" type="DescriptionType"
xdb:SQLName="DESCRIPTION"/>
<xs:element name="Part" type="PartType" xdb:SQLName="PART"/>
</xs:sequence>
<xs:attribute name="ItemNumber" type="xs:integer"
xdb:SQLName="ITEMNUMBER" xdb:SQLType="NUMBER"/>
</xs:complexType>

<xs:complexType name="PartType" xdb:SQLType="PART_T">


<xs:attribute name="Id" xdb:SQLName="PART_NUMBER" xdb:SQLType="VARCHAR2">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="10"/>
<xs:maxLength value="14"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="Quantity" type="moneyType" xdb:SQLName="QUANTITY"/>
<xs:attribute name="UnitPrice" type="quantityType" xdb:SQLName="UNITPRICE"/>
</xs:complexType>
XML Schema Annotations
 Too many options → most common
strategy:
 Specify the name of the default table
 defaultTable
 Specify the name and data type for each
element and data type
 SQLName, SQLType, SQLColType
 Note that:
 SQLName – SQL names for XML elements
 SQLCollName – SQL names for elements with
maxOccurs > 1
 SQLType – SQL names for all simple types or
complex types that do not use default mapping
XML Schema Annotations
 Recommendations:
 Avoid preserving DOM fidelity
 Store subtrees/complex types as CLOB when no XPath
queries are required
 xdb:SQLType=“CLOB”
 Store large unbounded XML elements using nested tables
 xdb:storeVarrayAsTable=“true”
 Important:
 SQL is case-insensitive, but names in SQL code are
implicitly uppercase, unless you enclose them in double-
quotes
 XML is case-sensitive. You must refer to SQL names in
XML code using the correct case: uppercase SQL names
must be written as uppercase
Generating XML
from SQL Data
SQL/XML in Oracle (1)
 XMLELEMENT
 Returns an XML element in an XMLType when
given:
 XML element name
 Optional list of XML attributes
(XMLATTRIBUTES())
 Optional list of values as the content of the new
element
 Other XML elements or XML fragments
(XMLFOREST()) as its children
 XMLATTRIBUTES
 Used within XMLELEMENT() to specify attributes
for the element.
CREATE TABLE employees (
XMLELEMENT, employee_id VARCHAR(10),
first_name VARCHAR2(100),
XMLATTRIBUTES last_name VARCHAR2(100),
job_id VARCHAR2(100),
hire_date DATE,
salary NUMBER,
email VARCHAR2(100),
phone_number VARCHAR2(100),
department_id VARCHAR(10));
SELECT
XMLELEMENT("Employee",
XMLATTRIBUTES(employee_id AS "empno",
job_id AS "job"),
XMLELEMENT("Name",
first_name || ' ' || last_name),
'is hired on ',
hire_date) AS result
FROM employees WHERE rownum=1;

<Employee empno="100" job="AD_PRES">


<Name>Steven King</Name>is hired on 17-JUN-87
</Employee>
SQL/XML in Oracle (2)
 XMLFOREST
 Returns an XML fragment in an XMLType when
given a list of named expressions for the XML
elements
 Each expression specifies the name of an XML
element and its content
 XMLCONCAT
 Returns an XML fragment in an XMLType by
concatenating a list of XML elements/values
 XMLAGG
 Returns an XML fragment in an XMLType by
aggregating XML fragments, with the option of
XML element sorting
XMLFOREST
SELECT
XMLELEMENT("Employee",
XMLATTRIBUTES(employee_id AS "empno",
job_id AS "job"),
XMLELEMENT("Name",first_name||' '||last_name),
'is hired on ', hire_date,
XMLFOREST(EMAIL, PHONE_NUMBER)) AS result
FROM employees
WHERE rownum=1;

<Employee empno="100" job="AD_PRES">


<Name>Steven King</Name>is hired on 17-JUN-87
<EMAIL>SKING</EMAIL>
<PHONE_NUMBER>515.123.4567</PHONE_NUMBER>
</Employee>
XMLCONCAT
SELECT XMLCONCAT(
XMLELEMENT("Email",email),
XMLELEMENT("Name", first_name||' '||last_name))
FROM employees
WHERE ROWNUM < 3;

SELECT (
XMLCONCAT (
XMLSEQUENCE (
CURSOR(SELECT * FROM employees WHERE rownum <
3))))
FROM dual;
XMLAGG
SELECT XMLAGG ( value(e)
ORDER BY EXTRACTVALUE(value(e),'/ROW/FIRST_NAME') DESC
NULLS FIRST)
FROM TABLE (
XMLSEQUENCE (
CURSOR (
SELECT first_name, last_name,salary
FROM employees ))) e
WHERE EXTRACTVALUE (value(e), '/ROW/SALARY')
BETWEEN 12000 AND 18000;

 Aggregates all the XML elements returned by the SQL


query into an XML document fragment
 Allows an optional ORDER BY clause during the
aggregation
Oracle SQL Extensions (1)
 SYS_XMLGEN
 Generates an XML document with the <?XML?>
prolog from one scalar type, a user-defined
object type, or an instance of XMLType
 XMLSEQUENCE
 Returns a collection of XMLTypes in an
XMLSEQUENCEType, which is a VARRAY of
XMLType instances in the database
 SYS_XMLAGG
 Aggregates XML elements from one scalar type,
a user-defined object type, or an instance of
XMLType
SYS_XMLGEN
SELECT
SYS_XMLGEN(
XMLELEMENT("Employee",
XMLATTRIBUTES(employee_id AS "empno",
job_id AS "job"),
XMLELEMENT("Name",first_name||' '||last_name),
'is hired on ',
hire_date)) AS result
FROM EMPLOYEES WHERE rownum=1;

<?xml version="1.0"?>
<ROW>
<Employee empno="100" job="AD_PRES">
<Name>Steven King</Name>is hired on 17-JUN-87
</Employee>
</ROW>
SELECT SYS_XMLGEN(
XMLELEMENT("Employee",
XMLATTRIBUTES(employee_id AS "empno",
job_id AS "job"),
XMLELEMENT("Name",first_name||' '||last_name),
'is hired on ',
hire_date),
XMLFORMAT.createformat('EmployeeList','NO_SCHEMA', null,
'http://www.oracle.com/','http://dburl',
'<?xml-stylesheet href="htmlRend.xsl"
type="text/xsl" ?>'))
FROM employees WHERE rownum < 3;

<?xml version="1.0"?>
<?xml-stylesheet href="htmlRend.xsl"
type="text/xsl" ?>
<EmployeeList>
<Employee empno="100" job="AD_PRES">
<Name>Steven King</Name>is hired on 17-JUN-87
</Employee>
</EmployeeList>
XMLSEQUENCE
SELECT XMLSEQUENCE(
CURSOR(
SELECT employee_id, first_name, last_name
FROM employees where rownum < 3 )) AS result
FROM dual;

XMLSEQUENCETYPE(
XMLTYPE( <ROW>
<EMPLOYEE_ID>100</EMPLOYEE_ID>
<FIRST_NAME>Steven</FIRST_NAME>
<LAST_NAME>King</LAST_NAME>
</ROW>),
XMLTYPE( <ROW>
<EMPLOYEE_ID>101</EMPLOYEE_ID>
<FIRST_NAME>Neena</FIRST_NAME>
<LAST_NAME>Kochhar</LAST_NAME>
</ROW> ))
SYS_XMLAGG
SELECT SYS_XMLAGG (
XMLCONCAT (value(e)),
XMLFORMAT.createFormat('EmployeeList'))
FROM TABLE (
XMLSEQUENCE (
CURSOR (
SELECT first_name, last_name,salary
FROM employees ))) e
WHERE EXTRACTVALUE (value(e), '/ROW/SALARY')
BETWEEN 12000 AND 18000;

 Adds an additional <ROWSET> root element and the


<?XML?> prolog to make sure the result is a well-
formed XML document
Oracle SQL Extensions (2)
 XMLCOLATTVAL
 Generates a set of <column/> elements with the
name attributes specifying the column names or the
name aliases
SELECT XMLELEMENT("Employee",
XMLATTRIBUTES (first_name||' '||last_name AS "name"),
XMLCOLATTVAL (hire_date, job_id,
department_id AS "dept")) AS "result"
FROM employees e
WHERE rownum=1;

<Employee name="Steven King">


<column name="HIRE_DATE">17-JUN-87</column>
<column name="JOB_ID">AD_PRES</column>
<column name="dept">90</column>
</Employee>
XML Retrieval
Using XMLType and
SQL/XML
XMLType Member Functions (1)
 XMLType, createXML, createSchemaBasedXML,
createNonSchemaBasedXML
 Create XMLTypes from XML data stored in
VARCHAR2, CLOB, or other XMLTypes
 getClobVal, getBlobVal, getNumberVal, getStringVal
 Gets the CLOB, BLOB, NUMBER, or String value in
VARCHAR2, respectively, from the XMLType
 getNumberVal can be used only when the content of
XMLType is numeric
 transform
 Transforms the XML content in XMLType with the XSL
stylesheet specified
XMLType, get CLOBVal
CREATE TABLE xml_table OF XMLType;
CREATE TABLE table_with_xml_column
(filename VARCHAR2(64), xml_document XMLType);

INSERT INTO xml_table


VALUES (XMLType(bfilename('XMLDIR', 'purchaseOrder.xml'),
nls_charset_id('AL32UTF8')));
INSERT INTO table_with_xml_column (filename, xml_document)
VALUES ('purchaseOrder.xml',
XMLType(bfilename('XMLDIR', 'purchaseOrder.xml'),
nls_charset_id('AL32UTF8')));

SELECT x.OBJECT_VALUE.getCLOBVal()
FROM xml_table x;
SELECT x.xml_document.getCLOBVal()
FROM table_with_xml_column x;
XMLType Member Functions (2)
 isFragment
 Checks if the XMLType is an XML document fragment
or a well-formed document
 isSchemaBased, getSchemaURL, getRootElement,
getNamespace
 Checks the XML schema–related information of
XMLType and returns respective information if exists
 isSchemaValidate, isSchemaValid, schemaValidation,
setSchemaValidate
 Checks and updates the XML Schema validation
status of XMLType
Oracle SQL Extensions
 existsNode
 Checks if the XML nodes or node sets specified by
XPath exist
 extract
 Extracts nodes or node sets based on the XPath
expression and returns an XMLType instance
containing the resulting node(s)
 extractValue
 Returns scalar content, such as numbers or strings,
when passed an XPath expression pointing to an XML
element with only a single text child
existsNode
SELECT OBJECT_VALUE
FROM purchaseorder
WHERE existsNode(OBJECT_VALUE,
'/PurchaseOrder[SpecialInstructions="Expedite"]') = 1;
OBJECT_VALUE
----------------------------------------------------------------------
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
extract
SELECT
extract(OBJECT_VALUE, '/PurchaseOrder/Reference')
"REFERENCE"
FROM purchaseorder
WHERE existsNode(OBJECT_VALUE,
'/PurchaseOrder[SpecialInstructions="Expedite"]') = 1;

REFERENCE
---------------------------------------------------
<Reference>AMCEWEN-20021009123336271PDT</Reference>
<Reference>SKING-20021009123336321PDT</Reference>
<Reference>AWALSH-20021009123337303PDT</Reference>
extractValue
SELECT
extractValue(OBJECT_VALUE, '/PurchaseOrder/Reference')
"REFERENCE"
FROM purchaseorder
WHERE existsNode(OBJECT_VALUE,
'/PurchaseOrder[SpecialInstructions="Expedite"]') = 1;

REFERENCE
---------------------------------------------------
AMCEWEN-20021009123336271PDT
SKING-20021009123336321PDT
AWALSH-20021009123337303PDT
SQL/XML in Oracle - XMLQuery
 Querying/construction of XML data using
XQuery
 Oracle extensions:
 ora:contains – calling existsNode, extract,
extractValue
 ora:matches – matching string with regular
expression
 ora:replace – replacing string using regular
expression
 ora:sqrt – square root
 ora:view – creates XML views over the relational data
XMLQuery
SELECT warehouse_name,
XMLQuery(
'for $i in /Warehouse
where $i/Area > 80000
return <Details>
<Docks num="{$i/Docks}"/>
<Rail>{if ($i/RailAccess = "Y")
then "true" else "false"}
</Rail>
</Details>'
PASSING warehouse_spec RETURNING CONTENT)
big_warehouses
FROM warehouses;
SQL/XML in Oracle - XMLTable
 Shreds the result of an XQuery-expression
evaluation into the relational rows and columns
of a new, virtual table
 Further inserting, SQL querying, …
SELECT xtab.poref, xtab.priority, xtab.contact
FROM purchaseorder,
XMLTable
XMLTable('for $i in /PurchaseOrder
let $spl := $i/SpecialInstructions
where $i/CostCenter eq "A10"
return <PO>
<Ref>{$i/Reference}</Ref>
{if ($spl eq "Next Day Air" or
$spl eq "Expedite") then
<Type>Fastest</Type>
else if ($spl eq "Air Mail") then
<Type>Fast</Type>
else ()}
<Name>{$i/Requestor}</Name>
</PO>'
PASSING OBJECT_VALUE
COLUMNS poref VARCHAR2(20) PATH '/PO/Ref',
priority VARCHAR2(8) PATH '/PO/Type'
DEFAULT 'Regular',
contact VARCHAR2(20) PATH '/PO/Name')
xtab;
XMLTable
POREF PRIORITY CONTACT
-------------------- -------- --------------------
SKING-20021009123336 Fastest Steven A. King
SMCCAIN-200210091233 Regular Samuel B. McCain
SMCCAIN-200210091233 Fastest Samuel B. McCain

 The result without COLUMNS: Table


with single column containing the
resulting XML fragments
XML Data
Updates
Oracle SQL Extensions
 updateXML
 Replaces XML nodes of any kind
 insertChildXML
 Inserts XML element or attribute nodes as children of
a given element node
 insertXMLbefore
 Insert XML nodes of any kind immediately before a
given node
 appendChildXML
 Inserts XML nodes of any kind as the last child
nodes of a given element node
 deleteXML
 Deletes XML nodes of any kind
updateXML
 Accepts:
 XMLType instance
 Set of XPath expression – string value pairs
 Updates XPath-referred elements or
attributes with the provided values
SELECT updateXML (
column_name,
'XPath1', 'text1',
…,
'XPathN', 'textN',
'Namespace1 NamespaceN')
FROM table_name;
SELECT updateXML(XMLType(
'<Employee xmlns:app1="www.example.com/ns1"
xmlns:app2="www.example.com/ns2">
<Name app1:type="Customer">Janet Jones</Name>
<Job app2:type="IT">Manager</Job>
<Salary app2:type="Hidden">12000</Salary>
<Commission app2:type="Hidden">3400</Commission>
</Employee>'),
'/Employee/Name/text()', 'Janet Lee',
'/Employee/Name/@app1:type', 'Important Customer',
'/Employee/Job/@app2:type', 'Hidden',
'/Employee//*[@app2:type="Hidden"]', null,
'xmlns:app1="www.example.com/ns1"
xmlns:app2="www.example.com/ns2"') AS result
FROM dual;

<Employee xmlns:app1="www.example.com/ns1"
xmlns:app2="www.example.com/ns2">
<Name app1:type="Important Customer">Janet Lee</Name>
<Job/>
<Salary/>
<Commission/>
</Employee>
insertChildXML
UPDATE purchaseorder
SET OBJECT_VALUE =
insertChildXML(OBJECT_VALUE,
'/PurchaseOrder/LineItems',
'LineItem',
XMLType(
'<LineItem ItemNumber="222">
<Description>The Harder They Come</Description>
<Part Id="953562951413"
UnitPrice="22.95"
Quantity="1"/>
</LineItem>'))
WHERE existsNode(OBJECT_VALUE,
'/PurchaseOrder[Reference="AMCEWEN-20021009123336171PDT"]')
= 1;
insertXMLbefore
UPDATE purchaseorder
SET OBJECT_VALUE =
insertXMLbefore(OBJECT_VALUE,
'/PurchaseOrder/LineItems/LineItem[1]',
XMLType('<LineItem ItemNumber="314">

<Description>Brazil</Description>
<Part Id="314159265359"
UnitPrice="69.95"
Quantity="2"/>
</LineItem>'))
WHERE existsNode(OBJECT_VALUE,
'/PurchaseOrder[Reference="AMCEWEN-20021009123336171PDT"]')
= 1;
deleteXML
UPDATE purchaseorder
SET OBJECT_VALUE =
deleteXML(OBJECT_VALUE,
'/PurchaseOrder/LineItems/LineItem[@ItemNumber="222"]')
WHERE existsNode(OBJECT_VALUE,
'/PurchaseOrder[Reference="AMCEWEN-20021009123336171PDT"]')
= 1;
XMLType Views
XMLType Views
CREATE OR REPLACE VIEW employee_vw AS
SELECT XMLELEMENT("Employee",
XMLATTRIBUTES(employee_id AS "empno"),
XMLFOREST(first_name, last_name, job_id)) AS RESULT
FROM employees;

SELECT * FROM eployee_vw;

 Wrapping up existing object-relational data


in XML
 Can be based on XSDs
 Checking validity
 XPath optimizations
XML Storage
Comparison
How to Store XML Data?
 XMLType or Relational tables?
 Data-centric documents: XSU, SQL/XML
 Efficient retrieval
 No need to preserve XML format
 If necessary: XMLType Views
 Document-centric documents: XMLType
 Hybrid documents: ?
 XMLType schema based storage?
 No (CLOB): DTD based documents, changing
XSDs
 Yes: intensive data retrieval/updates
How to Store XML Data?
 XMLType table or column?
 Column: We need to store relational data along
with XML documents
 Example: create time, create owner, …
 XMLType table in XDB repository?
 No – defined in SQL
 Yes: We need high-performance hierarchical
document navigation and protocol interfaces
 Defined in XML Schema by xdb:defaultTable for
root element
 Created automatically during schema
registration
Comparison of XML Storage
Category Relational storage with CLOB XMLType Schema-based
XMLType Views XMLType
Modeling (+) Relational modeling (-) No data (-) No data
with data normalization normalization normalization
(+) Relational storage that (+) Flexible storage (-) Limited XML Schema
handles schema evolution when schemas evolve evolution support
well or document size (+) Data reused by
(+) No XML overhead after varies building up multiple
data is stored (-) Document view views on XML data
(+) Easy reuse of data prevents reuse as
SQL data
Loading (-) Low throughput for data (+) Fast XML (-) Low throughput for
uploading uploading data uploading
Query (+) High performance for (-) Low performance (+) XPath queries
SQL queries for XPath queries rewritten to SQL for
(-) Requires table joins for with DOM tree high-performance data
XML queries traversal retrieval
XML (+) No DOM fidelity (+) Maintains the (+) DOM fidelity as an
fidelity original XML byte-for- option
byte (xdb:maintainDOM=“tru
e”)
Data Full support Full support Limited support
replication
The End…
Sources
 Oracle Database 10g XML & SQL: Design, Build, & Manage
XML Applications in Java, C, C++, & PL/SQL
 Authors: Mark Scardina, Ben Chang, Jinyu Wang
 Publisher: McGraw-Hill
 Oracle books: http://books.google.cz/books?id=cHt2YN5_JI8C
 Oracle:
 Oracle XML DB Developer's Guide 10g Release 2:
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b1
4259/toc.htm
 Oracle XML DB Developer's Guide 11g Release 1:
http://download.oracle.com/docs/cd/B28359_01/appdev.111/b2
8369/toc.htm
 Oracle XML DB Developer's Guide 11g Release 2:
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e1
0492/toc.htm

You might also like