Clase XML Oracle
Clase XML Oracle
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;
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;
-------------------------
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"
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>
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;
<?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;
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
<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;