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

Oracle9: XML Database Developer's Guide - Oracle XML DB

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Oracle9: XML Database Developer's Guide - Oracle XML DB

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1044

Oracle9i

XML Database Developers Guide - Oracle XML DB


Release 2 (9.2)
October 2002
Part No. A96620-02
Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2)
Part No. A96620-02
Copyright 2002 Oracle Corporation. All rights reserved.
Primary Author: Shelley Higgins
Graphics: Valarie Moore
Contributing Authors: Nipun Agarwal, Abhay Agrawal, Omar Alonso, Sandeepan Banerjee, Mark
Bauer, Ravinder Booreddy, Yuen Chan, Sivasankaran Chandrasekar, Vincent Chao, Mark Drake, Fei Ge,
Wenyun He, Thuvan Hoang, Sam Idicula, Neema Jalali, Bhushan Khaladkar, Viswanathan
Krishnamurthy, Muralidhar Krishnaprasad, Wesley Lin, Annie Liu, Anand Manikutty, Jack Melnick,
Nicolas Montoya, Steve Muench, Ravi Murthy, Eric Paapanen, Syam Pannala, John Russell, Eric Sedlar,
Vipul Shah, Cathy Shea, Tarvinder Singh, Simon Slack, Muralidhar Subramanian, Asha Tarachandani,
Randy Urbano, Priya Vennapusa, James Warner
Contributors: Harish Akali, Deanna Bradshaw, Paul Brandenstein, Lisa Eldridge, Geoff Lee, Susan
Kotsovolos, Sonia Kumar, Roza Leyderman, Diana Lorentz, Yasuhiro Matsuda, Bhagat Nainani, Visar
Nimani, Sunitha Patel, Denis Raphaely, Rebecca Reitmeyer, Ronen Wolf
The Programs (which include both the software and documentation) contain proprietary information of
Oracle Corporation; they are provided under a license agreement containing restrictions on use and
disclosure and are also protected by copyright, patent and other intellectual and industrial property
laws. Reverse engineering, disassembly or decompilation of the Programs, except to the extent required
to obtain interoperability with other independently created software or as specied by law, is prohibited.
The information contained in this document is subject to change without notice. If you nd any problems
in the documentation, please report them to us in writing. Oracle Corporation does not warrant that this
document is error-free. Except as may be expressly permitted in your license agreement for these
Programs, no part of these Programs may be reproduced or transmitted in any form or by any means,
electronic or mechanical, for any purpose, without the express written permission of Oracle Corporation.
If the Programs are delivered to the U.S. Government or anyone licensing or using the programs on
behalf of the U.S. Government, the following notice is applicable:
Restricted Rights Notice Programs delivered subject to the DOD FAR Supplement are "commercial
computer software" and use, duplication, and disclosure of the Programs, including documentation,
shall be subject to the licensing restrictions set forth in the applicable Oracle license agreement.
Otherwise, Programs delivered subject to the Federal Acquisition Regulations are "restricted computer
software" and use, duplication, and disclosure of the Programs shall be subject to the restrictions in FAR
52.227-19, Commercial Computer Software - Restricted Rights (June, 1987). Oracle Corporation, 500
Oracle Parkway, Redwood City, CA 94065.
The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently
dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup,
redundancy, and other measures to ensure the safe use of such applications if the Programs are used for
such purposes, and Oracle Corporation disclaims liability for any damages caused by such use of the
Programs.
Oracle is a registered trademark, and Oracle9i, Oracle8i, Oracle8, SQL*Plus, SQL*Net, Pro*C, On Oracle,
Oracle Store, ConText, and PL/SQL are trademarks or registered trademarks of Oracle Corporation.
Other names may be trademarks of their respective owners.
iii
Contents
Send Us Your Comments............................................................................................................... xxix
Preface........................................................................................................................................................ xxxi
Audience ............................................................................................................................................ xxxii
Organization...................................................................................................................................... xxxii
Related Documentation ................................................................................................................. xxxvii
Conventions.................................................................................................................................... xxxviii
Documentation Accessibility .............................................................................................................. xli
Whats New In Oracle XML DB? ................................................................................................... xliii
Oracle XML DB: Oracle9i Release 2 (9.2.0.2): Enhancements........................................................ xliii
Oracle XML DB, Oracle9i Release 2 (9.2.0.1): XMLType Enhancements..................................... xlv
Oracle XML DB, Oracle9i Release 2 (9.2.0.1): Repository ............................................................ xlvii
Oracle Tools Enhancements for Oracle XML DB........................................................................... xlix
Oracle Text Enhancements ................................................................................................................ xlix
Oracle Advanced Queuing (AQ) Support....................................................................................... xlix
Oracle XDK Support for XMLType....................................................................................................... l
Part I Introducing Oracle XML DB
1 Introducing Oracle XML DB
Introducing Oracle XML DB ............................................................................................................ 1-2
Not a Separate Database Server ................................................................................................. 1-2
Bene ts of Oracle XML DB............................................................................................................... 1-3
iv
Key Features of Oracle XML DB...................................................................................................... 1-4
Oracle XML DB and XML Schema .................................................................................................. 1-7
Oracle XML DB Architecture............................................................................................................ 1-7
XMLType Tables and Views Storage......................................................................................... 1-9
Oracle XML DB Repository....................................................................................................... 1-10
XMLType Storage Architecture ...................................................................................................... 1-11
Cached XML Object Management Architecture .................................................................... 1-14
XML Repository Architecture................................................................................................... 1-15
Why Use Oracle XML DB? .............................................................................................................. 1-16
Unifying Data and Content with Oracle XML DB................................................................. 1-17
Oracle XML DB Offers Faster Storage and Retrieval of Complex XML Documents........ 1-20
Oracle XML DB Helps You Integrate Applications............................................................... 1-21
When Your Data Is Not XML You Can Use XMLType Views............................................. 1-21
Searching XML Data Stored in CLOBs Using Oracle Text ....................................................... 1-23
Building Oracle XML DB XML Messaging Applications with Advanced Queueing......... 1-23
Managing Oracle XML DB Applications with Oracle Enterprise Manager.......................... 1-24
Requirements for Running Oracle XML DB............................................................................... 1-25
Standards Supported by Oracle XML DB.................................................................................... 1-25
Oracle XML DB Technical Support ............................................................................................... 1-26
Terminology Used in This Manual................................................................................................ 1-26
Oracle XML DB Examples Used in This Manual ....................................................................... 1-29
2 Getting Started with Oracle XML DB
Getting Started with Oracle XML DB............................................................................................. 2-2
Installing Oracle XML DB............................................................................................................ 2-2
When to Use the Oracle XML DB.................................................................................................... 2-2
Designing Your XML Application................................................................................................... 2-3
Oracle XML DB Design Issues: Introduction................................................................................ 2-3
a. Data............................................................................................................................................. 2-3
b. Access ......................................................................................................................................... 2-3
c. Application Language.............................................................................................................. 2-4
d. Processing.................................................................................................................................. 2-4
Storage............................................................................................................................................ 2-4
Oracle XML DB Application Design: a. How Structured Is Your Data?.................................. 2-5
Oracle XML DB Application Design: b. Access Models ............................................................. 2-7
v
Oracle XML DB Application Design: c. Application Language................................................ 2-8
Oracle XML DB Application Design: d. Processing Models...................................................... 2-9
Oracle XML DB Design: Storage Models..................................................................................... 2-10
Using XMLType Tables ............................................................................................................. 2-11
Using XMLType Views.............................................................................................................. 2-12
3 Using Oracle XML DB
Storing Data in an XMLType Column or XMLType Table.......................................................... 3-3
Accessing Data in XMLType Columns or XMLType Tables....................................................... 3-5
Using XPath with Oracle XML DB.................................................................................................. 3-5
Using existsNode() ....................................................................................................................... 3-7
Using extractValue()..................................................................................................................... 3-8
Using extract() ............................................................................................................................. 3-10
Using XMLSequence() ............................................................................................................... 3-11
Updating XML Documents with updateXML() .......................................................................... 3-13
Introducing the W3C XSLT Recommendation............................................................................ 3-15
Using XSL/XSLT with Oracle XML DB........................................................................................ 3-16
Other XMLType Methods................................................................................................................ 3-17
Introducing the W3C XML Schema Recommendation ............................................................. 3-18
Using XML Schema with Oracle XML DB.............................................................................. 3-19
XMLSchema-Instance Namespace........................................................................................... 3-21
Validating an XML Document Using an XML Schema............................................................. 3-22
Storing XML: Structured or Unstructured Storage..................................................................... 3-24
Data Manipulation Language (DML) Independence............................................................ 3-27
DOM Fidelity in Structured and Unstructured Storage ....................................................... 3-27
Structured Storage: XML Schema-Based Storage of XMLType ............................................... 3-28
Structured Storage: Storing complexType Collections ......................................................... 3-32
Structured Storage: Data Integrity and Constraint Checking.............................................. 3-33
Oracle XML DB Repository ............................................................................................................ 3-35
Query-Based Access to Oracle XML DB Repository.................................................................. 3-37
Using RESOURCE_VIEW......................................................................................................... 3-37
Using PATH_VIEW.................................................................................................................... 3-37
Creating New Folders and Documents................................................................................... 3-38
Querying Resource Documents................................................................................................ 3-38
Updating Resources ................................................................................................................... 3-38
vi
Deleting Resources ..................................................................................................................... 3-39
Storage Options for Resources ....................................................................................................... 3-40
De ning Your Own Default Table Storage for XML Schema-Based Documents................ 3-40
Accessing XML Schema-Based Content ....................................................................................... 3-44
Accessing Non-Schema-Based Content With XDBUriType ..................................................... 3-44
Oracle XML DB Protocol Servers................................................................................................... 3-44
Using FTP Protocol Server......................................................................................................... 3-45
Using HTTP/WebDAV Protocol Server ................................................................................. 3-49
Part II Storing and Retrieving XML Data in Oracle XML DB
4 Using XMLType
What Is XMLType?.............................................................................................................................. 4-2
Benefits of the XMLType Data Type and API .......................................................................... 4-3
When to Use XMLType ...................................................................................................................... 4-4
Storing XMLType Data in Oracle XML DB.................................................................................... 4-4
Pros and Cons of XML Storage Options in Oracle XML DB.................................................. 4-5
When to Use CLOB Storage for XMLType ............................................................................... 4-6
XMLType Member Functions ........................................................................................................... 4-7
How to Use the XMLType API ......................................................................................................... 4-7
Creating, Adding, and Dropping XMLType Columns ........................................................... 4-8
Inserting Values into an XMLType Column............................................................................. 4-9
Using XMLType in an SQL Statement....................................................................................... 4-9
Updating an XMLType Column............................................................................................... 4-10
Deleting a Row Containing an XMLType Column ............................................................... 4-10
Guidelines for Using XMLType Tables and Columns............................................................... 4-11
Specifying Storage Characteristics on XMLType Columns.................................................. 4-12
Changing Storage Options on an XMLType Column Using XMLData ............................. 4-13
Specifying Constraints on XMLType Columns...................................................................... 4-14
Manipulating XML Data in XMLType Columns/Tables ........................................................... 4-14
Inserting XML Data into XMLType Columns/Tables ................................................................ 4-15
Using INSERT Statements ......................................................................................................... 4-15
Selecting and Querying XML Data ............................................................................................... 4-17
Selecting XML Data .................................................................................................................... 4-17
Querying XML Data................................................................................................................... 4-18
vii
Using XPath Expressions for Searching XML Documents ................................................... 4-18
Querying XML Data Using XMLType Member Functions .................................................. 4-19
existsNode Function................................................................................................................... 4-20
extract () Function....................................................................................................................... 4-21
extractValue() Function ............................................................................................................. 4-24
More SQL Examples That Query XML ................................................................................... 4-26
Updating XML Instances and Data in Tables and Columns .................................................... 4-31
updateXML() SQL Function...................................................................................................... 4-31
Creating Views of XML Data with updateXML().................................................................. 4-35
Optimization of updateXML().................................................................................................. 4-35
updateXML() and NULL Values.............................................................................................. 4-36
Updating the Same XML Node More Than Once.................................................................. 4-37
XMLTransform() Function........................................................................................................ 4-37
Deleting XML Data........................................................................................................................... 4-38
Using XMLType In Triggers............................................................................................................ 4-38
Indexing XMLType Columns ......................................................................................................... 4-39
Creating Function-Based Indexes on XMLType Columns................................................... 4-39
Creating Oracle Text Indexes on XMLType Columns .......................................................... 4-40
5 Structured Mapping of XMLType
Introducing XML Schema ................................................................................................................. 5-3
XML Schema and Oracle XML DB.................................................................................................. 5-3
Using Oracle XML DB and XML Schema...................................................................................... 5-5
Why Do We Need XML Schema? .............................................................................................. 5-6
DTD Support in Oracle XML DB................................................................................................ 5-7
Introducing DBMS_XMLSCHEMA................................................................................................ 5-8
Registering Your XML Schema Before Using Oracle XML DB................................................. 5-8
Registering Your XML Schema Using DBMS_XMLSCHEMA.............................................. 5-9
Local and Global XML Schemas............................................................................................... 5-11
Registering Your XML Schema: Oracle XML DB Sets Up the Storage and Access
Infrastructure ............................................................................................................................... 5-13
Deleting Your XML Schema Using DBMS_XMLSCHEMA..................................................... 5-13
Guidelines for Using Registered XML Schemas........................................................................ 5-14
Objects That Depend on Registered XML Schemas .............................................................. 5-14
viii
Creating XMLType Tables, Views, or Columns..................................................................... 5-15
Validating XML Instances Against the XML Schema: schemaValidate()........................... 5-15
Fully Qualified XML Schema URLs......................................................................................... 5-16
Transactional Behavior of XML Schema Registration........................................................... 5-17
Generating XML Schema Using DBMS_XMLSCHEMA.generateSchema() ........................ 5-17
XML Schema-Related Methods of XMLType.............................................................................. 5-19
Managing and Storing XML Schema............................................................................................ 5-19
Root XML Schema, XDBSchema.xsd ....................................................................................... 5-19
How Are XML Schema-Based XMLType Structures Stored? .............................................. 5-20
DOM Fidelity..................................................................................................................................... 5-21
How Oracle XML DB Ensures DOM Fidelity with XML Schema....................................... 5-21
DOM Fidelity and SYS_XDBPD$ ............................................................................................. 5-21
Creating XMLType Tables and Columns Based on XML Schema........................................... 5-22
SQL Object-Relational Types Store XML Schema-Based XMLType Tables....................... 5-23
Specifying SQL Object Type Names with SQLName, SQLType Attributes......................... 5-24
SQL Mapping Is Specified in the XML Schema During Registration................................. 5-28
Mapping of Types Using DBMS_XMLSCHEMA...................................................................... 5-31
Setting Attribute Mapping Type Information........................................................................ 5-31
Setting Element Mapping Type Information.......................................................................... 5-31
XML Schema: Mapping SimpleTypes to SQL............................................................................. 5-33
simpleType: Mapping XML Strings to SQL VARCHAR2 Versus CLOBs ......................... 5-36
XML Schema: Mapping complexTypes to SQL .......................................................................... 5-37
Setting the SQLInLine Attribute to FALSE for Out-of-Line Storage................................... 5-37
Mapping XML Fragments to Large Objects (LOBs) .............................................................. 5-39
Oracle XML DB complexType Extensions and Restrictions..................................................... 5-41
complexType Declarations in XML Schema: Handling Inheritance................................... 5-41
Mapping complexType: simpleContent to Object Types ..................................................... 5-44
Mapping complexType: Any and AnyAttributes.................................................................. 5-45
Handling Cycling Between complexTypes in XML Schema................................................ 5-46
Further Guidelines for Creating XML Schema-Based XML Tables........................................ 5-49
Specifying Storage Clauses in XMLType CREATE TABLE Statements............................. 5-50
Inserting New Instances into XMLType Columns ................................................................ 5-51
Query Rewrite with XML Schema-Based Structured Storage ................................................. 5-51
What Is Query Rewrite?............................................................................................................. 5-51
When Does Query Rewrite Occur? .......................................................................................... 5-52
ix
What XPath Expressions Are Rewritten?................................................................................ 5-53
How are the XPaths Rewritten?................................................................................................ 5-55
Rewriting XPath Expressions: Mapping Types and Issues.................................................. 5-57
XPath Expression Rewrites for existsNode().......................................................................... 5-62
Rewrite for extractValue() ......................................................................................................... 5-65
Rewrite for extract().................................................................................................................... 5-67
Optimizing Updates Using updateXML() .............................................................................. 5-69
Creating Default Tables During XML Schema Registration.................................................... 5-70
Ordered Collections in Tables (OCTs).......................................................................................... 5-71
Using OCT for VARRAY Storage............................................................................................. 5-71
Cyclical References Between XML Schemas............................................................................... 5-71
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues...................... 5-74
Why Do I Appear to get Memory Leaks When Using Bind Variables for XPath
Expressions? ............................................................................................................................... 5-74
How Do I Check that Query Rewrite is Working Correctly?............................................... 5-77
Why Does the XML DB Query Not Use My Index?.............................................................. 5-78
How Do I Specify Attributes in a complexType XML Schema Declaration? .................... 5-79
Why Do the XML Schema and Element Not Match?............................................................ 5-81
How Do I Pull a Stylesheet From RESOURCE_VIEW [S/MIME]?..................................... 5-82
Why for Our XML Parser Does selectSingleNode return NULL When the xmlns
Attribute is Added?.................................................................................................................... 5-82
Why Do I Get Error ORA-19007: Schema and Element Do Not Match?............................ 5-84
Is it Possible to Register XML Schema for Schemas? ............................................................ 5-86
6 Transforming and Validating XMLType Data
Transforming XMLType Instances................................................................................................... 6-2
XMLTransform() and XMLType.transform() ........................................................................... 6-2
XMLTransform() Examples ............................................................................................................... 6-3
Validating XMLType Instances ........................................................................................................ 6-8
Validating XML Data Stored as XMLType: Examples ............................................................... 6-10
7 Searching XML Data with Oracle Text
Searching XML Data with Oracle Text ........................................................................................... 7-3
Introducing Oracle Text ..................................................................................................................... 7-3
Assumptions Made in This Chapters Examples.......................................................................... 7-4
x
Oracle Text Users and Roles.............................................................................................................. 7-5
Querying with the CONTAINS Operator ...................................................................................... 7-6
Using the WITHIN Operator to Narrow Query Down to Document Sections....................... 7-8
Introducing SECTION_GROUPS.................................................................................................... 7-8
XML_SECTION_GROUP ............................................................................................................ 7-8
AUTO_ SECTION_GROUP/ PATH_SECTION_GROUP for INPATH and HASPATH 7-10
Dynamically Adding Sections or Stop Section Using ALTER INDEX ............................... 7-10
WITHIN Syntax for Section Querying..................................................................................... 7-11
WITHIN Operator Limitations ................................................................................................. 7-11
INPATH or HASPATH Operators Search UsingXPath-Like Expressions.............................. 7-12
Using INPATH Operator for Path Searching in XML Documents ..................................... 7-13
Using HASPATH Operator for Path Searching in XML Documents.................................. 7-19
Building a Query Application with Oracle Text ......................................................................... 7-21
What Role Do You Need?.......................................................................................................... 7-21
Step 1. Create a Section Group Preference................................................................................... 7-21
Deciding Which Section Group to Use.................................................................................... 7-23
Creating a Section Preference with XML_SECTION_GROUP ............................................ 7-23
Creating a Section Preference with AUTO_SECTION_GROUP.......................................... 7-23
Creating a Section Preference with PATH_SECTION_GROUP.......................................... 7-24
Step 2. Set the Preferences Attributes .......................................................................................... 7-24
2.1 XML_SECTION_GROUP: Using CTX_DDL.add_zone_section.................................... 7-25
2.2 XML_SECTION_GROUP: Using CTX_DDL.Add_Attr_Section................................... 7-25
2.3 XML_SECTION_GROUP: Using CTX_DDL.Add_Field_Section.................................. 7-26
2.5 AUTO_SECTION_GROUP: Using CtX_DDL.Add_Stop_Section................................. 7-28
Step 3. Create an Index Using the Section Preference Created in Step 2............................... 7-28
Step 4. Create Your Query Syntax.................................................................................................. 7-30
Querying Within Attribute Sections ........................................................................................ 7-30
Presenting the Results of Your Query........................................................................................... 7-34
XMLType Indexing ........................................................................................................................... 7-35
You Need Query Rewrite Privileges........................................................................................ 7-35
System Parameter is Set to the Default, CTXSYS.PATH_SECTION_GROUP................... 7-36
XMLType Indexes Work Like Other Oracle Text Indexes.................................................... 7-36
Using Oracle Text with Oracle XML DB....................................................................................... 7-37
Creating an Oracle Text Index on an UriType Column........................................................ 7-37
Querying XML Data: Use CONTAINS or existsNode()?...................................................... 7-38
xi
Full-Text Search Functions in XPath Using ora:contains .......................................................... 7-40
ora:contains Features.................................................................................................................. 7-40
ora:contains Syntax..................................................................................................................... 7-40
ora:contains Examples ............................................................................................................... 7-41
Oracle XML DB: Creating a Policy for ora:contains() ................................................................ 7-42
Oracle XML DB: Using CTXXPATH Indexes for existsNode() ................................................ 7-45
Why do We Need CTXXPATH When ConText Indexes Can Perform XPath Searches?. 7-45
CTXXPATH Index Type ............................................................................................................ 7-46
Creating CTXXPATH Indexes .................................................................................................. 7-46
Creating CTXXPATH Storage Preferences with CTX_DDL. Statements ........................... 7-47
Performance Tuning CTXXPATH Index: Synchronizing and Optimizing the Index...... 7-47
Using Oracle Text: Advanced Techniques.................................................................................... 7-49
Highlight Support for INPATH/HASPATH Text Operators.............................................. 7-49
Distinguishing Tags Across DocTypes.................................................................................... 7-51
Specifying Doctype Limiters to Distinguish Between Tags ................................................. 7-51
Doctype-Limited and Unlimited Tags in a Section Group................................................... 7-52
XML_SECTION_GROUP Attribute Sections ......................................................................... 7-52
Constraints for Querying Attribute Sections.......................................................................... 7-54
Repeated Zone Sections............................................................................................................. 7-55
Overlapping Zone Sections....................................................................................................... 7-55
Nested Sections ........................................................................................................................... 7-55
Using Table CTX_OBJECTS and CTX_OBJECT_ATTRIBUTES View................................ 7-56
Case Study: Searching XML-Based Conference Proceedings .................................................. 7-57
Searching for Content and Structure in XML Documents.................................................... 7-57
Searching XML-Based Conference Proceedings Using Oracle Text ................................... 7-58
Searching Conference Proceedings Example: jsp .................................................................. 7-62
Frequently Asked Questions About Oracle Text........................................................................ 7-65
FAQs: General Questions About Oracle Text......................................................................... 7-65
FAQs: Searching Attribute Values with Oracle Text............................................................. 7-71
FAQs: Searching XML Documents in CLOBs Using Oracle Text ....................................... 7-71
xii
Part III Using XMLType APIs to Manipulate XML Data
8 PL/SQL API for XMLType
Introducing PL/SQL APIs for XMLType ........................................................................................ 8-2
Backward Compatibility with XDK for PL/SQL, Oracle9i Release 1 (9.0.1) ....................... 8-2
PL/SQL APIs For XMLType Features....................................................................................... 8-3
With PL/SQL APIs for XMLType You Can Modify and Store XML Elements .................. 8-4
PL/SQL DOM API for XMLType (DBMS_XMLDOM) ............................................................... 8-5
Introducing W3C Document Object Model (DOM) Recommendation................................ 8-5
PL/SQL DOM API for XMLType (DBMS_XMLDOM): Features ......................................... 8-7
Designing End-to-End Applications Using XDK and Oracle XML DB................................ 8-8
Using PL/SQL DOM API for XMLType: Preparing XML Data............................................ 8-9
Generating an XML Schema Mapping to SQL Object Types ............................................... 8-10
Wrapping Existing Data into XML with XMLType Views................................................... 8-11
PL/SQL DOM API for XMLType (DBMS_XMLDOM) Methods........................................ 8-11
PL/SQL DOM API for XMLType (DBMS_XMLDOM) Exceptions .................................... 8-20
PL/SQL DOM API for XMLType: Node Types..................................................................... 8-20
Working with XML Schema-Based XML Instances............................................................... 8-22
DOM NodeList and NamesNodeMap Objects....................................................................... 8-22
PL/SQL DOM API for XMLType (DBMS_XMLDOM): Calling Sequence........................ 8-23
PL/SQL DOM API for XMLType Examples .......................................................................... 8-24
PL/SQL Parser API for XMLType (DBMS_XMLPARSER) ....................................................... 8-26
PL/SQL Parser API for XMLType: Features .......................................................................... 8-26
PL/SQL Parser API for XMLType (DBMS_XMLPARSER): Calling Sequence ................. 8-28
PL/SQL Parser API for XMLType Example........................................................................... 8-29
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR) ....................................... 8-30
Enabling Transformations and Conversions with XSLT ...................................................... 8-30
PL/SQL XSLT Processor for XMLType: Features.................................................................. 8-30
PL/SQL XSLT Processor API (DBMS_XSLPROCESSOR): Methods .................................. 8-31
PL/SQL Parser API for XMLType (DBMS_XSLPROCESSOR): Calling Sequence........... 8-32
PL/SQL XSLT Processor for XMLType Example .................................................................. 8-33
9 Java API for XMLType
Introducing Java DOM API for XMLType..................................................................................... 9-2
xiii
Java DOM API for XMLType............................................................................................................ 9-2
Accessing XML Documents Stored in Oracle9i Database (Java) ........................................... 9-2
Using JDBC to Manipulate XML Documents Stored in a Database...................................... 9-5
Java DOM API for XMLType Features ......................................................................................... 9-15
Java DOM API for XMLType Classes ........................................................................................... 9-17
Non-Supported Java Methods.................................................................................................. 9-18
Java DOM API for XMLType: Calling Sequence ................................................................... 9-18
Part IV Viewing Existing Data as XML
10 Generating XML Data from the Database
Oracle XML DB Options for Generating XML Data From Oracle9i Database..................... 10-2
Generating XML Using SQLX Functions ................................................................................ 10-2
Generating XML Using Oracle Extensions to SQLX ............................................................. 10-2
Generating XML Using DBMS_XMLGEN.............................................................................. 10-2
Generating XML Using SQL Functions................................................................................... 10-2
Generating XML with XSQL Pages Publishing Framework................................................ 10-3
Generating XML Using XML SQL Utility (XSU) ................................................................... 10-3
Generating XML from the Database Using SQLX Functions .................................................. 10-5
XMLElement() Function.................................................................................................................. 10-5
XMLForest() Function...................................................................................................................... 10-9
XMLSEQUENCE() Function......................................................................................................... 10-11
XMLConcat() Function................................................................................................................... 10-15
XMLAgg() Function........................................................................................................................ 10-17
Generating XML from the Database Using SQLX Functions ................................................ 10-20
XMLColAttVal() Function............................................................................................................. 10-20
Generating XML from Oracle9i Database Using DBMS_XMLGEN.................................... 10-21
Sample DBMS_XMLGEN Query Result ............................................................................... 10-21
DBMS_XMLGEN Calling Sequence ...................................................................................... 10-22
Generating XML Using Oracle-Provided SQL Functions ...................................................... 10-42
SYS_XMLGEN() Function............................................................................................................. 10-42
Using XMLFormat Object Type.............................................................................................. 10-44
SYS_XMLAGG() Function............................................................................................................ 10-51
Generating XML Using XSQL Pages Publishing Framework............................................... 10-52
Generating XML Using XML SQL Utility (XSU) ..................................................................... 10-54
xiv
11 XMLType Views
What Are XMLType Views? ............................................................................................................ 11-2
Creating Non-Schema-Based XMLType Views........................................................................... 11-3
Creating XML Schema-Based XMLType Views .......................................................................... 11-4
Creating XML Schema-Based XMLType Views Using SQL/XML Generation
Functions 11-5
Creating XMLType Views Using Object Types and Views................................................ 11-11
Creating XMLType Views From XMLType Tables ................................................................... 11-17
Referencing XMLType View Objects Using REF()................................................................... 11-18
DML (Data Manipulation Language) on XMLType Views .................................................... 11-19
Query Rewrite on XMLType Views............................................................................................. 11-20
Query Rewrite on XML Schema-Based Views ..................................................................... 11-21
Query Rewrite on Non-Schema-Based XMLType Views ................................................... 11-21
Ad-Hoc Generation of XML Schema-Based XML.................................................................... 11-23
Validating User-Speci ed Information....................................................................................... 11-24
12 Creating and Accessing Data Through URLs
How Oracle9i Database Works with URLs and URIs................................................................ 12-2
URI Concepts ..................................................................................................................................... 12-4
What Is a URI?............................................................................................................................. 12-4
Advantages of Using DBUri and XDBUri............................................................................... 12-5
UriTypes Store Uri-References...................................................................................................... 12-6
Advantages of Using UriTypes ................................................................................................ 12-7
UriType Functions ...................................................................................................................... 12-7
HttpUriType Functions .................................................................................................................... 12-8
getContentType() Function ....................................................................................................... 12-9
getXML() Function...................................................................................................................... 12-9
DBUri, Intra-Database References .............................................................................................. 12-10
Formulating the DBUri ............................................................................................................ 12-10
Notation for DBUriType Fragments ...................................................................................... 12-13
DBUri Syntax Guidelines......................................................................................................... 12-13
Some Common DBUri Scenarios................................................................................................. 12-15
Identifying the Whole Table.................................................................................................... 12-15
Identifying a Particular Row of the Table ............................................................................. 12-16
Identifying a Target Column................................................................................................... 12-16
xv
Retrieving the Text Value of a Column................................................................................. 12-17
How DBUris Differ from Object References......................................................................... 12-18
DBUri Applies to a Database and Session ............................................................................ 12-18
Where Can DBUri Be Used? ................................................................................................... 12-18
DBUriType Functions .................................................................................................................... 12-19
XDBUriType..................................................................................................................................... 12-20
How to Create an Instance of XDBUriType.......................................................................... 12-21
Creating Oracle Text Indexes on UriType Columns ................................................................ 12-23
Using UriType Objects .................................................................................................................. 12-23
Storing Pointers to Documents with UriType...................................................................... 12-23
Using HttpUriType and DBUriType ..................................................................................... 12-25
Creating Instances of UriType Objects with the UriFactory Package .................................. 12-26
Registering New UriType Subtypes with the UriFactory Package................................... 12-26
Why De ne New Subtypes of UriType? .................................................................................... 12-29
SYS_DBURIGEN() SQL Function............................................................................................... 12-29
Rules for Passing Columns or Object Attributes to SYS_DBURIGEN() ........................... 12-30
SYS_DBURIGEN Examples..................................................................................................... 12-31
Turning a URL into a Database Query with DBUri Servlet ................................................... 12-34
DBUri Servlet Mechanism....................................................................................................... 12-34
Installing DBUri Servlet........................................................................................................... 12-36
DBUri Security .......................................................................................................................... 12-37
Configuring the UriFactory Package to Handle DBUris .................................................... 12-38
Part V Oracle XML DB Repository: Foldering, Security, and Protocols
13 Oracle XML DB Foldering
Introducing Oracle XML DB Foldering........................................................................................ 13-2
Oracle XML DB Repository ............................................................................................................ 13-4
Repository Terminology............................................................................................................ 13-4
Oracle XML DB Resources.............................................................................................................. 13-6
Where Exactly Is Repository Data Stored? ............................................................................. 13-6
Pathname Resolution ................................................................................................................. 13-7
Deleting Resources ..................................................................................................................... 13-7
Accessing Oracle XML DB Repository Resources...................................................................... 13-8
Navigational or Path Access ........................................................................................................... 13-9
xvi
Accessing Oracle XML DB Resources Using Internet Protocols........................................ 13-10
Query-Based Access........................................................................................................................ 13-12
Accessing Repository Data Using Servlets ................................................................................ 13-13
Accessing Data Stored in Oracle XML DB Repository Resources ........................................ 13-14
Managing and Controlling Access to Resources ...................................................................... 13-16
Extending Resource Metadata Properties .................................................................................. 13-17
Frequently Asked Questions (FAQs): XML DB Repository................................................... 13-18
Why Does XML Repository Hierarchical Index Not Work? .............................................. 13-18
14 Oracle XML DB Versioning
Introducing Oracle XML DB Versioning...................................................................................... 14-2
Oracle XML DB Versioning Features....................................................................................... 14-2
Oracle XML DB Versioning Terms Used in This Chapter.................................................... 14-3
Oracle XML DB Resource ID and Path Name ........................................................................ 14-3
Creating a Version-Controlled Resource (VCR) ......................................................................... 14-4
Version Resource or VCR Version ........................................................................................... 14-4
Resource ID of a New Version.................................................................................................. 14-5
Accessing a Version-Controlled Resource (VCR) .................................................................. 14-6
Updating a Version-Controlled Resource (VCR) ................................................................... 14-6
Access Control and Security of VCR............................................................................................. 14-8
Frequently Asked Questions: Oracle XML DB Versioning.................................................... 14-12
Can I Switch a VCR to a Non-VCR?....................................................................................... 14-12
How Do I Access the Old Copy of a VCR After Updating It? ........................................... 14-12
Can We Use Version Control for Data Other Than Oracle XML DB Data? ..................... 14-12
15 RESOURCE_VIEW and PATH_VIEW
Oracle XML DB RESOURCE_VIEW and PATH_VIEW............................................................ 15-2
RESOURCE_VIEW Definition and Structure......................................................................... 15-3
PATH_VIEW Definition and Structure ................................................................................... 15-4
Understanding the Difference Between RESOURCE_VIEW and PATH_VIEW............... 15-5
Operations You Can Perform Using UNDER_PATH and EQUALS_PATH..................... 15-6
Resource_View, Path_View API..................................................................................................... 15-7
UNDER_PATH................................................................................................................................... 15-7
EQUALS_PATH................................................................................................................................. 15-9
PATH.................................................................................................................................................... 15-9
xvii
DEPTH.............................................................................................................................................. 15-11
Using the Resource View and Path View API........................................................................... 15-11
Accessing Paths and Repository Resources: Examples....................................................... 15-11
Inserting Data into a Repository Resource: Examples ........................................................ 15-12
Deleting Repository Resources: Examples............................................................................ 15-13
Updating Repository Resources: Examples.......................................................................... 15-14
Working with Multiple Oracle XML DB Resources Simultaneously .................................. 15-15
Tuning XML DB to Obtain Faster Queries ................................................................................ 15-16
Searching for Resources Using Oracle Text............................................................................... 15-16
16 Oracle XML DB Resource API for PL/SQL (DBMS_XDB)
Introducing Oracle XML DB Resource API for PL/SQL........................................................... 16-2
Overview of DBMS_XDB ............................................................................................................... 16-2
DBMS_XDB: Oracle XML DB Resource Management ............................................................. 16-2
Using DBMS_XDB to Manage Resources, Calling Sequence............................................... 16-3
DBMS_XDB: Oracle XML DB ACL-Based Security Management ......................................... 16-5
Using DBMS_XDB to Manage Security, Calling Sequence .................................................. 16-6
DBMS_XDB: Oracle XML DB Con guration Management..................................................... 16-8
Using DBMS_XDB for Configuration Management, Calling Sequence............................. 16-9
DBMS_XDB: Rebuilding Oracle XML DB Hierarchical Indexes.......................................... 16-11
Using DBMS_XDB to Rebuild Hierarchical Indexes, Calling Sequence........................... 16-11
17 Oracle XML DB Resource API for Java
Introducing Oracle XML DB Resource API for Java.................................................................. 17-2
Using Oracle XML DB Resource API for Java ............................................................................ 17-2
Parameters for Oracle XML DB Resource API for Java............................................................. 17-2
Oracle XML DB Resource API for Java: Examples..................................................................... 17-3
18 Oracle XML DB Resource Security
Introducing Oracle XML DB Resource Security and ACLs...................................................... 18-2
How the ACL-Based Security Mechanism Works................................................................. 18-2
Access Control List Terminology................................................................................................... 18-2
Oracle XML DB ACL Features ....................................................................................................... 18-5
ACL Interaction with Oracle XML DB Table/View Security .............................................. 18-5
xviii
LDAP Integration and User IDs ............................................................................................... 18-5
Oracle XML DB Resource API for ACLs (PL/SQL) .............................................................. 18-5
How Concurrency Issues Are Resolved with Oracle XML DB ACLs................................. 18-5
Access Control: User and Group Access....................................................................................... 18-6
ACE Elements Specify Access Privileges for Principals ....................................................... 18-6
Oracle XML DB Supported Privileges.......................................................................................... 18-7
Atomic Privileges........................................................................................................................ 18-8
Aggregate Privileges .................................................................................................................. 18-9
ACL Evaluation Rules.................................................................................................................... 18-10
Using Oracle XML DB ACLs ........................................................................................................ 18-10
Updating the Default ACL on a Folder ................................................................................. 18-11
ACL and Resource Management.................................................................................................. 18-12
How to Set Resource Property ACLs..................................................................................... 18-12
Default Assignment of ACLs .................................................................................................. 18-12
Retrieving ACLs for a Resource ............................................................................................. 18-13
Changing Privileges on a Given Resource............................................................................ 18-13
Restrictions for Operations on ACLs ..................................................................................... 18-13
Using DBMS_XDB to Check Privileges ..................................................................................... 18-13
Row-Level Security for Access Control Security ................................................................. 18-14
19 Using FTP, HTTP, and WebDAV Protocols
Introducing Oracle XML DB Protocol Server.............................................................................. 19-2
Session Pooling............................................................................................................................ 19-2
Oracle XML DB Protocol Server Con guration Management ................................................. 19-3
Configuring Protocol Server Parameters ................................................................................ 19-4
Interaction with Oracle XML DB Filesystem Resources ....................................................... 19-6
Protocol Server Handles XML Schema-Based or Non-Schema-Based XML Documents 19-7
Event-Based Logging ................................................................................................................. 19-7
Using FTP and Oracle XML DB Protocol Server ........................................................................ 19-7
Oracle XML DB Protocol Server: FTP Features...................................................................... 19-7
Using HTTP and Oracle XML DB Protocol Server..................................................................... 19-9
Oracle XML DB Protocol Server: HTTP Features .................................................................. 19-9
Using WebDAV and Oracle XML DB ......................................................................................... 19-11
Oracle XML DB WebDav Features......................................................................................... 19-11
Using Oracle XML DB and WebDAV: Creating a WebFolder in Windows 2000 ........... 19-12
xix
20 Writing Oracle XML DB Applications in Java
Introducing Oracle XML DB Java Applications ......................................................................... 20-2
Which Oracle XML DB APIs Are Available Inside and Outside the Database?............... 20-2
Design Guidelines: Java Inside or Outside the Database?....................................................... 20-3
HTTP: Accessing Java Servlets or Directly Accessing XMLType Resources..................... 20-3
Accessing Many XMLType Object Elements: Use JDBC XMLType Support .................... 20-3
Use the Servlets to Manipulate and Write Out Data Quickly as XML ............................... 20-3
Writing Oracle XML DB HTTP Servlets in Java......................................................................... 20-4
Con guring Oracle XML DB Servlets .......................................................................................... 20-4
HTTP Request Processing for Oracle XML DB Servlets........................................................... 20-8
The Session Pool and XML DB Servlets ...................................................................................... 20-9
Native XML Stream Support .......................................................................................................... 20-9
Oracle XML DB Servlet APIs ....................................................................................................... 20-10
Oracle XML DB Servlet Example................................................................................................. 20-10
Installing the Oracle XML DB Example Servlet ................................................................... 20-11
Configuring the Oracle XML DB Example Servlet .............................................................. 20-12
Testing the Example Servlet.................................................................................................... 20-12
Part VI Oracle Tools that Support Oracle XML DB
21 Managing Oracle XML DB Using Oracle Enterprise Manager
Introducing Oracle XML DB and Oracle Enterprise Manager ................................................ 21-2
Getting Started with Oracle Enterprise Manager and Oracle XML DB ............................. 21-2
Oracle Enterprise Manager Oracle XML DB Features............................................................... 21-3
Configure Oracle XML DB........................................................................................................ 21-4
Create and Manage Resources.................................................................................................. 21-4
Manage XML Schema and Related Database Objects........................................................... 21-4
The Enterprise Manager Console for Oracle XML DB.............................................................. 21-7
XML Database Management Window: Right-Hand Dialog Windows .............................. 21-7
Hierarchical Navigation Tree: Navigator ............................................................................... 21-7
Con guring Oracle XML DB with Enterprise Manager ........................................................... 21-7
Viewing or Editing Oracle XML DB Configuration Parameters ....................................... 21-11
Creating and Managing Oracle XML DB Resources with Enterprise Manager................. 21-12
Administering Individual Resources..................................................................................... 21-15
xx
Individual Resource Content Menu....................................................................................... 21-17
Enterprise Manager and Oracle XML DB: ACL Security ................................................... 21-22
Granting and Revoking User Privileges with User > XML Tab ........................................ 21-23
XML Database Resource Privileges........................................................................................ 21-25
Managing XML Schema and Related Database Objects......................................................... 21-27
Navigating XML Schema in Enterprise Manager ................................................................ 21-28
Registering an XML Schema ................................................................................................... 21-31
Creating Structured Storage Infrastructure Based on XML Schema .................................... 21-34
Creating an XMLType Table................................................................................................... 21-35
Creating Tables with XMLType Columns ............................................................................ 21-37
Creating a View Based on XML Schema............................................................................... 21-39
Creating a Function-Based Index Based on XPath Expressions ........................................ 21-42
22 Loading XML Data into Oracle XML DB
Loading XMLType Data into Oracle9i Database ........................................................................ 22-2
Restoration................................................................................................................................... 22-2
Using SQL*Loader to Load XMLType Columns......................................................................... 22-2
23 Importing and Exporting XMLType Tables
Overview of IMPORT/EXPORT Support in Oracle XML DB.................................................. 23-2
Resource s and Foldering Do Not Fully Support IMPORT/EXPORT................................ 23-2
Non-XML Schema-Based XMLType Tables and Columns ....................................................... 23-2
XML Schema-Based XMLType Tables .......................................................................................... 23-2
Guidelines for Exporting Hierarchy-Enabled Tables ............................................................ 23-3
IMPORT/EXPORT Syntax and Examples..................................................................................... 23-4
User Level Import/Export......................................................................................................... 23-4
Table Mode Export ..................................................................................................................... 23-5
Metadata in Repository is Not Exported During a Full Database Export.............................. 23-6
Importing and Exporting with Different Character Sets .......................................................... 23-6
xxi
Part VII XML Data Exchange Using Advanced Queueing
24 Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams
What Is AQ?....................................................................................................................................... 24-2
How Do AQ and XML Complement Each Other?...................................................................... 24-2
Oracle Streams and AQ................................................................................................................... 24-5
Streams Message Queuing........................................................................................................ 24-6
XMLType Attributes in Object Types ........................................................................................... 24-6
Internet Data Access Presentation (IDAP)................................................................................... 24-7
IDAP Architecture ............................................................................................................................ 24-7
XMLType Queue Payloads ....................................................................................................... 24-8
Enqueue Using AQ XML Servlet................................................................................................. 24-10
Dequeue Using AQ XML Servlet ................................................................................................ 24-13
IDAP and AQ XML Schemas ....................................................................................................... 24-14
Frequently Asked Questions (FAQs): XML and Advanced Queuing .................................. 24-14
Can I Store AQ XML Messages with Many PDFs as One Record? ................................... 24-14
Do I Specify Payload Type as CLOB First, Then Enqueue and Store? ............................. 24-15
Can I Add New Recipients After Messages Are Enqueued?............................................. 24-15
How Does Oracle Enqueue and Dequeue and Process XML Messages?......................... 24-15
How Can I Parse Messages with XML Content from AQ Queues?.................................. 24-16
Can I Prevent the Listener from Stopping Until the XML Document Is Processed?...... 24-17
How Can I Use HTTPS with AQ? .......................................................................................... 24-17
What Are the Options for Storing XML in AQ Message Payloads? ................................. 24-17
Can We Compare IDAP and SOAP? ..................................................................................... 24-18
Part VIII Oracle XML DB Case Studies
25 Oracle XML DB Case Study: Web Services Retrieve and Display XML
Documents
XML DB Web Services Case Study: Overview........................................................................... 25-2
What Happens When You Enter a PO Number?................................................................... 25-2
Oracle XML Db Web Services: Main Components................................................................ 25-2
Running XML DB Web Services Case Study: Implementation Steps.................................... 25-3
Before You Run this Case Study Demo................................................................................... 25-3
xxii
Steps for Implementing the XML DB Web Services Case Study ......................................... 25-9
1. Run XDBServices.java.......................................................................................................... 25-10
2. Implement GetPOXMLServlet.java.................................................................................... 25-11
3. Deploy XDBServices Class to the Oracle9iAS/Web Services (SOAP) Server.............. 25-11
4. Deploy displayPOXML.html to Display Results on Client-Side Web Server.............. 25-12
5. Enter a PO Number and See the Retrieved PO Displayed............................................. 25-13
XML DB Web Services: Calling Sequence................................................................................. 25-14
XDBServices.java ............................................................................................................................ 25-15
getPOXMLServlet.java................................................................................................................... 25-19
26 Oracle XML DB Basic Demo
Prerequisites for Running the XML DB Basic Demo ................................................................ 26-2
Database SQL*NET and XML DB Configuration .................................................................. 26-3
Verify SQL*NET and XML DB Configuration ....................................................................... 26-7
Installing XML DB Basic Demo..................................................................................................... 26-8
Editing installParameters.xml................................................................................................... 26-9
Running the Installation Script ................................................................................................. 26-9
What is Oracle XML DB?............................................................................................................... 26-11
Oracle XML DB Components.................................................................................................. 26-12
Starting the XML DB Basic Demo .............................................................................................. 26-12
0.1 XML DB Demo: Initial Setup (Run Once) ........................................................................... 26-13
0.2 XML DB Demo: Resetting the Demo.................................................................................... 26-14
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support ............................ 26-14
1.1 Using SQL to Make Directories ........................................................................................ 26-17
1.2 Using FTP to Load Configuration Files........................................................................... 26-19
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML....................... 26-22
2.1 Registering XML Schema................................................................................................... 26-28
2.2 Objects Are Created With XML Schema Registration................................................... 26-30
3.0 XML DB Demo: How XML Files Conform to the XML Schema...................................... 26-31
3.1 Using FTP to Load Instance Documents ......................................................................... 26-33
3.2 Using SQL to Add Constraints to XML Data ................................................................. 26-34
3.3 Using FTP to Upload XML Documents that Attempt to Violate the Constraints..... 26-37
4.0 XML DB Demo: Simple XPath Queries Against XML Documents................................. 26-42
4.1 More Complex XPath Queries on XML Documents...................................................... 26-44
4.2 EXPLAIN Plan of Queries on XML Tables ..................................................................... 26-46
xxiii
4.3 Using extractValue() and an XPath Expression to Create XML Indexes.................... 26-48
4.4 Using EXPLAIN Plan to Determine if the Index is Being Used .................................. 26-49
5.0 XML DB Demo: Using HTTP to Access XML Content...................................................... 26-51
5.1 SQL Can Display the Retrieved XML Document Through XDBUriServlet............... 26-54
5.2 Editing XML Documents with WebDAV-Enabled Tools ............................................. 26-56
5.3 Displaying and Verifying Updates Made to XML Documents, Using SQL.............. 26-57
5.4 Updating XML Documents Using SQL........................................................................... 26-59
5.5 Displaying Changes Made to an XML Document Using Both XML and SQL.......... 26-60
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL .......................................... 26-62
6.1 XPath-Based Querying of RESOURCE_VIEWS Using Hierarchical Indexing.......... 26-68
7.0 XML DB Demo: Using Views to Access XML from Relational Tools ............................ 26-70
7.1 Relational Views of XML Act Like Other Views............................................................ 26-73
7.2 Querying Using Rollup...................................................................................................... 26-75
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content
Using XSL.................................................................................................................................. 26-76
8.1 PurchaseOrder Raw XML ................................................................................................. 26-77
8.2 Using Standard XSL Style Sheets to Transform XML Documents to HTML ............ 26-79
8.3 Transforming PurchaseOrder Using XSLT..................................................................... 26-81
8.4 Creating XMLType Views with SQL............................................................................... 26-83
8.5 Displaying DEPTVIEW Raw XML Using DBUriServlet .............................................. 26-85
8.6 Transforming DEPTVIEW From XML to HTML Using a Style Sheet ........................ 26-86
8.7 Displaying the Transformed DEPTVIEW After XSL Transformation........................ 26-87
9.0 XML DB Demo: OracleText Examples.................................................................................. 26-89
A Installing and Configuring Oracle XML DB
Installing Oracle XML DB ................................................................................................................ A-2
Installing or Reinstalling Oracle XML DB from Scratch............................................................ A-2
Installing a New Oracle XML DB with DBCA......................................................................... A-2
Dynamic Protocol Registration Registers FTP and HTTP Services with Local Listener.... A-3
Installing a New Oracle XML DB Manually Without DBCA................................................. A-4
Reinstalling Oracle XML DB....................................................................................................... A-4
Upgrading an Existing Oracle XML DB Installation................................................................... A-5
Upgrading XML DB From Release 2 (9.2.0.1) to Release 2 (9.2.0.2) ........................................... A-5
Migrating Data From Release 2 (9.2.0.1) to Release 2 (9.2.0.2) ............................................... A-6
Con guring Oracle XML DB............................................................................................................ A-9
xxiv
Oracle XML DB Con guration File, xdbcon g.xml ..................................................................... A-9
Top Level Tag <xdbconfig> ........................................................................................................ A-9
<sysconfig>................................................................................................................................. A-10
<userconfig>............................................................................................................................... A-10
<protocolconfig>........................................................................................................................ A-10
<httpconfig>............................................................................................................................... A-10
Oracle XML DB Con guration Example..................................................................................... A-11
Oracle XML DB Con guration API.............................................................................................. A-14
Get Configuration, cfg_get()..................................................................................................... A-14
Update Configuration, cfg_update()....................................................................................... A-14
Refresh Configuration, cfg_refresh() ...................................................................................... A-15
B XML Schema Primer
Introducing XML Schema ................................................................................................................. B-2
Purchase Order Schema, po.xsd................................................................................................. B-4
XML Schema Components................................................................................................................ B-6
Complex Type Definitions, Element and Attribute Declarations.......................................... B-6
Naming Conflicts....................................................................................................................... B-12
Simple Types..................................................................................................................................... B-13
List Types.................................................................................................................................... B-17
Union Types ............................................................................................................................... B-19
Anonymous Type De nitions ....................................................................................................... B-20
Element Content............................................................................................................................... B-21
Complex Types from Simple Types........................................................................................ B-21
Mixed Content............................................................................................................................ B-22
Empty Content ........................................................................................................................... B-23
AnyType...................................................................................................................................... B-24
Annotations....................................................................................................................................... B-25
Building Content Models............................................................................................................... B-26
Attribute Groups.............................................................................................................................. B-29
Nil Values .......................................................................................................................................... B-31
How DTDs and XML Schema Differ ........................................................................................... B-31
DTD Limitations ........................................................................................................................ B-33
XML Schema Features Compared to DTD Features............................................................. B-34
Converting Existing DTDs to XML Schema?......................................................................... B-37
xxv
XML Schema Example, PurchaseOrder.xsd................................................................................. B-37
C XPath and Namespace Primer
Introducing the W3C XML Path Language (XPath) 1.0 Recommendation.............................. C-2
The XPath Expression ........................................................................................................................ C-3
Evaluating Expressions with Respect to a Context ................................................................. C-3
XPath Expressions Often Occur in XML Attributes ................................................................ C-4
Location Paths...................................................................................................................................... C-5
Location Path Syntax Abbreviations.......................................................................................... C-5
Location Path Examples Using Unabbreviated Syntax .......................................................... C-5
Location Path Examples Using Abbreviated Syntax............................................................... C-7
Relative and Absolute Location Paths....................................................................................... C-9
Location Path Syntax Summary .............................................................................................. C-10
XPath 1.0 Data Model...................................................................................................................... C-10
Nodes........................................................................................................................................... C-11
Introducing the W3C XML Path Language (XPath) 2.0 Working Draft ................................ C-17
XPath 2.0 Expressions ............................................................................................................... C-17
Introducing the W3C Namespaces in XML Recommendation............................................... C-18
What Is a Namespace? .............................................................................................................. C-19
Qualified Names........................................................................................................................ C-21
Using Qualified Names ............................................................................................................ C-21
Namespace Constraint: Prefix Declared ................................................................................ C-22
Applying Namespaces to Elements and Attributes ............................................................. C-23
Namespace Scoping .................................................................................................................. C-23
Namespace Defaulting.............................................................................................................. C-24
Uniqueness of Attributes.......................................................................................................... C-25
Conformance of XML Documents .......................................................................................... C-26
Introducing the W3C XML Information Set............................................................................... C-26
Namespaces................................................................................................................................ C-27
End-of-Line Handling............................................................................................................... C-28
Base URIs .................................................................................................................................... C-28
Unknown and No Value........................................................................................................... C-29
Synthetic Infosets....................................................................................................................... C-29
xxvi
D XSLT Primer
Introducing XSL................................................................................................................................. D-2
The W3C XSL Transformation Recommendation Version 1.0.............................................. D-2
Namespaces in XML.................................................................................................................... D-4
XSL Stylesheet Architecture....................................................................................................... D-4
XSL Transformation (XSLT) ............................................................................................................. D-5
XML Path Language (Xpath)............................................................................................................ D-5
CSS Versus XSL.................................................................................................................................. D-5
XSL Stylesheet Example, PurchaseOrder.xsl ................................................................................ D-6
E Java DOM API for XMLType, Resource API for Java: Quick Reference
Java DOM API For XMLType ........................................................................................................... E-2
Non-Supported Java Methods .................................................................................................... E-2
Oracle XML DB Resource API for Java........................................................................................... E-6
F Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick
Reference
XMLType API....................................................................................................................................... F-2
PL/SQL DOM API for XMLType (DBMS_XMLDOM) ............................................................... F-6
PL/SQL Parser for XMLType (DBMS_XMLPARSER)................................................................ F-14
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR) ....................................... F-15
DBMS_XMLSCHEMA..................................................................................................................... F-16
Oracle XML DB XML Schema Catalog Views............................................................................. F-19
Resource API for PL/SQL (DBMS_XDB) ..................................................................................... F-20
DBMS_XMLGEN.............................................................................................................................. F-23
RESOURCE_VIEW, PATH_VIEW................................................................................................. F-24
DBMS_XDB_VERSION.................................................................................................................. F-25
DBMS_XDBT..................................................................................................................................... F-27
G Example Setup scripts. Oracle XML DB - Supplied XML Schemas
Example Setup Scripts ...................................................................................................................... G-2
Chapter 3 Examples Set Up Script: Creating User and Directory ........................................ G-2
Chapter 3 Examples Set Up Script: Granting Privileges, Creating Table... ......................... G-3
Chapter 3 Examples Script: invoice.xml................................................................................... G-8
xxvii
Chapter 3 Examples Script: PurchaseOrder.xml..................................................................... G-9
Chapter 3 Examples Script: FTP Script................................................................................... G-10
Chapter 3 Examples Script: Configuring FTP and HTTP Ports.......................................... G-11
RESOURCE_VIEW and PATH_VIEW Database and XML Schema...................................... G-12
Resource View Definition and Structure................................................................................ G-12
PATH_VIW Definition and Structure .................................................................................... G-12
XDBResource.xsd: XML Schema for Representing Oracle XML DB Resources ................. G-12
XDBResource.xsd...................................................................................................................... G-12
acl.xsd: XML Schema for Representing Oracle XML DB ACLs.............................................. G-15
ACL Representation XML Schema, acl.xsd ........................................................................... G-15
acl.xsd.......................................................................................................................................... G-15
xdbcon g.xsd: XML Schema for Con guring Oracle XML DB.............................................. G-18
xdbconfig.xsd............................................................................................................................. G-18
Glossary
Index
xxviii
xxix
Send Us Your Comments
Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2)
Part No. A96620-02
Oracle Corporation welcomes your comments and suggestions on the quality and usefulness of this
document. Your input is an important part of the information used for revision.
I Did you nd any errors?
I Is the information clearly presented?
I Do you need more information? If so, where?
I Are the examples correct? Do you need more examples?
I What features did you like most?
If you nd any errors or have any other suggestions for improvement, please indicate the document
title and part number, and the chapter, section, and page number (if available). You can send com-
ments to us in the following ways:
I Electronic mail: [email protected]
I FAX: (650) 506-7227 Attn: Server Technologies Documentation Manager
I Postal service:
Oracle Corporation
Server Technologies Documentation
500 Oracle Parkway, Mailstop 4op11
Redwood Shores, CA 94065
USA
If you would like a reply, please give your name, address, telephone number, and (optionally) elec-
tronic mail address.
If you have problems with the software, please contact your local Oracle Support Services.
xxx
xxxi
Preface
This manual describes Oracle XML DB, the Oracle9i XML database. It describes
howXML data can be stored, generated, manipulated, managed, and queried in the
database using Oracle XML DB.
After introducing you to the heart of Oracle XML DB , namely the XMLType
framework and Oracle XML DB Repository, the manual provides a brief
introduction to design criteria to consider when planning your Oracle XML DB
application. It provides examples of how and where you can use Oracle XML DB.
The manual then describes ways you can store and retrieve XML data using Oracle
XML DB, APIs for manipulating XMLType data, and ways you can view, generate,
transform, and search on existing XML data. The remainder of the manual discusses
how to use Oracle XML Repository, including versioning and security, how to
access and manipulate Repository resources using protocols, SQL, PL/SQL, or Java,
and how to manage your Oracle XML DB application using Oracle Enterprise
Manager. It also introduces you to XML messaging and Advanced Queueing
XMLType support.
The Preface contains the following sections:
I Audience
I Organization
I Related Documentation
I Conventions
I Documentation Accessibility
xxxii
Audience
This manual is intended for developers building XML applications on Oracle9i
database.
Prerequisite Knowledge
An understanding of XML, XML Schema, XPath, and XSL is helpful when using
this manual.
Many examples provided here are in SQL, Java, or PL/SQL, hence, a working
knowledge of one or more of these languages is presumed.
Organization
This document contains the following parts, chapters, and appendixes:
PART I. Introducing Oracle XML DB
Introduces you to the Oracle XML DB components and architecture, including
XMLType and the Repository. It discusses some basic design issues and provides a
comprehensive set of examples of where and how you can use Oracle XML DB.
Chapter 1, "Introducing Oracle XML DB"
Introduces you to the Oracle XML DB components and architecture. It includes a
description of the benets of using Oracle XML DB, the key features, standards
supported, and requirements for running Oracle XML DB. It lists Oracle XML
DB-related terms used throughout the manual.
Chapter 2, "Getting Started with Oracle XML DB"
Describes how to install Oracle XML DB, compatibility and migration, and some
preliminary application planning issues.
Chapter 3, "Using Oracle XML DB"
Introduces you to where and how you can use Oracle XML DB. It provides
examples of storing, accessing, updating, and validating your XML data using
Oracle XML DB.
PART II. Storing and Retrieving XML Data
Describes the ways you can store, retrieve, validate, and transform XML data using
Oracle9i database native XMLType API.
xxxiii
Chapter 4, "Using XMLType"
Describes how to create XMLType tables and manipulate and query XML data for
non-schema-based XMLType tables and columns.
Chapter 5, "Structured Mapping of XMLType"
Describes how to use Oracle XML DB mapping from SQL to XML and back,
provides an overview of how you must register your XML schema, how you can
either use Oracle XML DBs default mapping or specify your own mapping. It also
describes how to use Ordered Collections in Tables (OCTs) in Oracle XML DB.
Chapter 6, "Transforming and Validating XMLType Data"
Describes how you can use SQL functions to transform XML data stored in the
database and being retrieved or generated from the database. It also describes how
you can use SQL functions to validate XML data being input into the database.
Chapter 7, "Searching XML Data with Oracle Text"
Describes how you can create an Oracle Text index on DBUriType or Oracle XML
DB UriType columns and search XML data using Oracle Texts CONTAINS()
function and XMLTypes existsNode() function. It includes how to use
CTXXPATH index for XPath querying of XML data.
PART III. Using XMLType APIs to Manipulate XML Data
Describes the PL/SQL and Java XMLType APIs and how to use them.
Chapter 8, "PL/SQL API for XMLType"
Introduces the PL/SQL DOM API for XMLType, PL/SQL Parser API for XMLType,
and PL/SQL XSLT Processor API for XMLType. It includes examples and calling
sequence diagrams.
Chapter 9, "Java API for XMLType"
Describes how to use the Java (JDBC) API for XMLType. It includes examples and
calling sequence diagrams.
PART IV. Viewing Existing Data as XML
Chapter 10, "Generating XML Data from the Database"
Discusses SQLX, Oracle SQLX extension functions, and SQL functions for
generating XML. SQLX functions include XMLElement()and XMLForest().
xxxiv
Oracle SQLX extension functions include XMLColAttValue(). SQL functions
include SYS_XMLGEN(), XMLSEQUENCE(), and SYS_XMLAGG(). It also describes
how to use DBMS_XMLGEN, XSQL Pages Publishing Framework, and XML SQL
Utility (XSU) to generate XML data from data stored in the database.
Chapter 11, "XMLType Views"
Describes how to create XMLType views based on XML generation functions, object
types, or transforming XMLType tables. It also discusses how to manipulate XML
data in XMLType views.
Chapter 12, "Creating and Accessing Data Through URLs"
Introduces you to how Oracle9i database works with URIs and URLs. It describes
how to use UriTypes and associated sub-types: DBUriType, HttpUriType, and
XDBUriType to create and access database data using URLs. It also describes how
to create instances of UriType using the UriFactory package, how to use SYS_
DBURIGEN() SQL function, and how to turn a URL into a database query using
DBUri Servlet.
PART V. Oracle XML DB Repository: Foldering, Security, and Protocols
Describes Oracle XML DB Repository, the concepts behind it, how to use
Versioning, ACL security, the Protocol Server, and the various associated Oracle
XML DB Resource APIs.
Chapter 13, "Oracle XML DB Foldering"
Describes hierarchical indexing and foldering. Introduces you to the various Oracle
XML DB Repository components such as Oracle XML DB Resource View API,
Versioning, Oracle XML DB Resource API for PL/SQL and Java.
Chapter 14, "Oracle XML DB Versioning"
Describes how to create a version-controlled Oracle XML DB resource (VCR) and
how to access and update a VCR.
Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
Describes how you can use SQL to access data stored in Oracle XML DB Repository
using Oracle XML DB Resource View API. This chapter also compares the
functionality of the other Oracle XML DB Resource APIs.
xxxv
Chapter 16, "Oracle XML DB Resource API for PL/SQL (DBMS_XDB)"
Describes DBMS_Oracle XML DB and the Oracle XML DB Resource API for
PL/SQL.
Chapter 17, "Oracle XML DB Resource API for Java"
Describes Oracle XML DB Resource API for Java/JNDI and how to use it to access
Oracle XMl DB Repository data.
Chapter 18, "Oracle XML DB Resource Security"
Describes how to use Oracle XML DB resources and ACL security, how to share
ACL, and how to retrieve ACL information.
Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
Introduces Oracle XML DB Protocol Server and how to use FTP, HTTP, and
WebDAV with Oracle XML DB.
Chapter 20, "Writing Oracle XML DB Applications in Java"
Introduces you to writing Oracle XML DB applications in Java. It describes which
Java APIs are available inside and outside the database, tips for writing Oracle XML
DB HTTP servlets, which parameters to use to congure servlets in the
conguration le /xdbconfig.xml, and HTTP request processing.
PART VI. Oracle Tools That Support Oracle XML DB Development
Includes chapters that describe the tools you can use to build and manage your
Oracle XML DB application.
Chapter 21, "Managing Oracle XML DB Using Oracle Enterprise Manager"
Describes how you can use Oracle Enterprise Manager to register your XML
schema; create resources, XMLType tables, views, and columns; manage ACL
security, congure Oracle XML DB; and create function-based indexes.
Chapter 22, "Loading XML Data into Oracle XML DB"
Describes ways you can load XMLType data using SQL*Loader.
Chapter 23, "Importing and Exporting XMLType Tables"
Describes the IMPORT/EXPORT utility support for loading XMLType tables.
xxxvi
PART VII. XML Data Exchange Using Advanced Queueing
Describes Oracle Advanced Queueing support for XML and XMLType messaging.
Chapter 24, "Exchanging XML Data Using Advanced Queueing (AQ) and
Oracle Streams"
Introduces how you can use Advancd Queueing to exchange XML data. It briey
describes Oracle Streams, Internet Data Access Presentation (IDAP), using AQ XML
Servlet to enquue and dequeue messages, using IDAP, and AQ XML schemas.
PART VIII. Oracle XML DB Case Studies
Describes two XML DB-based applications.
Chapter 25, "Oracle XML DB Case Study: Web Services Retrieve and Display
XML Documents"
Provides the calling sequence and code for building an XML DB Web Services based
purchase order application.
Chapter 26, "Oracle XML DB Basic Demo"
Provides many examples and illustrations of ways to store, access, and manipulate
purchase order XML document using XML DB.
Appendix A, "Installing and Conguring Oracle XML DB"
Describes how to install and congure Oracle XML DB.
Appendix B, "XML Schema Primer"
Provides a summary of the W3C XML Schema Recommendation.
Appendix C, "XPath and Namespace Primer"
Provides an introduction to W3C XPath Recommendation, Namespace
Recommendation, and Information Sets.
Appendix D, "XSLT Primer"
Provides an introduction to the W3C XSL/XSLT Recommendation.
Appendix E, "Java DOM API for XMLType, Resource API for Java: Quick
Reference"
Provides a quick reference for the Oracle XML DB Java APIs.
xxxvii
Appendix F, "Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL
APIs: Quick Reference"
Provides a quick reference for the Oracle XML DB PL/SQL APIs.
Appendix G, "Example Setup scripts. Oracle XML DB - Supplied XML
Schemas"
Provides a description of the setup scripts used for the examples in Chapter 3. It
also descibes the RESOURCE_VIEW and PATH_VIEW structures and lists the
Oracle XML DB- supplied sample resource XML schema.
Glossary
Related Documentation
For more information, see these Oracle resources:
I Oracle9i Database New Features for information about the differences between
Oracle9i and the Oracle9i Enterprise Edition and the available features and
options. This book also describes features new to Oracle9i Release 2 (9.2).
I Oracle9i XML API Reference - XDK and Oracle XML DB
I Oracle9i XML Developers Kits Guide - XDK
I Oracle9i XML Case Studies and Applications (contains XDK examples, no
Oracle XML DB examples for this release)
I Oracle9i Database Error Messages
I Oracle Text Application Developers Guide
I Oracle Text Reference
I Oracle9i Database Concepts.
I Oracle9i Java Developers Guide
I Oracle9i Application Developers Guide - Fundamentals
I Oracle9i Application Developers Guide - Advanced Queuing
I Oracle9i Supplied PL/SQL Packages and Types Reference
Some of the examples in this book use the sample schemas of the seed database,
which is installed by default when you install Oracle. Refer to Oracle9i Sample
Schemas for information on how these schemas were created and how you can use
them yourself.
xxxviii
In North America, printed documentation is available for sale in the Oracle Store at
http://oraclestore.oracle.com/
Customers in Europe, the Middle East, and Africa (EMEA) can purchase
documentation from
http://www.oraclebookshop.com/
Other customers can contact their Oracle representative to purchase printed
documentation.
To download free release notes, installation documentation, white papers, or other
collateral, please visit the Oracle Technology Network (OTN). You must register
online before using OTN; registration is free and can be done at
http://otn.oracle.com/admin/account/membership.html
If you already have a username and password for OTN, then you can go directly to
the documentation section of the OTN Web site at
http://otn.oracle.com/docs/index.htm
To access the database documentation search engine directly, please visit
http://tahiti.oracle.com
Conventions
This section describes the conventions used in the text and code examples of this
documentation set. It describes:
I Conventions in Text
I Conventions in Code Examples
Conventions in Text
We use various conventions in text to help you more quickly identify special terms.
The following table describes those conventions and provides examples of their use.
xxxix
Conventions in Code Examples
Code examples illustrate SQL, PL/SQL, SQL*Plus, or other command-line
statements. They are displayed in a monospace (xed-width) font and separated
from normal text as shown in this example:
Convention Meaning Example
Bold Bold typeface indicates terms that are
dened in the text or terms that appear in
a glossary, or both.
When you specify this clause, you create an
index-organized table.
Italics Italic typeface indicates book titles or
emphasis.
Oracle9i Database Concepts
Ensure that the recovery catalog and target
database do not reside on the same disk.
UPPERCASE
monospace
(fixed-width)
font
Uppercase monospace typeface indicates
elements supplied by the system. Such
elements include parameters, privileges,
datatypes, RMAN keywords, SQL
keywords, SQL*Plus or utility commands,
packages and methods, as well as
system-supplied column names, database
objects and structures, usernames, and
roles.
You can specify this clause only for a NUMBER
column.
You can back up the database by using the
BACKUP command.
Query the TABLE_NAME column in the USER_
TABLES data dictionary view.
Use the DBMS_STATS.GENERATE_STATS
procedure.
lowercase
monospace
(fixed-width)
font
Lowercase monospace typeface indicates
executables, lenames, directory names,
and sample user-supplied elements. Such
elements include computer and database
names, net service names, and connect
identiers, as well as user-supplied
database objects and structures, column
names, packages and classes, usernames
and roles, program units, and parameter
values.
Note: Some programmatic elements use a
mixture of UPPERCASE and lowercase.
Enter these elements as shown.
Enter sqlplus to open SQL*Plus.
The password is specied in the orapwd le.
Back up the datales and control les in the
/disk1/oracle/dbs directory.
The department_id, department_name,
and location_id columns are in the
hr.departments table.
Set the QUERY_REWRITE_ENABLED
initialization parameter to true.
Connect as oe user.
The JRepUtil class implements these
methods.
lowercase
italic
monospace
(fixed-width)
font
Lowercase italic monospace font
represents placeholders or variables.
You can specify the parallel_clause.
Run Uold_release.SQL where old_
release refers to the release you installed
prior to upgrading.
xl
SELECT username FROM dba_users WHERE username = MIGRATE;
The following table describes typographic conventions used in code examples and
provides examples of their use.
Convention Meaning Example
[ ] Brackets enclose one or more optional
items. Do not enter the brackets.
DECIMAL (digits [ , precision ])
{ } Braces enclose two or more items, one of
which is required. Do not enter the braces.
{ENABLE | DISABLE}
| A vertical bar represents a choice of two
or more options within brackets or braces.
Enter one of the options. Do not enter the
vertical bar.
{ENABLE | DISABLE}
[COMPRESS | NOCOMPRESS]
... Horizontal ellipsis points indicate either:
I That we have omitted parts of the
code that are not directly related to
the example
I That you can repeat a portion of the
code
CREATE TABLE... AS subquery;
SELECT col1, col2,... , coln FROM
employees;
.
.
.
Vertical ellipsis points indicate that we
have omitted several lines of code not
directly related to the example.
Other notation You must enter symbols other than
brackets, braces, vertical bars, and ellipsis
points as shown.
acctbal NUMBER(11,2);
acct CONSTANT NUMBER(4) := 3;
Italics Italicized text indicates placeholders or
variables for which you must supply
particular values.
CONNECT SYSTEM/system_password
DB_NAME = database_name
UPPERCASE Uppercase typeface indicates elements
supplied by the system. We show these
terms in uppercase in order to distinguish
themfromterms you dene. Unless terms
appear in brackets, enter them in the
order and with the spelling shown.
However, because these terms are not
case sensitive, you can enter them in
lowercase.
SELECT last_name, employee_id FROM
employees;
SELECT * FROM USER_TABLES;
DROP TABLE hr.employees;
xli
Documentation Accessibility
Our goal is to make Oracle products, services, and supporting documentation
accessible, with good usability, to the disabled community. To that end, our
documentation includes features that make information available to users of
assistive technology. This documentation is available in HTML format, and contains
markup to facilitate access by the disabled community. Standards will continue to
evolve over time, and Oracle Corporation is actively engaged with other
market-leading technology vendors to address technical obstacles so that our
documentation can be accessible to all of our customers. For additional information,
visit the Oracle Accessibility Program Web site at
http://www.oracle.com/accessibility/
Accessibility of Code Examples in Documentation JAWS, a Windows screen
reader, may not always correctly read the code examples in this document. The
conventions for writing code require that closing braces should appear on an
otherwise empty line; however, JAWS may not always read a line of text that
consists solely of a bracket or brace.
Accessibility of Links to External Web Sites in Documentation This
documentation may contain links to Web sites of other companies or organizations
that Oracle Corporation does not own or control. Oracle Corporation neither
evaluates nor makes any representations regarding the accessibility of these Web
sites.
lowercase Lowercase typeface indicates
programmatic elements that you supply.
For example, lowercase indicates names
of tables, columns, or les.
Note: Some programmatic elements use a
mixture of UPPERCASE and lowercase.
Enter these elements as shown.
SELECT last_name, employee_id FROM
employees;
sqlplus hr/hr
CREATE USER mjones IDENTIFIED BY ty3MU9;
Convention Meaning Example
xlii
xliii
Whats New In Oracle XML DB?
This chapter describes the new features, enhancements, APIs, and product
integration added through Oracle XML DB as a part of Oracle9i Release 2 (9.2.0.2)
and Oracle9i Release 2 (9.2.0.1).
Oracle XML DB: Oracle9i Release 2 (9.2.0.2): Enhancements
This section summarizes the Oracle XML DB enhancements provided with patch
release, Oracle9i Release 2 (9.2.0.2).
Exporting and Importing XML Data
Oracle9i Release 2 (9.2.0.2) provides enhanced IMPORT/EXPORT utility support to
assist in loading XML data into Oracle XML DB. See Chapter 23, "Importing and
Exporting XMLType Tables".
XMLAgg() SQLX Function
XMLAgg() now supports the ORDER BY clause. See Chapter 10, "Generating XML
Data from the Database", "XMLAgg() Function".
updateXML() XMLType Function
The updateXML() section has been reworked to include more comprehensive
examples.
See Also: Oracle9i Release Notes, Release 2 (9.2.0.2) available
with your software.
xliv
Globalization Support: Multibyte Characters
Oracle XML DB can handle multibyte characters as long as the client character set is
the same as the database character set.
Updated Oracle XML DB - Supplied XML Schema
The end of Appendix G, "Example Setup scripts. Oracle XML DB - Supplied XML
Schemas" lists the three updated Oracle XML DB - supplied XML schema,
XDBResource.xsd, acl.xsd, and xdbconfig.xsd.
Migrating from Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
Notes have been adding describing how to migrate from Release 2 (9.2.0.1) to
Release 2 (9.2.0.2). See Appendix A, "Installing and Conguring Oracle XML DB".
RESOURCE_VIEW PATH Operator
Further examples and explanation have been added to this section for determining
paths under multiple correlations or specied path name arguments. See
Chapter 15, "RESOURCE_VIEW and PATH_VIEW", "PATH" on page 15-9.
New Configuration Parameters
A new tuning parameter, resource-view-cache-size has been added. When
querying large RESOURCE_VIEWs you can now tune the
resource-view-cache-size parameter in the xdbconfig le. See Chapter 15,
"RESOURCE_VIEW and PATH_VIEW", "Tuning XML DB to Obtain Faster Queries".
HTTP/webDAV parameter default-url-charset has been added. This is the
character set in which an HTTP Protocol Server assumes the incoming URL is
encoded when it is not encoded in UTF-8 or the requests Content-Type eld
Charset parameter. See Chapter 19, "Using FTP, HTTP, and WebDAV Protocols",
Table 193.
PL/SQL DOM API for XMLType: New Methods
Several newDBMS_XMLDOM methods are now supported for the PL/SQL DOM API
for XMLType. See Chapter 8, "PL/SQL API for XMLType". Note that there are a few
methods that have been de-supported in this release.
Java DOM API for XMLType: Desupported Methods
Afewmethods in XDBDocument, XDBNode, and XDBDOMImplementation classes
have been de-supported in this release. See Chapter 9, "Java API for XMLType".
xlv
Highlight Support for XML Documents with INPATH/HASPTH Oracle Text
Operators
You can now highlight XML documents in Oracle Text with the INPATH/HASPATH
query element(s) highlighted and using CTX_DOC.MARKUP or HIGHLIGHT
procedures. See Chapter 7, "Searching XML Data with Oracle Text", "Highlight
Support for INPATH/HASPATH Text Operators" on page 7-49.
Oracle XML DB Case Studies are Provided
See Chapter 25, "Oracle XML DB Case Study: Web Services Retrieve and Display
XML Documents" and Chapter 26, "Oracle XML DB Basic Demo".
Oracle XML DB, Oracle9i Release 2 (9.2.0.1): XMLType Enhancements
XMLType datatype was rst introduced in Oracle9i. This datatype has been
signicantly enhanced in Oracle9i Release 2 (9.2.0.1). This release is also referred to,
in general, as Release 2 (9.2). The following sections describe these enhancements.
XMLType Tables
Datatype XMLType can nowbe used to create tables of XMLType. This gives you the
exibility to store XML either in a column, in a table, or as a whole table, much like
objects.
XMLType Constructors
Additional XMLType constructors have been added. Besides the createXML()
functions, XMLType can now also be constructed using user-dened constructors.
W3C XML Schema Support
Extensive XML schema support has been added in this release to Oracle XML DB.
You can now perform the following:
I Construct an XMLType object based on an XML schema and have it be
continuously validated.
See Also:
http://otn.oracle.com/tech/xml/content.html for the
latest Oracle XML DB updates and notes.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
xlvi
I Create XML schema-based XMLType tables. This feature automatically
creates appropriate storage structures for optimal storage of XML
schema-based documents. Unlike SQL DDL, this process does not require
knowledge of all column data types and their denitions.
I Register annotated XML schema using the DBMS_XMLSCHEMA package, to
share storage and type denitions. Registered XML schema can be shared
across all database users to allow for instance wide common document
denition. The registration process optionally creates default tables. With
XML schema annotation you can specify various objects such as, SQL types,
default storage tables, and so on.
I Pre-parse incoming XML documents and automatically direct them to
default storage tables. This allows protocols such as FTP and WebDAV to
accept structured XML documents and store them in object-relational
tables.
I Automatically validate XML documents or instances against W3C XML
Schema when the XML documents or instances are added to Oracle XML
DB.
I Explicitly validate XML documents and instances against XML schema
using XMLIsSchemaValid() method on XMLType.
I Use datatype -aware extraction of part of an XML document using the
extractValue operator.
SQLX Functions and Oracle Extensions
This release includes support for SQLX operations for generating XML from
existing relational and object relational tables. This is based on ISO-ANSI Working
Draft for XML-Related Specications (SQL/XML) [ISO/IEC 9075 Part 14 and ANSI]
which denes ways in which the database language SQL can be used in conjunction
with XML.
For example, the following functions dened by the SQLX standards body are
supported: XMLElement(), XMLForest(), XMLConcat(), and XMLAgg(). Oracle
XML DB also extends the SQLX operations with functions such as:
XMLColAttVal(), XMLSequence(), SYS_XMLGEN(), and SYS_XMLAGG().
W3C XPath Support for Extraction, Condition Checks, and Updates
Oracle9i Release 1 (9.0.1) provided the extract() and existsNode() functions
on XMLType objects. These allowed XPath-based queries against XML documents.
This release provides additional support as follows:
xlvii
I extract(), existsNode(), and extractValue() now allow for a
namespace-based operation.
I extract(), existsNode(), and extractValue() support the full
XPath function set, including axis operators.
I updateXML() function (new) replaces part of the XMLType DOM by using
XPath as a locator.
ToObject Method
ToObject method allows the caller to convert an XMLType object to a PL/SQL
object type.
XMLType Views
This release supports XMLType-based views. These enable you to view any data in
the database as XML. XMLType views can be XML schema-based or non-XML
schema-based. See Chapter 11, "XMLType Views".
W3C XSLT Support
This release introduces a new function, XMLTransform() that allows for a
database-based transformation of in-memory or on disk XML documents. See
Chapter 6, "Transforming and Validating XMLType Data".
JDBC Support for XMLType
Oracle XML DB allows database clients to bind and dene XMLType. JDBC support
includes a function-rich XMLType class that allows for native (for thick JDBC) XML
functionality support. See Chapter 9, "Java API for XMLType".
C-Based PL/SQL DOM, Parser, and XSLT APIs
This release includes native PL/SQL DOM, Parser, and XSLT APIs integrated in the
database code. These PL/SQL APIs are compatible with the Java-based PLSQL
APIs shipped as part of XDK for PL/SQL with Oracle9i Release 1 (9.0.1) and higher.
See Chapter 8, "PL/SQL API for XMLType".
Oracle XML DB, Oracle9i Release 2 (9.2.0.1): Repository
In this release, Oracle XML DB Repository adds advanced foldering and security
mechanisms to the database. Oracle XML DB Repository is a new feature that
provides a novel le system-like access to all database data. The Repository allows
the following actions:
xlviii
I Viewing the database and its content as a le system containing resources,
typically referred to as les and folders.
I Access and manipulation of resources through path name-based SQL and
Java API.
I Access and manipulation of resources through built-in native Protocol
Servers for FTP, HTTP, and WebDAV.
I ACL-based security for Oracle XML DB resources.
Oracle XML DB Resource API (PL/SQL): DBMS_XDB
DBMS_XDB package provides methods to access and manipulate Oracle XML DB
resources. Chapter 16, "Oracle XML DB Resource API for PL/SQL (DBMS_XDB)".
Oracle XML DB Resource API (JNDI)
This uses JNDI (Java Naming and Directory Interface) to locate resources, and
manage collections. It supports JNDI Service Provider Interface (SPI). This interface
works only inside the database server on the JServer platform. See Chapter 17,
"Oracle XML DB Resource API for Java".
Oracle XML DB Resource View API (SQL)
ResourceView is a public XMLType view that you can use to perform path
name-based queries against all resources in a database instance. This view merges
path-based queries with queries against relational and object-relational tables and
views. See Chapter 15, "RESOURCE_VIEW and PATH_VIEW".
In Release 2 (9.2.0.2) the XDBconfig le includes a tuning parameter,
resource-view-cache-size to allow faster queries. See the end of Chapter 15,
"RESOURCE_VIEW and PATH_VIEW".
Oracle XML DB Versioning: DBMS_XDB_VERSION
DBMS_XDB_VERSION package provides methods to version Oracle XML DB
resources. See Chapter 14, "Oracle XML DB Versioning".
Oracle XML DB ACL Security
Methods that implement ACL-based security are a part of DBMS_XDB package.
They allow you to create high-performance access control lists for any XMLType
object. See Chapter 18, "Oracle XML DB Resource Security".
xlix
Oracle XML DB Protocol Servers
The Protocol Servers provide access to any foldered XMLType row through FTP,
HTTP, and WebDAV. Note that XMLType can manage arbitrary binary data as well
in any le format. See Chapter 19, "Using FTP, HTTP, and WebDAV Protocols".
XDBURIType
URIType now includes a new subtype, XDBURIType, that represents a path name
within Oracle XML DB. See Chapter 12, "Creating and Accessing Data Through
URLs".
Oracle Tools Enhancements for Oracle XML DB
Oracle Enterprise Manager
Oracle Enterprise Manager provides a graphical interface to manage, administer,
and congure Oracle XML DB. See Chapter 21, "Managing Oracle XML DB Using
Oracle Enterprise Manager".
Oracle Text Enhancements
This release offers the following Oracle Text enhancements:
I Columns of type XMLType can now be indexed natively in Oracle9i
database using Oracle Text.
I CONTAINS() is a new function for use as ora:contains in an XPath
query and as part of the existsNode() function.
I CTXXPATH is a newindex type for use with existsNode() to speedup the
performance of XPath searching.
See Chapter 7, "Searching XML Data with Oracle Text".
Oracle Advanced Queuing (AQ) Support
With this release, the Advanced Queueing (AQ) Internet Data Access Presentation
(IDAP) has been enhanced. IDAP facilitates your using AQ over the Internet. You
can now use AQ XML servlet to access Oracle9i AQ using HTTP and SOAP.
Also in this release, IDAP is the Simple Object Access Protocol (SOAP)
implementation for AQ operations. IDAP now denes the XML message structure
used in the body of the SOAP request.
l
You can now use XMLType as the AQ payload type instead of having to embed
XMLType as an attribute in an Oracle object type.
Oracle XDK Support for XMLType
XDK for Java Support
XSQL Servlet and XML SQL Utility (XSU) for Java now support XMLType. Most
methods on XMLType object, such as, getClobVal(), are nowavailable in XSU for
Java.
XDK for PLSQL Support
XML SQL Utility (XSU) for PLSQL now supports XMLType.
See:
I Chapter 24, "Exchanging XML Data Using Advanced Queueing
(AQ) and Oracle Streams"
I Oracle9i Application Developers Guide - Advanced Queuing
See:
I "Generating XML Using XSQL Pages Publishing Framework"
on page 10-52. and "Generating XML Using XML SQL Utility
(XSU)" on page 10-54
I Oracle9i XML Developers Kits Guide - XDK
Part I
Introducing Oracle XML DB
Part I of this manual introduces Oracle XML DB. It contains the following chapters:
I Chapter 1, "Introducing Oracle XML DB"
I Chapter 2, "Getting Started with Oracle XML DB"
I Chapter 3, "Using Oracle XML DB"
Introducing Oracle XML DB 1-1
1
Introducing Oracle XML DB
This chapter introduces you to Oracle XML DB by describing the Oracle XML DB
benets, features, and architecture. This chapter contains the following sections:
I Introducing Oracle XML DB
I Benets of Oracle XML DB
I Key Features of Oracle XML DB
I Oracle XML DB and XML Schema
I Oracle XML DB Architecture
I XMLType Storage Architecture
I Why Use Oracle XML DB?
I Searching XML Data Stored in CLOBs Using Oracle Text
I Building Oracle XML DB XML Messaging Applications with Advanced
Queueing
I Managing Oracle XML DB Applications with Oracle Enterprise Manager
I Requirements for Running Oracle XML DB
I Oracle XML DB Technical Support
I Terminology Used in This Manual
I Oracle XML DB Examples Used in This Manual
Introducing Oracle XML DB
1-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB
This chapter introduces you to Oracle XML DB. It discusses the features available
for building XML applications on the Oracle9i database.
From its beginnings, XML's core characteristics of self-description and dynamic
extensibility have provided the exibility needed to transport messages between
various applications, and loosely couple distributed business processes.
XML is also language-independent and platform-independent. As XML support has
become standard in browsers, application servers, and databases, enterprises have
wished to tie legacy applications to the Web using XML to transform various
proprietary le- and document-exchange templates into XML.
More recently, a new generation of XML standards, such as XML Schema, has
enabled a unied data model that can address both structured data and documents.
XML Schema has emerged as a key innovation in managing document content with
the same rigor as data by enabling documents marked up as XML to move into the
database.
Oracle XML DB is a set of built-in high-performance storage and retrieval
technologies geared to XML. Oracle XML DB fully absorbs the World Wide Web
Consortium (W3C) XML data model into Oracle9i database and provides new
standard access methods for navigating and querying XML. You get all the
advantages of relational database technology and XML technology at the same
time. Oracle XML DB can be used to store, query, update, transform, or otherwise
process XML, while at the same time providing SQL access to the same XML data.
Not a Separate Database Server
Oracle XML DB is not some separate server but rather the name for a distinct group
of technologies related to high-performance XML storage and retrieval that are
available within the familiar Oracle database. Oracle XML DB can also be thought
of as an evolution of the Oracle database that encompasses both SQL and XML data
models in a highly interoperable manner, thus providing native XML support.
You use Oracle XML DB in conjunction with Oracle XML Developers Kit (XDKs).
XDKs provide common development-time utilities that can run in the middle tier in
Oracle9iAS or in Oracle9i database.
See Also: Oracle9i XML Developers Kits Guide - XDK. for more
information about XDK
Benefits of Oracle XML DB
Introducing Oracle XML DB 1-3
Benets of Oracle XML DB
Applications often manage structured data as tables and unstructured data as les
or Large Objects (LOBs). This subjects developers to different paradigms for
managing different kinds of data. Systems channel application-development down
either of the following paths:
I Unstructured. This typically makes document access transparent and table
access complex.
I Structured. This typically makes document access complex and table access
transparent.
Oracle XML DB provides the following benets:
I The ability to store and manage both structured and unstructured data under
the same standard W3C XML data model (XML Schema).
I Complete transparency and interchangeability between the XML and SQL data
views.
I Valuable Repository functionality: foldering, access control, FTP, and WebDAV
protocol support with versioning. This enables applications to retain the le
abstraction when manipulating XML data brought into Oracle. As a result, you
can store XML in the database (rendering it queryable) and at the same time
access it through popular desktop tools.
I Better management of unstructured XML data by supporting
I Piecewise updates
I XML indexing
I Integrated XML text search with Oracle Text
I Multiple views on the data, including relational views for SQL access
I Enforcement of intra- and inter-document relationships in XML documents
I Users today face a performance barrier in storing and retrieving complex XML.
Oracle XML DB provides high performance and scalability for XML operations
with the help of a number of specic optimizations that relate to XML-specic
data-caching and memory management, query optimization on XML, special
hierarchical indexes on the XML Repository, and so on.
I Enables data and documents from disparate systems to be accessed, for
example, through Oracle Gateway and External Tables, and combined into a
Key Features of Oracle XML DB
1-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
standard data model. This integrative aspect reduces the complexity of
developing applications that must deal with data from different stores.
Key Features of Oracle XML DB
Table 11 describes Oracle XML DB features. This list includes XML features
available since Oracle9i Release 1 (9.0.1).
Table 11 Oracle XML DB Features
Oracle XML DB Features Description
XMLType The native datatype XMLType helps store and manipulate XML. Multiple storage
options (Character Large Object (CLOB), structured XML) are available with
XMLType, and administrators can choose a storage that meets their requirements.
CLOB storage is an un-decomposed storage that is like an image of the original
XML.
The native structured XML storage is a shredded decomposition of XML into
underlying object-relational structures (automatically created and managed by
Oracle) for better SQL queriability.
With XMLType, you can perform SQL operations such as:
I Queries, OLAP function invocations, and so on, on XML data, as well as XML
operations
I XPath searches, XSL transformations, and so on, on SQL data
You can build regular SQL indexes or Oracle Text indexes on XMLType for high
performance for a very broad spectrum of applications. See Chapter 4, "Using
XMLType".
DOM delity The Document Object Model (DOM) is a standard programmatic representation of
XML documents. Oracle XML DB can shred XML documents while storing them
(structured XML Storage) in a manner that maintains DOM delity: the DOM that
you store is the DOM that you get back. DOM delity means that your programs
can manipulate exactly the same XML data that you got, and the process of storage
does not affect the order of elements, the presence of namespaces and so on. DOM
delity does not, however, imply maintenance of whitespaces, and the like; if you
want to preserve the exact layout of XML including whitespaces you can use
CLOB storage. See Chapter 5, "Structured Mapping of XMLType".
Document delity For applications that need to store XML while maintaining complete delity to the
original, including whitespace characters, the CLOB storage option is available.
Key Features of Oracle XML DB
Introducing Oracle XML DB 1-5
XML Schema Oracle XML DB gives you the ability to constrain XML documents to XML
schemas. You can create tables and types automatically given a W3C standard
XML Schema. You can also enforce that an XML document being stored is
schema-valid. This means you have a standard data model for all your data
(structured and unstructured) and can use the database to enforce this data model.
See Chapter 5, "Structured Mapping of XMLType".
XMLSchemastorage
with DOM delity
Use structured storage (object-relational) columns, VARRAYs, nested tables, and
LOBs to store any element or element-subtree in your XML schema and still
maintain DOM delity (DOM stored == DOM retrieved). See Chapter 5,
"Structured Mapping of XMLType".
Note: If you choose CLOB storage option, available with XMLType since Oracle9i
Release 1 (9.0.1), you can keep whitespaces.
XML Schema
validation
While storing XML documents in Oracle XML DB you can optionally ensure that
their structure complies (is valid against) with specic XML Schema. See
Chapter 6, "Transforming and Validating XMLType Data".
XML piecewise
update
You can use XPath to specify individual elements and attributes of your document
during updates, without rewriting the entire document. This is more efcient,
especially for large XML documents. See Chapter 5, "Structured Mapping of
XMLType".
XPath search You can use XPath syntax (embedded in an SQL statement or as part of an HTTP
request) to query XML content in the database. See Chapter 4, "Using XMLType"
and Chapter 7, "Searching XML Data with Oracle Text".
XML indexes Use XPath to specify parts of your document to create indexes for XPath searches.
Enables fast access to XML documents. See Chapter 4, "Using XMLType".
SQLX operators New SQL member functions tracking the emerging ANSI SQLX standard, such as,
XMLElement (to create XML elements on the y) and others, to make XML
queries and on-the-y XML generation easy. These render SQL and XML
metaphors interoperable.See Chapter 10, "Generating XML Data from the
Database".
XSL transformations
for XMLType
Use XSLT to transform XML documents through an SQL operator.
Database-resident, high-performance XSL transformations. See Chapter 6,
"Transforming and Validating XMLType Data" and Appendix D, "XSLT Primer".
Lazy XML loading Oracle XML DB provides a virtual DOM; it only loads rows of data as they are
requested, throwing away previously referenced sections of the document if
memory usage grows too large. You can use this to get high scalability when many
concurrent users are dealing with large XML documents. The virtual DOM is
available through Java interfaces running in a Java execution environment at the
client or with the server. See Chapter 8, "PL/SQL API for XMLType".
Table 11 Oracle XML DB Features (Cont.)
Oracle XML DB Features Description
Key Features of Oracle XML DB
1-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XML views You can create XML views to create permanent aggregations of various XML
document fragments or relational tables. You can also create views over
heterogeneous data sources using Oracle Gateways. See Chapter 11, "XMLType
Views".
PL/SQL and OCI
interfaces
Use DOM and other APIs for accessing and manipulating XML data. You can get
static and dynamic access to XML. See Chapter 8, "PL/SQL API for XMLType".
Schema caching Structural information (such as element tags, datatypes, and storage location) is
kept in a special schema cache, to minimize access time and storage costs. See
Chapter 5, "Structured Mapping of XMLType".
XML generation SQL operators such as SYS_XMLGEN and SYS_XMLAGG provide native,
high-performance generation of XML from SQL queries. New operators such as
XMLElement(), to create XML tables and elements on the y, make XML
generation more exible. See Chapter 10, "Generating XML Data from the
Database". These operators track the emerging ANSI SQLX standard.
Oracle XML DB
Repository
A built-in XML Repository. This Repository can be used for foldering whereby you
can view XML content stored in Oracle XML DB as a hierarchy of directory-like
folders. See Chapter 13, "Oracle XML DB Foldering".
I The repository supports access control lists (ACLs) for any XMLType object, and
lets you dene your own privileges in addition to providing certain
system-dened ones. See Chapter 18, "Oracle XML DB Resource Security".
I You can use the Repository to view XML content as navigable directories
through a number of popular clients and desktop tools. Items managed by the
repository are called resources.
I Hierarchical indexing is enabled on the Repository. Oracle XML DB provides
a special hierarchical index to speed folder search. Additionally, you can
automatically map hierarchical data in relational tables into folders (where the
hierarchy is dened by existing relational information, such as with CONNECT
BY).
SQL Repository
search
You can search the XML Repository using SQL. Operators like UNDER_PATHand
DEPTH allow applications to search folders, XML le metadata (such as owner
and creation date), and XML le content. See Chapter 15, "RESOURCE_VIEW and
PATH_VIEW".
WebDav, HTTP, and
FTP access
You can access any foldered XMLType row using WebDAV and FTP. Users
manipulating XML data in the Oracle9i database can use the HTTP API. See
Chapter 19, "Using FTP, HTTP, and WebDAV Protocols".
Versioning Oracle XML DB provides versioning and version-management capabilities over
resources managed by the XML Repository. See Chapter 14, "Oracle XML DB
Versioning".
Table 11 Oracle XML DB Features (Cont.)
Oracle XML DB Features Description
Oracle XML DB Architecture
Introducing Oracle XML DB 1-7
Oracle XML DB and XML Schema
XML schema unies both document and data modeling. In Oracle XML DB, you can
create tables and types automatically using XML Schema. In short, this means that
you can develop and use a standard data model for all your data, structured,
unstructured, and pseudo/semi-structured. You can now use Oracle9i database to
enforce this data model for all your data.
You can create XML schema-based XMLType tables and columns and optionally
specify, for example, that they:
I Conform to pre-registered XML schema
I Are stored in structured storage format specied by the XML schema
maintaining DOM delity
You can also choose to wrap existing relational and object-relational data into XML
format using XMLType views.
You can store an XMLType object as an XML schema-based object or a non-XML
schema-based object:
I XML Schema-based objects. These are stored in Oracle XML DB as LOBs or in
structured storage (object-relationally) in tables, columns, or views.
I Non-XML schema-based objects. These are stored in Oracle XML DB as Large
Objects (LOBs).
You can map from XML instances to structured or LOB storage. The mapping can
be specied in XML schema and the XML schema must be registered in Oracle XML
DB. This is a required step before storing XML schema-based instance documents.
Once registered, the XML schema can be referenced using its URL.
Oracle XML DB Architecture
Figure 11 shows the Oracle XML DB architecture. The two main features in Oracle
XML DB architecture are:
I The XMLType tables and views storage, which includes storage of XMLType
tables and views
I The Oracle XML DB Repository, also referred to in this manual as "XML
Repository" or "Repository"
The section following Figure 11 describes the architecture in more detail.
Oracle XML DB Architecture
1-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 11 Oracle XML DB Architecture: XMLType Storage and Repository
AQ and
Oracle9i
Streams
Access
Gateways
to external
sources
XMLType Tables
and Views
Oracle XML DB
Repository
Oracle XML DB
Oracle9i Database
Direct
HTTP
Access
Oracle
Net
Services
Access
Browser
or other
UI
WebDAV
Access
FTP
Access
Browser
JDBC
Application
Desktop
Tool
FTP
Tool
XML Services
XML Validation
XML Transformation
XML Schema
Registration
Create Tables
Store in LOB or O-R
Insert, Delete, Update
XMLType tables
Indexing
Retrieve / Generate
XML Using
XMLType APIs
SQL
Java
PL/SQL
XML Services
Versioning
ACL Security
Foldering
Retrieve XML Using
Resource APIs
SQL
Java / JNDI
PL / SQL
Oracle XML DB Architecture
Introducing Oracle XML DB 1-9
XMLType Tables and Views Storage
"XMLType tables and views storage" in Oracle XML DB provides a native XML
storage and retrieval capability in the database, strongly integrated with SQL.
XML data, including XML schema denition les can be stored in LOBs, in
structured storage (object-relationally), or using any hybrid combining both LOBs
and structured storage. See Chapter 3, "Using Oracle XML DB" and Chapter 4,
"Using XMLType".
Supported XML Access APIs
I PL/SQL and Java APIs for XMLType. Use these APIs to:
I Create XMLType tables, columns, and views
I Query and retrieve XML data
I SQL functions, such as XMLElement() and XMLForest(). Applications can
query XML data in the database using standard SQL and SQL member
functions that comply with the SQLX standard.
Supported XML Services
In Oracle XML DB, besides accessing or generating XML data, you can also perform
various operations on the data:
I PL/SQL and J ava API s for XMLType. These enable you to manipulate
XMLType data, such as update, delete, and insert XML data.
I I ndexing. This speeds up data searches where XPath features are not critical. It
is most suited for XML data stored in LOBs.
I Transforming XML data to other XML, HTML, and so on, using XMLTypes
XMLTransform() function, XDKs XSLT Processors, or XSQL Servlet Pages
Publishing Framework. See Chapter 6, "Transforming and Validating XMLType
Data" and Chapter 10, "Generating XML Data from the Database".
I Validating XML data. Validates XML data against XML schema when the XML
data is stored in the database.
See Also: Part IV. Viewing Existing Data as XML.
See Also: "XMLType Storage Architecture" on page 1-11.
Oracle XML DB Architecture
1-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Repository
Oracle XML DB Repository (XML Repository or Repository) is an XML data
repository in the Oracle9i database optimized for handling XML data. At the heart
of Oracle XML DB Repository is the Oracle XML DB foldering module.
The contents of Oracle XML DB Repository are referred to as resources. These can be
either containers (or directories / folders) or les. All resources are identied by a
path name and have a (extensible) set of (metadata) properties such as Owner,
CreationDate, and so on, in addition to the actual contents dened by the user.
Supported XML Access APIs
Figure 11 lists the following Oracle XML DB supported XML access and
manipulation APIs:
I Oracle XML DB Resource API s. Use these APIs to access the foldered XMLType
and other data, that is, data accessed using the Oracle XML DB hierarchically
indexed Repository. The APIs are available in the following languages:
SQL (through the RESOURCE_VIEW and PATH_VIEW APIs)
PL/SQL (DBMS_XDB) API
Java API
I Oracle XML DB Protocol Server. Oracle XML DB supports FTP, HTTP, and
WebDav protocols, as well as JDBC, for fast access of XML data stored in the
database in XMLType tables and columns. See Chapter 19, "Using FTP, HTTP,
and WebDAV Protocols".
Supported XML Services
XML Repository, besides supporting APIs to access and manipulate XML and other
data, also supports the following services:
I Versioning. Oracle XML DB provides support for versioning resources. The
DBMS_XDB_VERSION PL/SQL package implements functions to make a
resource version-controlled. Any subsequent updates to the resource results in
See Also: Chapter 13, "Oracle XML DB Foldering".
See Also: Part V. Oracle XML DB Repository: Foldering, Security,
and Protocols
XMLType Storage Architecture
Introducing Oracle XML DB 1-11
new versions being created while the data corresponding to the previous
versions is retained.
I ACL Security. Security of accessing Oracle XML DB resources is based on the
ACL (Access Control Lists) mechanism. Every resource in Oracle XML DB has
an associated ACL that lists its privileges. Whenever resources are accessed or
manipulated, these ACLs determine if the operation is legal.
I Foldering. XML Repositorys foldering module manages a persistent hierarchy
of containers, also known as folders or directories, and resources. Other Oracle
XML DB modules, such as protocol servers, the schema manager, and the
Oracle XML DB RESOURCE_VIEW API, use the foldering module to map path
names to resources.
XMLType Storage Architecture
Figure 12 describes the XMLType tables and views storage architecture in more
detail.
For XMLType tables, tables with XMLType columns, and views, if XML
schema-based and the XML schema is registered with Oracle XML DB, XML
elements are mapped to database tables. These can be easily viewed and accessed in
XML Repository.
Data in XMLType tables and tables containing XMLType columns can be stored in
Character Large Objects (CLOBs) or natively in structured XML storage.
Data in XMLType views can be stored in local tables or remote tables that are
accessed using DBLinks.
Both XMLType tables and views can be indexed using B*Tree, Oracle Text,
function-based, or bitmap indexes.
Options for accessing data in XML Repository include:
I HTTP, through the HTTP protocol handler.
I WebDav and FTP, through the WebDav and FTP protocol server.
I SQL, through Oracle Net Services including JDBC. Oracle XML DB also
supports XML data messaging using Advanced Queueing (AQ) and SOAP.
XMLType Storage Architecture
1-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
See Also:
I Part II. Storing and Retrieving XML Data in Oracle XML DB
I Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
I Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
I Chapter 24, "Exchanging XML Data Using Advanced Queueing
(AQ) and Oracle Streams"
XMLType Storage Architecture
Introducing Oracle XML DB 1-13
Figure 12 Oracle XML DB: XMLType Storage and Retrieval Architecture
Oracle9i
Database
Direct
HTTP
Access
HTTP
Protocol
Handler
Oracle
Net
Access
CLOB
Storage
Native
Structured
XML
Storage
SQL
Engine
JDBC
WebDAV Access
and
FTP Access
AQ
Access
DAV, FTP
Protocol
Handlers
Local
Tables
DBLinks
Remote
Tables
Accessed
via DBLinks
Indexes:
B*Tree
Text
Function-
based
Bitmap
XML Schemas
XMLType
Tables
XMLType
Views
Repository
Hierarchical
Index
Oracle XML DB
XMLType Storage Architecture
1-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Cached XML Object Management Architecture
Figure 13 shows the Oracle XML DB Cached XML Object Management
Architecture, relevant for programmatic access to XMLType instances. The Oracle
XML DB cache can be deployed at the client (with Oracle JDBC OCI driver) or
within the server. This cache provides:
I A lazily materialized virtual DOM from the stored XMLType, whose nodes are
fetched on demand
I A cache for XML schemas
You can thus get dynamic access to XML without having to materialize an entire
XML DOM in memory. This is accomplished by calculating offsets to the nodes in
the DOM during compilation.
Figure 13 Cached XML Object Management Architecture
XML
Schemas Cache
Cached XML
Object
Management
Dynamic
Java
Access
Virtual
DOM
XMLType Storage Architecture
Introducing Oracle XML DB 1-15
XML Repository Architecture
Figure 14 describes the Oracle XML DB Repository (XML Repository) architecture.
A resource is any piece of content managed by Oracle XML DB, for which we desire
to maintain or view the le/folder metaphor.
Each resource has a name, an associated access control list that determines who can
see the resource, certain static properties, and some extra ones that are extensible by
the application. The application using the Repository obtains a logical view of
folders in parent-child arrangement. The Repository is available in the database (for
example, for SQL access) using the RESOURCE_VIEW.
The RESOURCE_VIEW in Oracle9i database consists of a Resource (itself an
XMLType), that contains the queryable name of the resource, its ACLs, and its
properties, static or extensible.
I If the content comprising the resource is XML (stored somewhere in an
XMLType table or view), the RESOURCE_VIEW points to that XMLType row
that stores the content.
I If the content is not XML, then the RESOURCE_VIEW stores it as a LOB.
Parent-child relationships between folders (necessary to construct the hierarchy) are
maintained and traversed efciently using the hierarchical index. Text indexes are
available to search the properties of a resource, and internal B*Tree indexes over
Names and ACLs speed up access to these attributes of the Resource XMLType.
In addition to the resource information, the RESOURCE_VIEW also contains a Path
column, which holds the paths to each resource.
See Also:
I Chapter 13, "Oracle XML DB Foldering"
I Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
Why Use Oracle XML DB?
1-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 14 Oracle XML DB: Repository Architecture
Why Use Oracle XML DB?
The following section describes Oracle XML DB advantages for building XML
database applications. The main advantages are:
I Unifying Data and Content with Oracle XML DB
I Oracle XML DB Offers Faster Storage and Retrieval of Complex XML
Documents
I Oracle XML DB Helps You Integrate Applications
Table
Name ACL Property 1 Property N Property N
RESOURCE_VIEW (XMLType)
Name ACL Property 1 Property N Extra Content Parent
abc
LOB
XMLType
Rows
Tables or
Views
of XML
Application Logical View of
Oracle XML DB Repository
Path
Database View of Oracle XML DB Repository
B*Tree
Index
Text
Index
Hierarchical
Index
Oracle9i Database
WebDAV
FTP
Why Use Oracle XML DB?
Introducing Oracle XML DB 1-17
I When Your Data Is Not XML You Can Use XMLType Views
Unifying Data and Content with Oracle XML DB
Most applications data and Web content is stored in a relational database or a le
system, or a combination of both. XML is used mostly for transport and is
generated from a database or a le system. As the volume of XML transported
grows, the cost of regenerating these XML documents grows and these storage
methods become less effective at accommodating XML content. See Figure 15.
Oracle XML DB is effective at accommodating XML content. It provides enhanced
native support for XML.
Figure 15 Unifying Data and Content: Some Common XML Architectures
Application Server
Applications
XML Processing and
Repository Layer
RDBMS
Structured Data
and Metadata
Multimedia and
Document Content
Application Server
Applications
RDBMS
Structured Data Multimedia, Document
Content and XML,
Metadata
XML
Repository
Oracle iAS
Applications
Oracle
XML DB
Multimedia and
Document Content,
Structured Data,
XML, Metadata
File
System
Non-Native XML Processing Separate Data and Content Servers Oracle XML DB
Why Use Oracle XML DB?
1-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Organizations today typically manage their structured data and unstructured data
differently:
I Unstructured data, in tables, makes document access transparent and table
access complex
I Structured data, often in binary large objects (such as in BLOBs) makes access
more complex and table access transparent.
With Oracle XML DB you can store and manage both structured, unstructured, and
pseudo or semi-structured data, using a standard data model, and standard SQL
and XML.
Oracle XML DB provides complete transparency and interchangeability between
XML and SQL. You can perform both the following:
I XML operations on object-relational (such as table) data
I SQL operations on XML documents
This makes the database much more accessible to XML-shaped data content.
Exploiting Database Capabilities
In previous releases, without strong database XML support, you most likely stored
your XML data in les or in unstructured storage such as CLOBs. Whether you
stored your XML data in les or CLOBs, you did not exploit several key capabilities
of Oracle database:
I I ndexing and Search: Applications use queries such as nd all the product
denitions created between March and April 2002", a query that is typically
supported by a B*Tree index on a date column. Previously, content management
vendors have had to build proprietary query APIs to handle this problem.
Oracle XML DB can enable efcient structured searches on XML data. See
Chapter 4, "Using XMLType", Chapter 10, "Generating XML Data from the
Database", and Chapter 7, "Searching XML Data with Oracle Text".
I Updates and Transaction Processing: Commercial relational databases use fast
updates of subparts of records, with minimal contention between users trying
to update. As traditionally document-centric data participate in collaborative
environments through XML, this requirement becomes more important. File- or
CLOB- storage cannot provide the granular concurrency control that Oracle
XML DB does. See Chapter 4, "Using XMLType".
I Managing Relationships: Data with any structure typically has foreign key
constraints. Currently, XML data-stores lack this feature, so you must
implement any constraints in application code. Oracle XML DB enables you to
Why Use Oracle XML DB?
Introducing Oracle XML DB 1-19
constrain XML data according to XML schema denitions and hence achieve
control over relationships that structured data has always enjoyed. See
Chapter 5, "Structured Mapping of XMLType" and the purchase order case
study/examples at the end of Chapter 4, "Using XMLType".
I Multiple Views of Data: Most enterprise applications need to group data
together in different ways for different modules. This is why relational views
are necessaryto allow for these multiple ways to combine data. By allowing
views on XML, Oracle XML DB creates different logical abstractions on XML
for, say, consumption by different types of applications. See Chapter 11,
"XMLType Views".
I Performance and Scalability: Users expect data storage, retrieval, and query to
be fast. Loading a le or CLOB and parsing is typically slower than relational
data access. Oracle XML DB dramatically speeds up XML storage and retrieval.
See Chapter 2, "Getting Started with Oracle XML DB" and Chapter 3, "Using
Oracle XML DB".
I Ease of Development: Databases are foremost an application platform that
provides standard, easy ways to manipulate, transform, and modify individual
data elements. While typical XML parsers give standard read access to XML
data they do not provide an easy way to modify and store individual XML
elements. Oracle XML DB supports a number of standard ways to store, modify,
and retrieve data: using XML Schema, XPath, DOM, and Java.
Exploiting XML Capabilities
If the drawbacks of XML le storage force you to break down XML into database
tables and columns, there are several XML advantages you have left:
I Structure I ndependence: The open content model of XML cannot be captured
easily in the pure tables-and-columns world. XML Schemas allow global
element declarations, not just scoped to a container. Hence you can nd a
particular data item regardless of where in the XML document it moves to as
your application evolves. See Chapter 5, "Structured Mapping of XMLType".
See Also:
I Chapter 9, "Java API for XMLType"
I Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
I Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
Why Use Oracle XML DB?
1-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Storage I ndependence: When you use relational design, your client programs
must know where your data is stored, in what format, what table, and what the
relationships are among those tables. XMLType enables you to write
applications without that knowledge and allows DBAs to map structured data
to physical table and column storage. See Chapter 5, "Structured Mapping of
XMLType" and Chapter 13, "Oracle XML DB Foldering".
I Ease of Presentation: XML is understood natively by browsers, many popular
desktop applications, and most internet applications. Relational data is not
generally accessible directly from applications, but requires programming to be
made accessible to standard clients. Oracle XML DB stores data as XML and
pump it out as XML, requiring no programming to display your database
content. See:
I Chapter 6, "Transforming and Validating XMLType Data".
I Chapter 10, "Generating XML Data from the Database".
I Chapter 11, "XMLType Views".
I Oracle9i XML Developers Kits Guide - XDK, in the chapter, XSQL Pages
Publishing Framework. It includes XMLType examples.
I Ease of I nterchange: XML is the language of choice in Business-to-Business
(B2B) data exchange. If you are forced to store XML in an arbitrary table
structure, you are using some kind of proprietary translation. Whenever you
translate a language, information is lost and interchange suffers. By natively
understanding XML and providing DOM delity in the storage/retrieval
process, Oracle XML DB enables a clean interchange. See:
I Chapter 6, "Transforming and Validating XMLType Data"
I Chapter 11, "XMLType Views"
Oracle XML DB Offers Faster Storage and Retrieval of Complex XML Documents
Users today face a performance barrier when storing and retrieving complex, large,
or many XML documents. Oracle XML DB provides very high performance and
scalability for XML operations. The major performance features are:
I Native XMLType. See Chapter 4, "Using XMLType".
I The lazily evaluated virtual DOM support. See Chapter 8, "PL/SQL API for
XMLType".
Why Use Oracle XML DB?
Introducing Oracle XML DB 1-21
I Database-integrated ad-hoc XPath and XSLT support. This support is described
in several chapters, including Chapter 4, "Using XMLType" and Chapter 6,
"Transforming and Validating XMLType Data".
I XML Schema-caching support. See Chapter 5, "Structured Mapping of
XMLType".
I CTXPATH Text indexing. See Chapter 7, "Searching XML Data with Oracle
Text".
I The hierarchical index over the Repository. See Chapter 13, "Oracle XML DB
Foldering".
Oracle XML DB Helps You Integrate Applications
Oracle XML DB enables data from disparate systems to be accessed through
gateways and combined into one common data model. This reduces the complexity
of developing applications that must deal with data from different stores.
When Your Data Is Not XML You Can Use XMLType Views
XMLType views provide a way for you wrap existing relational and object-relational
data in XML format. This is especially useful if, for example, your legacy data is not
in XML but you need to migrate to an XML format. Using XMLType views you do
not need to alter your application code.
To use XMLType views you must rst register an XML schema with annotations
that represent the bi-directional mapping fromXML to SQL object types and back to
XML. An XMLType view conforming to this schema (mapping) can then be created
by providing an underlying query that constructs instances of the appropriate SQL
object type. Figure 16 summarizes the Oracle XML DB advantages.
See Also: Chapter 11, "XMLType Views".
Why Use Oracle XML DB?
1-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 16 Oracle XML DB Benets
Oracle
XML DB
Faster Storage and
Retrieval of Complex
XML Documents
Unifies Data
and Content
Helps
Integrate
Applications
Also Handles
non-XML Data
with XMLType
Views
Higher performance
of XML operations
Higher scalability
of XML operations
Facilitates migrating of
legacy and non-XML to
XML data
Enhanced native
database support for
XML
Stores and manages
structured, unstructured,
and semi-structured data
Transparent XML and SQL
interoperability
Exploits database features:
Exploits XML features:
XMLType views
over local or remote
sources
Connectivity to other
databases, files, ...
Uniform SQL / XML
queries over data
integrated from
multiple sources
indexing, searching
updating, transaction processing
manages constraints
multiple data views
speeds up XML storage, retrieval
supports standards for storing,
modifying, retrieving data
structure and storage independence
facilitates presentation and data display
facilitates B2B data exchange
Building Oracle XML DB XML Messaging Applications with Advanced Queueing
Introducing Oracle XML DB 1-23
Searching XML Data Stored in CLOBs Using Oracle Text
Oracle enables special indexing on XML, including Oracle Text indexes for section
searching, special operators to process XML, aggregation of XML, and special
optimization of queries involving XML.
XML data stored in Character Large Objects (CLOBs) or stored in XMLType
columns in structured storage (object-relationally), can be indexed using Oracle
Text. HASPATH() and INPATH() operators are designed to optimize XML data
searches where you can search within XML text for substring matches.
Oracle9i Release 2 (9.2) also provides:
I CONTAINS() function that can be used with existsNode() for XPath based
searches. This is for use as the ora:contains function in an XPath query, as
part of existsNode().
I The ability to create indexes on UriType and XDBUriType columns.
I A new index type, CTXXPATH, that allows higher performance XPath searching
in Oracle XML DB under existsNode().
Building Oracle XML DB XML Messaging Applications with Advanced
Queueing
Advanced Queueing now supports the use of:
I XMLType as a message/payload type, including XML schema-based XMLType
I Queueing/dequeuing of XMLType messages
See Also:
I Chapter 7, "Searching XML Data with Oracle Text"
I Oracle Text Application Developers Guide
I Oracle Text Reference
Managing Oracle XML DB Applications with Oracle Enterprise Manager
1-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Managing Oracle XML DB Applications with Oracle Enterprise Manager
You can use Oracle Enterprise Manager (Enterprise Manager) to manage and
administer your Oracle XML DB application. Enterprise Managers graphical user
interface facilitates your performing the following tasks:
I Conguration
I Conguring Oracle XML DB, including protocol server conguration
I Viewing and editing Oracle XML DB conguration parameters
I Registering XML schema
I Create resources
I Managing resource security, such as editing resource ACL denitions
I Granting and revoking resource privileges
I Creating and editing resource indexes
I Viewing and navigating your Oracle XML DB hierarchical Repository
I Create XML schema-based tables and views
I Creating your storage infrastructure based on XML schemas
I Editing an XML schema
I Creating an XMLType table and a table with XMLType columns
I Creating a view based XML schema
I Creating a function-based index based on XPath expressions
See Also:
I Oracle9i Application Developers Guide - Advanced Queuing for
information about using XMLType with Oracle Advanced
Queuing
I Chapter 24, "Exchanging XML Data Using Advanced Queueing
(AQ) and Oracle Streams"
See Also: Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
Standards Supported by Oracle XML DB
Introducing Oracle XML DB 1-25
Requirements for Running Oracle XML DB
Oracle XML DB is available with Oracle9i Release 2 (9.2).
Standards Supported by Oracle XML DB
Oracle XML DB supports all major XML, SQL, Java, and Internet standards:
I W3C XML Schema 1.0 Recommendation. You can register XML schemas,
validate stored XML content against XML schemas, or constrain XML stored in
the server to XML schemas.
I W3C XPath 1.0 Recommendation. You can search or traverse XML stored inside
the database using XPath, either from HTTP requests or from SQL.
I ISO-ANSI Working Draft for XML-Related Specications (SQL/XML) [ISO/IEC
9075 Part 14 and ANSI]. You can use the emerging ANSI SQLX functions to
query XML from SQL.
I Java Database Connectivity (JDBC) API. JDBC access to XML is available for
Java programmers.
I W3C XSL 1.0 Recommendation. You can transform XML documents at the
server using XSLT.
I W3C DOM Recommendation Levels 1.0 and 2.0 Core. You can retrieve XML
stored in the server as an XML DOM, for dynamic access.
I Protocol support. You can store or retrieve XML data from Oracle XML DB
using standard protocols such as HTTP, FTP, IETF WebDAV, as well as Oracle
Net. See Chapter 19, "Using FTP, HTTP, and WebDAV Protocols".
I Java Servlet version 2.2, (except that the Servlet WAR le, web.xml is not
supported in its entirety, and only one ServletContext and one web-app are
currently supported, and stateful servlets are not supported). See Chapter 20,
"Writing Oracle XML DB Applications in Java".
I Simple Object Access Protocol (SOAP). You can access XML stored in the server
from SOAP requests. You can build, publish, or nd Web Services using Oracle
XML DB and Oracle9iAS, using WSDL and UDDI. You can use Oracle
See:
I http://otn.oracle.com/tech/xml for the latest news
and white papers on Oracle XML DB
I Chapter 2, "Getting Started with Oracle XML DB"
Oracle XML DB Technical Support
1-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Advanced Queuing IDAP, the SOAP specication for queuing operations, on
XML stored in Oracle9i databases. See Chapter 24, "Exchanging XML Data
Using Advanced Queueing (AQ) and Oracle Streams" and Oracle9i Application
Developers Guide - Advanced Queuing.
Oracle XML DB Technical Support
Besides your regular channels of support through your customer representative or
consultant, technical support for Oracle XML-enabled technologies is available free
through the Discussions option on Oracle Technology Network (OTN):
http://otn.oracle.com/tech/xml
You do not need to be a registered user of OTN to post or reply to XML-related
questions on the OTN technical discussion forum. To use the OTN technical forum
follow these steps:
1. In the left-hand navigation bar of the OTN site, select Support > Discussions.
2. Click Enter a Technical Forum.
3. Scroll down to the Technologies section. Select XML.
4. Post any questions, comments, requests, or bug reports.
Terminology Used in This Manual
Table 12 describes terms used in this manual.
See Also: "Glossary"
Terminology Used in This Manual
Introducing Oracle XML DB 1-27
Table 12 Terminology Used in This Manual
Term Used in Manual Description
XML Schema XML Schema is a schema denition language (also in XML) that can be used to
describe the structure and various other semantics of conforming instance
documents. See Appendix B, "XML Schema Primer".
Oracle XML DB uses annotated XML schemas, that is, XML schemas that include
additional attributes dened by Oracle XML DB. The Oracle XML DB attributes
serve to specify metadata that in turn determines both the XML structuring and its
mapping to a database schema. You can register XML schemas and then use the
appropriate XML schema URLs while creating XMLType tables and columns and
also to dene XMLType views. See:
I Chapter 5, "Structured Mapping of XMLType"
I Appendix B, "XML Schema Primer"
XPath A language for addressing parts of an XML document, for use by XSLT and
XPointer. XPath uses the directory traversal syntax to traverse an XML document.
It includes syntax for specifying predicate expressions on the nodes traversed. The
result of a XPath traversal is an XML fragment. See Appendix C, "XPath and
Namespace Primer".
XSL A stylesheet language used for transforming XML documents to HTML, XML or
any other formats. See Appendix D, "XSLT Primer".
DOM Document Object Model (DOM) is an application program interface (API) for
HTML and XML documents. It denes the logical structure of documents and the
way a document is accessed and manipulated. In the DOM specication, the term
document is used in the broad sense.
XML is increasingly being used as a way of representing many different kinds of
information that may be stored in diverse systems, and much of this would
traditionally have been seen as data rather than as documents. Nevertheless, XML
presents this data as documents, and DOM can be used to manage this data.
With DOM, you can build documents, navigate their structure, and add, modify,
or delete elements and content. Anything in an HTML or XML document can be
accessed, changed, deleted, or added using DOM, with a few exceptions. DOM is
designed for use with any programming language.
Oracle XML DB provides implementations of DOM APIs to operate on XMLType
instances using various client APIs including PL/SQL DOM, Java DOM, and C
DOM (for OCI clients). See
I Chapter 5, "Structured Mapping of XMLType"
I Chapter 8, "PL/SQL API for XMLType"
Oracle XML DB
Repository
See also Chapter 3, "Using Oracle XML DB"
Terminology Used in This Manual
1-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Resource An object identied by a URL. In compliance with HTTP and WebDAV standards,
it has a set of system properties, such as displayname, creationdate, and so
on. In all cases, it maintains a reference count and destroys any associated data
when the last URL binding to it is removed. It maintains an access control list
(ACL) and owner. An Oracle XML DB resource is an XMLType mapped to a path
name that contains these properties. See Chapter 15, "RESOURCE_VIEW and
PATH_VIEW".
Repository Oracle XML DB Repository is the set of all Oracle XML DB resources. The
Repository is a hierarchically organized set of XMLType objects, each with a path
name to identify them. Think of the Oracle XML DB Repository as a le system of
objects rather than les. There is one root to this Repository (/), which contains a
set of resources, each with a path name. Resources that contain (contain with
respect to the hierarchical naming system) other resources are called folders (see
Folder in the following).
Oracle XML DB objects can have many path names (that is, a resource can be in
more than one folder). In some sense, the database itself is the Repository, since
any database object can be mapped to a path name. However, Oracle XML DB uses
Repository to refer to the set of database objects, in any schema, that are mapped
to path names. See Chapter 13, "Oracle XML DB Foldering".
Folder A non-leaf node object in Oracle XML DB Repository, or one with the potential to
be such a node. Oracle XML DB has special storage semantics for collections for
optimization reasons. It maintains a special kind of hierarchical index used to
navigate the hierarchy of collections, and denes a property, called name that is
used to form path names in the hierarchy. There are many names for collections,
such as folders and directories. Any XML element type can be a folder by specifying
the isFolder attribute in the Oracle XML DB schema. See Chapter 13, "Oracle
XML DB Foldering".
Pathname A hierarchical name is composed of a root element (the rst /), element separators
(/), and various sub-elements (or path elements). A path element can be composed
of any character in the database character set except the following (\ /). In
Oracle XML DB, a forward slash is the default name separator in a path name.
Resource Name A resource here means any database object stored in Oracle XML DB Repository.
Resource name is the name of a resource within its parent folder. Resource names
are the path elements, that is, lenames within folders. Resource names must be
unique (potentially subject to case-insensitivity) within a folder.
Content The body of a resource is what you get when you treat the resource like a le and
ask for its contents.
XDBBinary An XML element dened by the Oracle XML DB schema that contains binary data.
XDBBinary elements are stored in the Repository when completely unstructured
binary data is uploaded into Oracle XML DB.
Table 12 Terminology Used in This Manual (Cont.)
Term Used in Manual Description
Oracle XML DB Examples Used in This Manual
Introducing Oracle XML DB 1-29
Oracle XML DB Examples Used in This Manual
This manual contains examples that illustrate the use of Oracle XML DB and
XMLType. The examples are based on a number of database schema, sample XML
documents, and sample XML schema. The infrastructure for the examples is
described, in most cases, with the examples in each chapter.
ACL Terminology See also Chapter 18, "Oracle XML DB Resource Security"
Access Control List
(ACL)
Restricts access to an object. Oracle XML DB uses ACLs to restrict access to any
Oracle XML DB resource, that is, any XMLType object that is mapped into the
Oracle XML DB le system hierarchy.
Protocol Terminology See also Chapter 19, "Using FTP, HTTP, and WebDAV Protocols" and Chapter 3,
"Using Oracle XML DB"
FTP File Transfer Protocol. Dened as an Internet Standard (STD009) in RFC959.
Oracle XML DB implements this standard. FTP is implemented by both dedicated
clients at the operating system level, le system explorer clients, and browsers.
FTP is commonly used for bulk le upload and download and for scripting of
Repository maintenance. FTP can be used in a mode similar to HTTP, with
frequent session establishment/destruction, by browsers in passive mode.
HTTP HyperText Transfer Protocol. Oracle XML DB implements HTTP 1.1 as dened
in RFC2616. Oracle XML DB implements cookies, basic authentication, and
HTTP/1.1 (RFC2616, 2109 & 2965) in this release.
WebDAV Web Distributed Authoring and Versioning (WebDav). Oracle XML DB supports
RFC2518 and access control in this release.
Servlets Sun developed a widely accepted standard for invoking Java code as the result of
protocol requests and passing parameters to that request. Servlets are most
commonly implemented with HTTP. The majority of Java services are
implemented as servlets, through mechanisms (implemented in Java) such as JSPs
(Java Server Pages) or SOAP (Simple Object Access Protocol). Servlets thus form
the architectural basis for a large percentage of web application development.
Oracle XML DB provides a method for invoking Java stored procedures over
protocols other than Oracle Services (Net Services). Oracle XML DB implements
most servlet standards. Chapter 20, "Writing Oracle XML DB Applications in Java".
Table 12 Terminology Used in This Manual (Cont.)
Term Used in Manual Description
Oracle XML DB Examples Used in This Manual
1-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
See Also:
I Appendix G, "Example Setup scripts. Oracle XML DB -
Supplied XML Schemas"
I http://otn.oracle.com/tech/xml/doc.html for the updated
example listings.
Getting Started with Oracle XML DB 2-1
2
Getting Started with Oracle XML DB
This chapter provides some preliminary design criteria for consideration when
planning your Oracle XML DB solution. It contains the following sections:
I Getting Started with Oracle XML DB
I When to Use the Oracle XML DB
I Designing Your XML Application
I Oracle XML DB Design Issues: Introduction
I Oracle XML DB Application Design: a. How Structured Is Your Data?
I Oracle XML DB Application Design: b. Access Models
I Oracle XML DB Application Design: c. Application Language
I Oracle XML DB Application Design: d. Processing Models
I Oracle XML DB Design: Storage Models
Getting Started with Oracle XML DB
2-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Getting Started with Oracle XML DB
Installing Oracle XML DB
Oracle XML DB is installed as part of the General Purpose Database shipping with
Oracle9i Release 2 (9.2) database. If you need to perform a manual installation or
de-installation of the Oracle XML DB, see Appendix A, "Installing and Conguring
Oracle XML DB" for further information.
When to Use the Oracle XML DB
Oracle XML DB is suited for any application where some or all of the data
processed by the application is represented using XML. Oracle XML DB provides
for high performance ingestion, storage, processing and retrieval of XML data.
Additionally, it also provides the ability to quickly and easily generate XML from
existing relational data.
The type of applications that Oracle XML DB is particularly suited to include:
I Business-to-Business (B2B) and Application-to-Application (A2A) integration
I Internet applications
I Content-management applications
I Messaging
I Web Services
A typical Oracle XML DB application has one or more of the following
requirements and characteristics:
I Large numbers of XML documents must be ingested or generated
I Large XML documents need to be processed or generated
I High performance searching, both within a document and across a large
collections of documents
I High Levels of security. Fine grained control of security
I Data processing must be contained in XML documents and data contained in
traditional relational tables
I Uses languages such as Java that support open standards such as SQL, XML,
XPath, and XSLT
Oracle XML DB Design Issues: Introduction
Getting Started with Oracle XML DB 2-3
I Accesses information using standard Internet protocols such as FTP,
HTTP/WebDav, or JDBC
I Full queriability from SQL and integration with analytic capabilities
I Validation of XML documents is critical
Designing Your XML Application
Oracle XML DB provides you with the ability to ne tune howXML documents will
be stored and processed in Oracle9i database. Depending on the nature of the
application being developed, XML storage must have at least one of the following
features
I High performance ingestion and retrieval of XML documents
I High performance indexing and searching of XML documents
I Be able to update sections of an XML document
I Manage highly either or both structured and non-structured XML documents
Oracle XML DB Design Issues: Introduction
This section discusses the preliminary design criteria you can consider when
planning your Oracle XML DB application. Figure 21 provides an overview of
your main design options for building Oracle XML DB applications.
a. Data
Will your data be highly structured (mostly XML), semi- structured (pseudo-
structured), or mostly non-structured? If highly structured, will your table(s) be
XML schema-based or non-schema-based? See "Oracle XML DB Application
Design: a. How Structured Is Your Data?" on page 2-5 and Chapter 3, "Using Oracle
XML DB".
b. Access
How will other applications and users access your XML and other data? How
secure must the access be? Do you need versioning? See "Oracle XML DB
Application Design: b. Access Models" on page 2-7.
Oracle XML DB Design Issues: Introduction
2-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
c. Application Language
In which language(s) will you be programming your application? See "Oracle XML
DB Application Design: c. Application Language" on page 2-8.
d. Processing
Will you need to generate XML? See Chapter 10, "Generating XML Data from the
Database".
How often will XML documents be accessed, updated, and manipulated? Will you
need to update fragments or the whole document?
Will you need to transform the XML to HTML, WML, or other languages, and how
will your application transform the XML? See Chapter 6, "Transforming and
Validating XMLType Data".
Does your application need to be primarily database resident or work in both
database and middle tier?
Is your application data-centric, document- and content-centric, or integrated (is
both data- and document-centric). "Oracle XML DB Application Design: d.
Processing Models" on page 2-9.
Will you be exchanging XML data with other applications, across gateways? Will
you need Advanced Queueing (AQ) or SOAP compliance? See Chapter 24,
"Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams".
Storage
How and where will you store the data, XML data, XML schema, and so on? See
"Oracle XML DB Design: Storage Models" on page 2-10.
Note: Your choice of which models to choose in the preceding
four categories, a through d, are typically related to each other.
However, the storage model you choose is orthogonal to the choices
you make for the other design models. In other words, choices you
make for the other design modeling options are not dependent on
the storage model option you choose.
Oracle XML DB Application Design: a. How Structured Is Your Data?
Getting Started with Oracle XML DB 2-5
Figure 21 Oracle XML DB Design Options
Oracle XML DB Application Design: a. How Structured Is Your Data?
Figure 22 shows the following data structure categories and associated suggested
storage options:
I Structured data. Is your data highly structured? In other words, is your data
mostly XML data?
I Semi/pseudo-structured data. Is your data semi/pseudo-structured? In other
words does your data include some XML data?
I Unstructured data. Is your data unstructured? In other words, is your data
mostly non-XML data?
XML Schema-Based or Non-Schema-Based
Also consider the following data modeling questions:
I If your application is XML schema-based:
For structured data, you can use either Character Large Object (CLOB) or
structured storage.
Data
Structure?
Access?
Repository
Path Access
SQL
Query Access
Language?
Java
JDBC
PL/SQL
JNDI
Processing and
Data
Manipulation?
DOM
SQL inserts /
updates
XSLT
Queriability
Updatability
Storage Options ?
a c
b d
XMLType Tables or XMLType Views
You get the same Oracle XML DB functionality regardless
of which storage option you chose.
The storage option affects the application's performance
and data fidelity
Oracle XML DB Application Design: a. How Structured Is Your Data?
2-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
For semi- or pseudo-structured data, you can use either CLOB, structured,
or hybrid storage. Here your XML schema can be more loosely coupled. See
also "Oracle XML DB Design: Storage Models" on page 2-10.
For unstructured data, an XML schema design is not applicable.
I If your application is non-schema-based. For structured, semi/
pseudo-structured, and unstructured data, you can store your data in either
CLOBs in XMLType tables or views or in les in Repository folders. With this
design you have many access options including path- and query-based access
through Resource Views.
Figure 22 Data Storage Models: How Structured Is Your Data?
How Structured is
Your Data?
Structured
Data
Unstructured
Data
Semi-structured
Psudo-structured
Data
XML
Schema
Based?
Non-Schema
Based?
XML
Schema
Based?
Non-Schema
Based?
Use either:
CLOB or
Structured
Storage
Store as:
CLOB in
XMLType
Table
File in
Repository
Folder
Views
Access
through
Resource
APIs
Use either:
CLOB
Structured
Hybrid
Storage
(semi-
structured
storage)
Store as:
CLOB in
XMLType
Table
File in
Repository
Folder
Views
Access
through
Resource
APIs
Store as:
CLOB in
XMLType
Table
File in
Repository
Folder
Views
Access
through
Resource
APIs
Oracle XML DB Application Design: b. Access Models
Getting Started with Oracle XML DB 2-7
Oracle XML DB Application Design: b. Access Models
Figure 23 shows the two main data access modes to consider when designing your
Oracle XML DB applications:
I Navigation- or path-based access. This is suitable for both content/document
and data oriented applications. Oracle XML DB provides the following
languages and access APIs:
SQL access through Resource/Path Views. See Chapter 15,
"RESOURCE_VIEW and PATH_VIEW".
PL/SQL access through DBMS_XDB. See Chapter 16, "Oracle XML DB
Resource API for PL/SQL (DBMS_XDB)".
Java access. See Chapter 17, "Oracle XML DB Resource API for Java".
Protocol-based access using HTTP/WebDAV or FTP, most suited to
content-oriented applications. See Chapter 19, "Using FTP, HTTP, and
WebDAV Protocols".
I Query-based access. This can be most suited to data oriented applications.
Oracle XML DB provides access using SQL queries through the following APIs:
Java (through JDBC) access. See Chapter 9, "Java API for XMLType".
PL/SQL access. See Chapter 8, "PL/SQL API for XMLType".
These options for accessing Repository data are also discussed in Chapter 13,
"Oracle XML DB Foldering".
You can also consider the following access model criteria:
I What level of security do you need? See Chapter 18, "Oracle XML DB Resource
Security".
I What kind of indexing will best suit your application? Will you need to use
Oracle Text indexing and querying? See Chapter 4, "Using XMLType" and
Chapter 7, "Searching XML Data with Oracle Text".
I Do you need to version the data? If yes, see Chapter 14, "Oracle XML DB
Versioning".
Oracle XML DB Application Design: c. Application Language
2-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 23 Data Access Models: How Will Users or Applications Access the Data?
Oracle XML DB Application Design: c. Application Language
You can program your Oracle XML DB applications in the following languages:
I Java (JDBC, Java Servlets)
I PLSQL
See Also:
I Chapter 9, "Java API for XMLType"
I Chapter 17, "Oracle XML DB Resource API for Java"
I Chapter 20, "Writing Oracle XML DB Applications in Java"
I Appendix E, "Java DOM API for XMLType, Resource API for
Java: Quick Reference"
Oracle XML DB
Data Access Options
Use SQL Use Repository
JDBC / Java bean
PL/SQL
Available Languages
and APIs
SQL (RESOURCE_ / PATH_VIEW)
JNDI
FTP
HTTP / WebDav
Available Language
and XMLType APIs
Query-based
Access
Path-based
Access
Oracle XML DB Application Design: d. Processing Models
Getting Started with Oracle XML DB 2-9
Oracle XML DB Application Design: d. Processing Models
The following processing options are available and should be considered when
designing your Oracle XML DB application:
I XSLT. Will you need to transformthe XML to HTML, WML, or other languages,
and how will your application transform the XML? While storing XML
documents in Oracle XML DB you can optionally ensure that their structure
complies (is valid against) with specic XML Schema. See Chapter 6,
"Transforming and Validating XMLType Data".
I DOM. See Chapter 8, "PL/SQL API for XMLType". Use object-relational
columns, VARRAYs, nested tables, as well as LOBs to store any element or
Element-subtree in your XML Schema, and still maintain DOM delity (DOM
stored == DOM retrieved). Note: If you choose the CLOB storage option,
available with XMLType since Oracle9i Release 1 (9.0.1), you can keep white
spaces. If you are using XML schema, see the discussion on DOM delity in
Chapter 5, "Structured Mapping of XMLType".
I XPath searching. You can use XPath syntax embedded in an SQL statement or
as part of an HTTP request to query XML content in the database. See
Chapter 4, "Using XMLType",Chapter 7, "Searching XML Data with Oracle
Text", Chapter 13, "Oracle XML DB Foldering", and Chapter 15,
"RESOURCE_VIEW and PATH_VIEW".
I XML Generation and XMLType views. Will you need to generate or regenerate
XML? If yes, see Chapter 10, "Generating XML Data from the Database".
How often will XML documents be accessed, updated, and manipulated? See
Chapter 4, "Using XMLType" and Chapter 15, "RESOURCE_VIEW and
PATH_VIEW".
Will you need to update fragments or the whole document? You can use XPath to
specify individual elements and attributes of your document during updates,
See Also:
I Chapter 8, "PL/SQL API for XMLType"
I Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
I Appendix F, "Oracle XML DB XMLType API, PL/SQL and
Resource PL/SQL APIs: Quick Reference"
Oracle XML DB Design: Storage Models
2-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
without rewriting the entire document. This is more efcient, especially for large
XML documents. Chapter 5, "Structured Mapping of XMLType".
Is your application data-centric, document- and content-centric, or integrated (is
both data- and document-centric)? See Chapter 3, "Using Oracle XML DB".
Messaging Options
Advanced Queueing (AQ) supports XML and XMLType applications. You can
create queues with payloads that contain XMLType attributes. These can be used for
transmitting and storing messages that contain XML documents. By dening Oracle
objects with XMLType attributes, you can do the following:
I Store more than one type of XML document in the same queue. The documents
are stored internally as CLOBs.
I Selectively dequeue messages with XMLType attributes using the operators
existsNode(), extract(), and so on.
I Dene transformations to convert Oracle objects to XMLType.
I Dene rule-based subscribers that query message content using XMLType
operators such as existsNode() and extract().
Oracle XML DB Design: Storage Models
Figure 24 summarizes the Oracle XML DB storage options with regards to using
XMLType tables or views. If you have existing or legacy relational data, use
XMLType Views.
Regardless of which storage options you choose for your Oracle XML DB
application, Oracle XML DB provides the same functionality. However, the option
you choose will affect your applications performance and the data delity (data
accuracy).
Currently, the three main storage options for Oracle XML DB applications are:
I LOB-based storage? LOB-based storage assures complete textual delity
including whitespaces. This means that if you store your XML documents as
See Also:
I Chapter 24, "Exchanging XML Data Using Advanced Queueing
(AQ) and Oracle Streams"
I Oracle9i Application Developers Guide - Advanced Queuing
Oracle XML DB Design: Storage Models
Getting Started with Oracle XML DB 2-11
CLOBs, when the XML documents are retrieved there will be no data loss. Data
integrity is high, and the cost of regeneration is low.
I Structured storage? Structured storage loses whitespace information but
maintains delity to the XML DOM, namely DOM stored = DOM retrieved.
This provides:
Better SQL queriability with improved performance
Piece-wise updatability
I Hybrid or semi-structured storage. Hybrid storage is a special case of
structured storage in which a portion of the XML data is broken up into a
structured format and the remainder of the data is stored as a CLOB.
The storage options are totally independent of the following criteria:
I Data queryability and updatability, namely, how and how often the data is
queried and updated.
I How your data is accessed. This is determined by your application processing
requirements.
I What language(s) your application uses. This is also determined by your
application processing requirements.
Using XMLType Tables
If you are using XMLType tables you can store your data in:
I CLOBs (unstructured) storage
I Structured storage
I Hybrid or semi-structured storage
See Also:
I "Storing XML: Structured or Unstructured Storage", "Structured
Storage: XML Schema-Based Storage of XMLType" and "Storage
Options for Resources" in Chapter 3, "Using Oracle XML DB"
I Chapter 4, "Using XMLType","Storing XMLType Data in Oracle
XML DB" on page 4-4
I Chapter 5, "Structured Mapping of XMLType", "DOM Fidelity"
on page 5-21
Oracle XML DB Design: Storage Models
2-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Using XMLType Views
Use XMLType views if you have existing relational data. You can use the following
options to dene the XMLType views:
I SQLX operators. Using these operators you can store the data in relational
tables and also generate/regenerate the XML. See Chapter 10, "Generating XML
Data from the Database".
I Object Types:
Object tables
Object constructors. You can store the data in relational tables using object
constructors.
Object views
Figure 24 Structured Storage Options
XMLType
Views
Oracle XML DB Data
Storage Options
Your Storage Option Affects Performance
and Data Fidelity
If you have existing
relational data use
XMLType Views
CLOB or
Unstructured
Storage
Hybrid or
Semi-structured
Storage
SQLX
Operators
Relational
Tables
Object
Types
XMLType
Tables
Can define the
views using:
Structured
Storage
Object
Tables
Object
Views
Object
Constructors
Relational
Tables
Using Oracle XML DB 3-1
3
Using Oracle XML DB
This chapter describes where and howyou can use Oracle XML DB. It discusses and
includes examples on common Oracle XML DB usage scenarios including XMLType
data storage and access, updating and validating your data, and why it helps to
understand XPath and XML Schema. It provides you with ideas for how you can
use the Repository to store, access, and manipulate database data using standard
protocols from a variety of clients.
The chapter also discusses howyou can dene a default XML table for storing XML
schema-based documents and using XDBUriType to access non-schema-based
content.
It contains the following sections:
I Storing Data in an XMLType Column or XMLType Table
I Accessing Data in XMLType Columns or XMLType Tables
I Using XPath with Oracle XML DB
I Updating XML Documents with updateXML()
I Introducing the W3C XSLT Recommendation
I Using XSL/XSLT with Oracle XML DB
I Other XMLType Methods
I Introducing the W3C XML Schema Recommendation
I Validating an XML Document Using an XML Schema
I Storing XML: Structured or Unstructured Storage
I Structured Storage: XML Schema-Based Storage of XMLType
I Oracle XML DB Repository
3-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Query-Based Access to Oracle XML DB Repository
I Storage Options for Resources
I Dening Your Own Default Table Storage for XML Schema-Based Documents
I Accessing XML Schema-Based Content
I Accessing Non-Schema-Based Content With XDBUriType
I Oracle XML DB Protocol Servers
See Also:
I Chapter 25, "Oracle XML DB Case Study: Web Services Retrieve
and Display XML Documents"
I Chapter 26, "Oracle XML DB Basic Demo"
for further examples of where and how you can use Oracle XML
DB.
Storing Data in an XMLType Column or XMLType Table
Using Oracle XML DB 3-3
Storing Data in an XMLType Column or XMLType Table
When storing XML documents in Oracle9i database you can use a number of
approaches, including:
I Parsing the XML document apart, outside Oracle9i database, and storing the
data in the XML document as rows in one or more tables. In this scenario the
database has no idea that is managing XML content.
I Storing the XML document in Oracle9i database using a CLOB or VARCHAR
column. Again in this scenario the database has no idea that it is managing
XML content, but you can programmatically use XDK to perform XML
operations.
I Storing the XML document in Oracle9i database using the XMLType datatype.
Two options are available in this scenario.
I The rst is to store the XML document in an XMLType column.
I The second is to store the XML document using an XMLType table.
Both these options mean that the database is aware that it is managing XML
content. Selecting this approach provides you with a number of signicant
advantages, as the database provides a set of features that make it possible to
process XML content efciently.
Example 31 Creating a Table with an XMLType Column
CREATE TABLE Example1
(
KEYVALUE varchar2(10) primary key,
XMLCOLUMN xmltype
);
Example 32 Creating a Table of XMLType
CREATE TABLE XMLTABLE OF XMLType;
Example 33 Storing an XML Document by First Creating an XMLType Instance Using
getDocument()
To store an XML document in an XMLType table or column the XML document
must rst be converted into an XMLType instance. This is done using the different
constructors provided by the XMLType datatype. For example, given a PL/SQL
function called getCLOBDocument():
create or replace function getClobDocument(
Storing Data in an XMLType Column or XMLType Table
3-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
filename in varchar2,
charset in varchar2 default NULL)
return CLOB deterministic
is
file bfile := bfilename(DIR,filename);
charContent CLOB := ;
targetFile bfile;
lang_ctx number := DBMS_LOB.default_lang_ctx;
charset_id number := 0;
src_offset number := 1 ;
dst_offset number := 1 ;
warning number;
begin
if charset is not null then
charset_id := NLS_CHARSET_ID(charset);
end if;
targetFile := file;
DBMS_LOB.fileopen(targetFile, DBMS_LOB.file_readonly);
DBMS_LOB.LOADCLOBFROMFILE(charContent, targetFile,
DBMS_LOB.getLength(targetFile), src_offset, dst_offset,
charset_id, lang_ctx,warning);
DBMS_LOB.fileclose(targetFile);
return charContent;
end;
/
-- create XMLDIR directory
-- connect system/manager
-- create directory XMLDIR as <location_of_xmlfiles_on_server>;
-- grant read on directory xmldir to public with grant option;
-- you can use getCLOBDocument() to generate a CLOB from a file containin
-- an XML document. For example, the following statement inserts a row into the
-- XMLType table Example2 created earlier:
INSERT INTO XMLTABLE
VALUES(XMLTYPE(getCLOBDocument(purchaseorder.xml)));
Note the use of parameter, "charset". This is used to identify the character set of the
designated le. If omitted, the default character set id of the current database is
used.
For example, if a le, invoice.xml uses one of the Korean character sets,
KO16KSC5601, it can be loaded into XMLType table, XMLDOC as follows:
insert into xmldoc
Using XPath with Oracle XML DB
Using Oracle XML DB 3-5
values(xmltype(getClobDocument(invoice.xml,KO16KSC5601)));
The following example uses the UTF8 le format:
insert into xmldoc
values(xmltype(getClobDocument(invoice.xml,UTF8)));
In the last example both the database and the le use the same character set such as
UTF8:
insert into xmldoc values(xmltype(getClobDocument(invoice.xml)));
Accessing Data in XMLType Columns or XMLType Tables
Once a collection of XML documents have been stored as XMLType tables or
columns the next step is to be able to retrieve them. When working with a collection
of XML documents you have two fundamental tasks to perform:
I Decide how to select a subset of the available documents
I Determine how best to access some subset of the nodes contained within the
documents
Oracle9i database and XMLType datatype provide a number of functions that make
it easy to perform these tasks. These functions make use of the W3C XPath
recommendation to navigate across and within a collection of XML documents.
Using XPath with Oracle XML DB
A number of the functions provided by the Oracle XML DB are based on the W3C
XPath recommendation. XPath traverses nested XML elements by your specifying
the elements to navigate through with a slash-separated list of element and attribute
names. By using XPath to dene queries within and across XML documents. With
Oracle XML DB you can express hierarchical queries against XML documents in a
familiar, standards compliant manner.
Note: Oracle XML DB can handle multibyte characters as long as
the client character set is the same as the database character set.
See Also: Appendix C, "XPath and Namespace Primer" for an
introduction to the W3C XPath Recommendation.
Using XPath with Oracle XML DB
3-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The primary use of XPath in Oracle XML DB is in conjunction with the extract(),
extractValue(), and existsNode() functions.
The existsNode() function evaluates whether or not a given document contains a
node which matches a W3C XPath expression. The existsNode() function returns
true (1) if the document contains the node specied by the XPath expression
supplied to the function. The functionality provided by the existsNode()
function is also available through the XMLType datatype existNode() method.
PurchaseOrder XML Document
Examples in this section are based on the following PurchaseOrder XML
document:
<PurchaseOrder
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.oracle.com/xdb/po.xsd">
<Reference>ADAMS-20011127121040988PST</Reference>
<Actions>
<Action>
<User>SCOTT</User>
<Date>2002-03-31</Date>
</Action>
</Actions>
<Reject/>
<Requestor>Julie P. Adams</Requestor>
<User>ADAMS</User>
<CostCenter>R20</CostCenter>
<ShippingInstructions>
<name>Julie P. Adams</name>
<address>Redwood Shores, CA 94065</address>
<telephone>650 506 7300</telephone>
</ShippingInstructions>
<SpecialInstructions>Ground</SpecialInstructions>
<LineItems>
<LineItem ItemNumber="1">
<Description>The Ruling Class</Description>
<Part Id="715515012423" UnitPrice="39.95" Quantity="2"/>
</LineItem>
<LineItem ItemNumber="2">
See Also:
I Chapter 4, "Using XMLType"
I Chapter 10, "Generating XML Data from the Database"
Using XPath with Oracle XML DB
Using Oracle XML DB 3-7
<Description>Diabolique</Description>
<Part Id="037429135020" UnitPrice="29.95" Quantity="3"/>
</LineItem>
<LineItem ItemNumber="3">
<Description>8 1/2</Description>
<Part Id="037429135624" UnitPrice="39.95" Quantity="4"/>
</LineItem>
</LineItems>
</PurchaseOrder>
Using existsNode()
The existsNode() syntax is shown in Figure 31.
Figure 31 existsNode() Syntax
Example 34 existsNode() Examples That Find a Node to Match the XPath Expression
Given this sample XML document, the following existsNode() operators return
true (1).
SELECT existsNode(value(X),/PurchaseOrder/Reference)
FROM XMLTABLE X;
SELECT existsNode(value(X),
/PurchaseOrder[Reference="ADAMS-20011127121040988PST"])
FROM XMLTABLE X;
SELECT existsNode(value(X),
/PurchaseOrder/LineItems/LineItem[2]/Part[@Id="037429135020"])
FROM XMLTABLE X;
SELECT existsNode(value(X),
/PurchaseOrder/LineItems/LineItem[Description="8 1/2"])
FROM XMLTABLE X;
EXISTSNODE ( XMLType_instance , XPath_string
namespace
)
,
Using XPath with Oracle XML DB
3-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 35 existsNode() Examples That Do Not Find a Node that Matches the XPath
Expression
The following existsNode() operations do not nd a node that matches the
XPath expression and all return false(0):
SELECT existsNode(value(X),'/PurchaseOrder/UserName')
FROM XMLTABLE X;
SELECT existsNode(value(X),
'/PurchaseOrder[Reference="ADAMS-XXXXXXXXXXXXXXXXXXXX"]')
FROM XMLTABLE X;
SELECT existsNode(value(X),
'/PurchaseOrder/LineItems/LineItem[3]/Part[@Id="037429135020"]')
FROM XMLTABLE X;
SELECT existsNode(value(X),
'/PurchaseOrder/LineItems/LineItem[Description="Snow White"]')
FROM XMLTABLE X;
The most common use for existsNode() is in the WHERE clause of SQL SELECT,
UPDATE, or DELETE statements. In this situation the XPath expression passed to
the existsNode() function is used to determine which of the XML documents
stored in the table will be processed by the SQL statement.
Example 36 Using existsNode() in the WHERE Clause
SELECT count(*)
FROM XMLTABLE x
WHERE existsNode(value(x),'/PurchaseOrder[User="ADAMS"]') = 1;
DELETE FROM XMLTABLE x
WHERE existsNode(value(x),'/PurchaseOrder[User="ADAMS"]') = 1;
commit;
The extractValue() function is used to return the value of a text node or
attribute associated with an XPath Expression from an XML document stored as an
XMLType. It returns a scalar data type.
Using extractValue()
The extractValue() syntax is shown in Figure 32.
Using XPath with Oracle XML DB
Using Oracle XML DB 3-9
Figure 32 extractValue() Syntax
The following are examples of extractValue():
Example 37 Valid Uses of extractValue()
SELECT extractValue(value(x),'/PurchaseOrder/Reference')
FROM XMLTABLE X;
Returns the following:
EXTRACTVALUE(VALUE(X),'/PURCHASEORDER/REFERENCE')
------------------------------------------------------------------------
ADAMS-20011127121040988PST
SELECT extractValue(value(x),
'/PurchaseOrder/LineItems/LineItem[2]/Part/@Id')
FROM XMLTABLE X;
Returns the following:
EXTRACTVALUE(VALUE(X),'/PURCHASEORDER/LINEITEMS/LINEITEM[2]/PART/@ID')
-----------------------------------------------------------------------
037429135020
extractValue() can only return a the value of a single node or attribute value.
For instance the following example shows an invalid use of extractValue(). In
the rst example the XPath expression matches three nodes in the document, in the
second example the Xpath expression identies a nodetree, not a text node or
attribute value.
Example 38 Non-Valid Uses of extractValue()
SELECT extractValue(value(X),
/PurchaseOrder/LineItems/LineItem/Description)
FROM XMLTABLE X;
-- FROM XMLTABLE X;
-- *
-- ERROR at line 3:
-- ORA-19025: EXTRACTVALUE returns value of only one node
EXTRACTVALUE ( XMLType_instance , XPath_string
, value_expr
)
Using XPath with Oracle XML DB
3-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
SELECT extractValue(value(X),
/PurchaseOrder/LineItems/LineItem[1])
FROM XMLTABLE X;
-- FROM XMLTABLE X
-- *
-- ERROR at line 3:
-- ORA-19025: EXTRACTVALUE returns value of only one node
Example 39 Using extractValue() in the WHERE Clause
extractValue() can also be used in the WHERE clause of a SELECT, UPDATE, or
DELETE statement. This makes it possible to performjoins between XMLType tables
or tables containing XMLType columns and other relational tables or XMLType
tables. The following query shows you how to use extractValue() in both the
SELECT list and the WHERE clause:
SELECT extractValue(value(x),/PurchaseOrder/Reference)
FROM XMLTABLE X, SCOTT.EMP
WHERE extractValue(value(x),/PurchaseOrder/User) = EMP.ENAME
AND EMP.EMPNO = 7876;
-- This returns:
-- EXTRACTVALUE(VALUE(X),/PURCHASEORDER/REFERENCE)
-- --------------------------------------------------
-- ADAMS-20011127121040988PST
Using extract()
The extract() syntax is shown in Figure 33.
Figure 33 extract() Syntax
extract() is used when the XPath expression will result in a collection of nodes
being returned. The nodes are returned as an instance of XMLType. The results of
extract() can be either a Document or a DocumentFragment. The functionality
of extract is also available through the XMLType datatypes extract() method.
EXTRACT ( XMLType_instance , XPath_string
namespace
)
,
Using XPath with Oracle XML DB
Using Oracle XML DB 3-11
Example 310 Using extract() to Return an XML Fragment
The following extract() statement returns an XMLType that contains an XML
document fragment containing occurrences of the Description node. These
match the specied XPath expression shown.
set long 20000
SELECT extract(value(X),
/PurchaseOrder/LineItems/LineItem/Description)
FROM XMLTABLE X;
-- This returns:
-- EXTRACT(VALUE(X),/PURCHASEORDER/LINEITEMS/LINEITEM/DESCRIPTION)
-- ------------------------------------------------------------------
-- <Description>The Ruling Class</Description>
-- <Description>Diabolique</Description>
-- <Description>8 1/2</Description>
Example 311 Using extract() to Return a Node Tree that Matches an XPath
Expression
In this example extract() returns the node tree that matches the specied XPath
expression:
SELECT extract(value(X),
'/PurchaseOrder/LineItems/LineItem[1]')
FROM XMLTABLE X;
This returns:
EXTRACT(VALUE(X),'/PURCHASEORDER/LINEITEMS/LINEITEM[1]')
-------------------------------------------------------------------------
<LineItem ItemNumber="1">
<Description>The Ruling Class</Description>
<Part Id="715515012423" UnitPrice="39.95" Quantity="2"/>
</LineItem>
Using XMLSequence()
The XMLSequence() syntax is shown in Figure 34.
Note: In this case the XML is not well formed as it contains more
than one root node.
Using XPath with Oracle XML DB
3-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 34 XMLSequence() Syntax
An XML document fragment can be converted into a set of XMLTypes using the
XMLSequence() function. XMLSequence() takes an XMLType containing a
document fragment and returns a collection of XMLType objects. The collection will
contain one XMLType for each root level node in the fragment. The collection can
then be converted into a set of rows using the SQL TABLE function.
Example 312 Using XMLSequence() and TABLE() to Extract Description Nodes from
an XML Document
The following example shows how to use XMLSequence() and Table() to extract
the set of Description nodes from the purchaseorder document.
set long 10000
set feedback on
SELECT extractValue(value(t),'/Description')
FROM XMLTABLE X,
TABLE ( xmlsequence (
extract(value(X),
'/PurchaseOrder/LineItems/LineItem/Description')
)
) t;
This returns:
EXTRACTVALUE(VALUE(T),'/DESCRIPTION')
-------------------------------------------------------------------------
The Ruling Class
Diabolique
8 1/2
XMLSEQUENCE (
XMLType_instance
sys_refcursor_instance
, fmt
)
Updating XML Documents with updateXML()
Using Oracle XML DB 3-13
Updating XML Documents with updateXML()
The updateXML() syntax is shown in Figure 35.
Figure 35 updateXML() Syntax
You can update XML documents using the updateXML() function. updateXML()
updates an attribute value, node, text node, or node tree. The target for the update
operation is identied using an XPath expression. The following examples show
how you can use updateXML() to modify the contents of an XML Document
stored as an XMLType.
Example 313 Using updateXML() to Update a Text Node Value Identied by an XPath
Expression
This example uses updateXML() to update the value of the text node identied by
the XPath expression /PurchaseOrder/Reference:
UPDATE XMLTABLE t
SET value(t) = updateXML(value(t),
'/PurchaseOrder/Reference/text()',
'MILLER-200203311200000000PST')
WHERE existsNode(value(t),
'/PurchaseOrder[Reference="ADAMS-20011127121040988PST"]') = 1;
This returns:
1 row updated.
SELECT value(t)
FROM XMLTABLE t;
This returns:
VALUE(T)
-------------------------------------------------------------------------
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.oracle.com/xdb/po.xsd">
<Reference>MILLER-200203311200000000PST</Reference>
...
</PurchaseOrder>
UPDATEXML ( XMLType_instance , XPath_string , value_expr namespace )
Updating XML Documents with updateXML()
3-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 314 Using updateXML() to Replace Contents of a Node Tree Associated
with XPath Elements
In this example updateXML() replaces the contents of the node tree associated
with the element identied by the XPath expression
/PurchaseOrders/LineItems/LineItem[2].
UPDATE XMLTABLE t
SET value(t) =
updateXML(value(t),
'/PurchaseOrder/LineItems/LineItem[2]',
xmltype('<LineItem ItemNumber="4">
<Description>Andrei Rublev</Description>
<Part Id="715515009928" UnitPrice="39.95"
Quantity="2"/>
</LineItem>'
)
)
WHERE existsNode(value(t),
'/PurchaseOrder[Reference="MILLER-200203311200000000PST"]'
) = 1;
This returns:
1 row updated.
SELECT value(t)
FROM XMLTABLE t;
And this returns:
VALUE(T)
------------------------------------------------------------------------
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNames
paceSchemaLocation="http://www.oracle.com/xdb/po.xsd">
<Reference>MILLER-200203311200000000PST</Reference>
...
<LineItems>
Note: In this example, since the replacement value is a Node tree,
the third argument to the updateXML() function is supplied as an
instance of the XMLType datatype.
Introducing the W3C XSLT Recommendation
Using Oracle XML DB 3-15
<LineItem ItemNumber="1">
<Description>The Ruling Class</Description>
<Part Id="715515012423" UnitPrice="39.95" Quantity="2"/>
</LineItem>
<LineItem ItemNumber="4">
<Description>Andrei Rublev</Description>
<Part Id="715515009928" UnitPrice="39.95" Quantity="2"/>
</LineItem>
<LineItem ItemNumber="3">
<Description>8 1/2</Description>
<Part Id="037429135624" UnitPrice="39.95" Quantity="4"/>
</LineItem>
</LineItems>
</PurchaseOrder>
Introducing the W3C XSLT Recommendation
The W3C XSLT Recommendation denes an XML language for specifying how to
transform XML documents from one form to another. Transformation can include
mapping from one XML schema to another or mapping from XML to some other
format such as HTML or WML.
Example 315 XSL Stylesheet Example: PurchaseOrder.xsl
The following example, PurchaseOrder.xsl, is an example fragment of an XSL
stylesheet:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xdb="http://xmlns.oracle.com/xdb"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:template match="/">
<html>
<head/>
<body bgcolor="#003333" text="#FFFFCC" link="#FFCC00"
vlink="#66CC99" alink="#669999">
<FONT FACE="Arial, Helvetica, sans-serif">
<xsl:for-each select="PurchaseOrder"/>
<xsl:for-each select="PurchaseOrder">
<center>
See Also: Appendix D, "XSLT Primer" for an introduction to the
W3C XSL and XSLT recommendations.
Using XSL/XSLT with Oracle XML DB
3-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<span style="font-family:Arial; font-weight:bold">
<FONT COLOR="#FF0000">
<B>Purchase Order </B>
</FONT>
</span>
</center>
<br/>
...
<FONT FACE="Arial, Helvetica, sans-serif"
COLOR="#000000">
<xsl:for-each select="Part">
<xsl:value-of select="@Quantity*@UnitPrice"/>
</xsl:for-each>
</FONT>
</td>
</tr>
</tbody>
</xsl:for-each>
</xsl:for-each>
</table>
</xsl:for-each>
</FONT>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Using XSL/XSLT with Oracle XML DB
Oracle XML DB complies with the W3C XSL/XSLT recommendation by supporting
XSLT transformations in the database. In Oracle XML DB, XSLT transformations can
be performed using either of the following:
I XMLTransform() function
I XMLType datatypes transform() method
Since XSL stylesheets are valid XML documents both approaches apply when the
XSL stylesheets are provided as instances of the XMLType datatype. The results of
the XSL transformation are also returned as an XMLType.
See Also: Appendix D, "XSLT Primer" for the full listing of this
XSL stylesheet.
Other XMLType Methods
Using Oracle XML DB 3-17
Because the transformation takes place close to the data, Oracle XML DB can
optimize features such as memory usage, I/O operations, and network trafc
required to perform the transformation.
Example 316 Using transform() to Transform an XSL
The following example shows howtransform() can apply XSLT to an XSL
stylesheet, PurchaseOrder.xsl, to transform the PurchaseOrder.xml
document:
SELECT value(t).transform(xmltype(getDocument('purchaseOrder.xsl')))
from XMLTABLE t
where existsNode(value(t),
'/PurchaseOrder[Reference="MILLER-200203311200000000PST"]'
) = 1;
This returns:
VALUE(T).TRANSFORM(XMLTYPE(GETDOCUMENT('PURCHASEORDER.XSL')))
-------------------------------------------------------------------------
<html>
<head/>
<body bgcolor="#003333" text="#FFFFCC" link="#FFCC00" vlink="#66CC99" alink="#
669999">
<FONT FACE="Arial, Helvetica, sans-serif">
<center>
...
</FONT>
</body>
</html>
Since the transformed document using XSLT is expected as in instance of XMLType,
the source could easily be a database table.
Other XMLType Methods
The following describes additional XMLType methods:
I createXML(). A static method for creating an XMLType instance. Different
signatures allow the XMLType to created from an number of different sources
containing an XML document. Largely replaced by the XMLType constructor in
Oracle9i Release 2 (9.2).
See Also: Chapter 6, "Transforming and Validating XMLType
Data"
Introducing the W3C XML Schema Recommendation
3-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I isFragment(). Returns true (1) if the XMLType contains a document
fragment. A document fragment is an XML document without a Root Node.
Document fragments are typically generated using the extract() function
and method.
I getClobVal(). Returns a CLOB containing an XML document based on the
contents of the XMLType.
I getRootElement(). Returns the name of the root element of the XML
document contained in the XMLType.
I getNameSpace(). Returns the name of the root element of the XML document
contained in the XMLType.
Introducing the W3C XML Schema Recommendation
XML Schema provides a standardized way of dening what the expected contents
of a set of XML documents should be. An XML schema is a an XML document that
denes metadata. This metadata species what the member contents of the
document class should be. The members of a document class can be referred to as
instance documents.
Since an XML schema denition is simply an XML document that conforms to the
class dened by the XML Schema http://www.w3.org/2001/XMLSchema, XML
schemas can be authored using a simple text editor, such as Notepad, vi, a
schema-aware editor, such as the XML editor included with the Oracle9i JDeveloper
tool, or an explicit XML schema authoring tool, such as XMLSpy from Altova
Corporation. The advantage of using a tool such as XMLSpy, is that these tools
allow the XML schema to be developed using an intuitive, graphical editor which
hides much of the details of the XML schema denition from the developer.
Example 317 XML Schema Example, PurchaseOrder.xsd
The following example PurchaseOrder.xsd, is a standard W3C XML Schema
example fragment, in its native form, as an XML Document:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="ActionsType" >
<xs:sequence>
<xs:element name="Action" maxOccurs="4" >
<xs:complexType >
<xs:sequence>
<xs:element ref="User"/>
<xs:element ref="Date"/>
</xs:sequence>
Introducing the W3C XML Schema Recommendation
Using Oracle XML DB 3-19
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="RejectType" >
<xs:all>
<xs:element ref="User" minOccurs="0"/>
<xs:element ref="Date" minOccurs="0"/>
<xs:element ref="Comments" minOccurs="0"/>
</xs:all>
</xs:complexType>
<xs:complexType name="ShippingInstructionsType" >
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="address"/>
<xs:element ref="telephone"/>
</xs:sequence>
...
....
<xs:complexType>
<xs:attribute name="Id" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="12"/>
<xs:maxLength value="14"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="Quantity" type="money"/>
<xs:attribute name="UnitPrice" type="quantity"/>
</xs:complexType>
</xs:element>
</xs:schema>
Using XML Schema with Oracle XML DB
Oracle XML DB supports the use of the W3C XML Schema in two ways.
I Automatic Validation of instance documents
I Denition of Storage models
See Also: Appendix B, "XML Schema Primer" for the detailed
listing of PurchaseOrder.xsd.
Introducing the W3C XML Schema Recommendation
3-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
To use a W3C XML Schema with Oracle XML DB, the XML schema document has
to be registered with the database. Once an XML schema has been registered
XMLType tables and columns can be created which are bound to the schema.
To register an XML schema you must provide two items. The rst is the
XMLSchema document, the second is the URL which will be used by XML
documents which claim to conform to this Schema. This URL will be provided in
the root element of the instance document using either the
noNamespaceSchemaLocation attribute or schemaLocation attribute as
dened in the W3C XML Schema recommendation
XML schemas are registered using methods provided by PL/SQL package DBMS_
XMLSCHEMA. Schemas can be registered as global or local schemas. See Chapter 5,
"Structured Mapping of XMLType" for a discussion of the differences between
Global and Local Schemas.
Oracle XML DB provides a number of options for automatically generating default
database objects and Java classes as part of the schema registration process. Some of
these options are discussed later in this section.
Example 318 Registering PurchaseOrder.xsd as a Local XML Schema Using
registerSchema()
The following example shows how to register the preceding PurchaseOrder.xsd
XML schema as a local XML schema using the registerSchema() method.
begin
dbms_xmlschema.registerSchema(
http://www.oracle.com/xsd/purchaseOrder.xsd,
getDocument(PurchaseOrder.xsd),
TRUE, TRUE, FALSE, FALSE
);
end;
/
--This returns:
-- PL/SQL procedure successfully completed.
The registerSchema() procedure causes Oracle XML DB to perform the
following operations:
I Parse and validate the XML schema
I Create a set of entries in Oracle Data Dictionary that describe the XML schema
Introducing the W3C XML Schema Recommendation
Using Oracle XML DB 3-21
I Create a set of SQL object denitions, based on the complexTypes dened in the
XML schema
Once the XML schema has been registered with Oracle XML DB, it can be
referenced when dening tables that contain XMLType columns, or creating
XMLType tables.
Example 319 Creating an XMLType Table that Conforms to an XML Schema
This example shows how to create an XMLType table which can only contain XML
Documents that conform to the denition of the PurchaseOrder element in the
XML schema registered at
http://www.oracle.com/xsd/purchaseorder.xsd.
CREATE TABLE XML_PURCHASEORDER of XMLType
XMLSCHEMA "http://www.oracle.com/xsd/purchaseOrder.xsd"
ELEMENT "PurchaseOrder";
This results in:
Table created.
DESCRIBE XML_PURCHASEORDER
Returns the following:
Name Null? Type
----------------------------------------- -------- ----------------------------
TABLE of SYS.XMLTYPE(XMLSchema "http://www.oracle.com/xsd/purchaseOrder.xsd"
Element "PurchaseOrder") STORAGE Object-relational TYPE "PurchaseOrder538_T"
XMLSchema-Instance Namespace
Oracle XML DB must recognize that the XML document inserted into an XML
schema-based table or column is a valid member of the class of documents dened
by the XML schema. The XML document must correctly identify the XML schema
or XML schemas it is associated with.
This means that XML schema, for each namespace used in the document, must be
identied by adding the appropriate attributes to the opening tag for the root
element of the document. These attributes are dened by W3C XML Schema
recommendation and are part of the W3C XMLSchema-Instance namespace.
Consequently in order to dene these attributes the document must rst declare the
XMLSchema-instance namespace. This namespace is declared as follows:
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance:
Validating an XML Document Using an XML Schema
3-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Once the XMLSchema-instance namespace has been declared and given a
namespace prex the attributes that identify the XML schema can be added to the
root element of the instance document. A given document can be associated with
one or more XML schemas. In the preceding example, the namespace prex for the
XMLSchema-instance namespace was dened as xsi.
noNameSpaceSchemaLocation Attribute. The XML schema associated with the
unqualied elements is dened using the attribute
noNamespaceSchemaLocation. In the case of the PurchaseOrder.xsd XML
schema, the correct denition would be as follows:
<PurchaseOrder
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:noNamespaceSchemaLocation="http://www.oracle.com/xsd/purchaseOrder.xsd">
Using Multiple Namespaces: schemaLocation Attribute. If the XML document uses
multiple namespaces then each namespace needs to be identied by a
schemaLocation attribute. For example, assuming that the Purchaseorder
document used the namespace PurchaseOrder, and the PurchaseOrder
namespace is given the prex po. The denition of the root element of a
PurchaseOrder document would then be as follows:
<po:PurchaseOrder
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:po=PurchaseOrder
xsi:schemaLocation="PurchaseOrder
http://www.oracle.com/xsd/purchaseOrder.xsd">
Validating an XML Document Using an XML Schema
By default Oracle XML DB performs a minimum amount of validation when a
storing an instance document. This minimal validation ensures that the structure of
the XML document conforms to the structure specied in the XML schema.
Example 320 Attempting to Insert an Invoice XML Document Into an XMLType Table
Conforming to PurchaseOrder XML Schema
The following example shows what happens when an attempt is made to insert an
XML Document containing an invoice into a XMLType table that is dened as
storing documents which conform to the PurchaseOrder Schema
INSERT INTO XML_PURCHASEORDER
values (xmltype(getDocument('Invoice.xml')))
values (xmltype(getDocument('Invoice.xml')))
Validating an XML Document Using an XML Schema
Using Oracle XML DB 3-23
*
This returns:
ERROR at line 2:
ORA-19007: Schema and element do not match
The reason for not performing full instance validation automatically is based on the
assumption that, in the majority of cases it is likely that schema based validation
will have been performed prior to attempting to insert the XML document into the
database.
In situations where this is not the case, full instance validation can be enabled using
one of the following approaches:
I A table level CHECK constraint
I A PL/SQL BEFORE INSERT trigger
Example 321 Using CHECK Constraints in XMLType Tables
This example shows how to use a CHECK constraint to an XMLType table and the
result of attempting to insert an invalid document into the table:
ALTER TABLE XML_PURCHASEORDER
add constraint VALID_PURCHASEORDER
check (XMLIsValid(sys_nc_rowinfo$)=1);
-- This returns:
-- Table altered
INSERT INTO XML_PURCHASEORDER
values (xmltype(getDocument(InvalidPurchaseOrder.xml)));
INSERT INTO XML_PURCHASEORDER;
*
-- This returns:
-- ERROR at line 1:
-- ORA-02290: check constraint (DOC92.VALID_PURCHASEORDER) violated
Example 322 Using BEFORE INSERT Trigger to Validate Data Inserted Into XMLType
Tables
The next example shows how to use a BEFORE INSERT trigger to validate that the
data being inserted into the XMLType table conforms to the specied schema
CREATE TRIGGER VALIDATE_PURCHASEORDER
before insert on XML_PURCHASEORDER
for each row
Storing XML: Structured or Unstructured Storage
3-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
declare
XMLDATA xmltype;
begin
XMLDATA := :new.sys_nc_rowinfo$;
xmltype.schemavalidate(XMLDATA);
end;
/
-- This returns:
-- Trigger created.
insert into XML_PURCHASEORDER
values (xmltype(getDocument(InvalidPurchaseOrder.xml)));
-- values (xmltype(getDocument(InvalidPurchaseOrder.xml)))
-- *
-- ERROR at line 2:
-- ORA-31154: invalid XML document
-- ORA-19202: Error occurred in XML processing
-- LSX-00213: only 0 occurrences of particle "User", minimum is 1
-- ORA-06512: at "SYS.XMLTYPE", line 0
-- ORA-06512: at "DOC92.VALIDATE_PURCHASEORDER", line 5
-- ORA-04088: error during execution of trigger DOC92.VALIDATE_PURCHASEORDER
As can be seen both approaches ensure that only valid XML documents can be
stored in the XMLType table:
I Table CHECKConstraint. The TABLE constraint approachs advantage is that it
is simpler to code. Its disadvantage is that, since it is based on the
isSchemaValid() method, it can only indicate whether or not the instance
document is valid. When the instance document is not valid it cannot give any
information as to why a document is invalid.
I BEFORE INSERT Trigger. The BEFORE INSERT trigger requires a little more
coding. Its advantage is that it is based on the schemaValidate() method.
This means that when the instance document is not valid it can provide
information about what was wrong with the instance document. It also has the
advantage of allowing the trigger to take corrective action when appropriate.
Storing XML: Structured or Unstructured Storage
When designing an Oracle XML DB application you must rst decide whether the
XMLType columns and table will be stored using structured or unstructured storage
techniques.
Storing XML: Structured or Unstructured Storage
Using Oracle XML DB 3-25
Table 31 compares using structured and structured storage to store XML.
Table 31 Comparing Structured and Unstructured XML Storage
Feature Unstructured XML Storage Structured XML Storage
Storage technique Contents of XMLType columns and tables are
stored using the CLOB data type.
Contents of XMLType columns and tables are
stored as a collection of SQL objects. By
default, the underlying storage model for
XML schema-based XMLType columns and
tables is structured storage.
Can store
non-XML
schema-based
tables?
Only option available for XMLType tables
and columns that are not associated with an
XML schema.
Can only be used when the XMLType
column or table is based on an XML schema.
This means that the instance documents
must conform to the underlying XML
schema.
Performance:
Storage and
retrieval speed
It allows for higher rates of ingestion and
retrieval, as it avoids the overhead associated
with parsing and recomposition during
storage and retrieval operations.
Results in a slight overhead during ingestion
and retrieval operations in that the
document has to be shredded during
ingestion and re-constituted prior to
retrieval.
Performance:
operation speed
Slower than for structured storage. When an XML schema is registered, Oracle
XML DB generates a set of SQL objects that
correspond to complexTypes dened in the
XML schema. XPath expressions sent to
Oracle XML DB functions are translated to
SQL statements that operate directly against
the underlying objects.
This re-writing of XMLType operations into
object-relational SQL statements results in
signicant performance improvements
compared with performing the same
operations against XML documents stored
using unstructured storage.
Flexible. Can
easily process
varied content?
Allows for a great deal of exibility in the
documents being processed making it an
appropriate choice when the XML
documents contain highly variable content.
Leverages the object-relational capabilities of
the Oracle9i database.
Storing XML: Structured or Unstructured Storage
3-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Memory usage:
Do the XML
documents need
parsing?
Oracle XML DB must parse the entire XML
document and load it into an in-memory
DOM structure before any validation, XSL
Transformation, or XPath operations can be
performed on it.
Allows Oracle XML DB to minimize memory
usage and optimize performance of
DOM-based operations on XMLType table
and columns by using:
I Lazy Manifestation (LM): Occurs when
Oracle XML DB constructs a DOM
structure based on an XML document.
With LM, instead of constructing the
whole DOM when the document is
accessed, Oracle XML DB only
instantiates the nodes required to
perform the immediate operation. As
other parts of the document are required
the appropriate node trees are
dynamically loaded into the DOM.
I Least Recently Used (LRU): Strategy to
discard nodes in the DOM that have not
been accessed recently.
Update
processing
When stored, any update operations on the
document will result in the entire CLOB
being re-written.
If any part of the document is updated using
updateXML() then the entire document has
to be fetched from the CLOB, updated, and
written back to the CLOB.
Can update individual elements, attributes,
or nodes in an XML document without
rewriting the entire document.
Possible to re-write the updateXML()
operation to an SQL UPDATE statement that
operates on columns or objects referenced by
the XPATH expression.
Indexing You can use B*Tree indexes based on the
functional evaluation of XPath expressions
or Oracle Text inverted list indexes.
Unstructured storage make it impossible to
create B*TREE indexes based on the values
of elements or attributes that appear within
collections.
You can use B*Tree indexes and Oracle Text
inverted list indexes.
By tuning the way in which collections are
managed, indexes can be created on any
element or attribute in the document,
including elements or attributes that appear
with collections.
Table 31 Comparing Structured and Unstructured XML Storage (Cont.)
Feature Unstructured XML Storage Structured XML Storage
Storing XML: Structured or Unstructured Storage
Using Oracle XML DB 3-27
Data Manipulation Language (DML) Independence
Oracle XML DB ensures that all Data Manipulation Language (DML) operations
based on Oracle XML DB functions return consistent results. By abstracting the
storage model through the use of the XMLType datatype, and providing a set of
operators that use XPath to perform operations against XML documents, Oracle
XML DB makes it possible for you to switch between structured and unstructured
storage, and to experiment with different forms of structured storage without
affecting the application.
DOM Fidelity in Structured and Unstructured Storage
To preserve DOM delity a system must ensure that a DOM generated from the
stored representation of an XML Document is identical to a DOM generated from
Space needed Can be large. Since based on XML schema, it is not
necessary for Oracle XML DB to store XML
tag names when storing the contents of XML
documents. This can signicantly reduce the
storage space required.
Data integrity -- Makes it possible to use a set of
database integrity constraints that allow
the contents of an XML document to be
validated against information held
elsewhere in the database.
Tuning:
Fine-grained
object control
None You can annotate XML schema, for ne grain
control over sets of SQL objects generated
from XML schema and how these objects are
stored in the database.
You can control how collections are
managed, dene tablespace usage, and
partitioning of table or tables used to store
and manage the SQL objects. This makes it
possible to ne tune the performance of the
Oracle XML DB to meet the needs of the
application.
Other annotations control how Simple
elements and attributes are mapped to SQL
columns
Table 31 Comparing Structured and Unstructured XML Storage (Cont.)
Feature Unstructured XML Storage Structured XML Storage
Structured Storage: XML Schema-Based Storage of XMLType
3-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
the original XML document. Preserving DOM integrity ensures that none of the
information contained in the XML Document is lost as a result of storing it.
The problemwith maintaining DOMintegrity is that an XML document can contain
a lot of information in addition to the data contained in element and attribute
values. Some of this information is explicitly provided, using Comments and
Processing Instructions. Other information can be implicitly provided, such as:
I Ordering of the elements in a collection
I Ordering of child elements within the parent
I Relative position of Comments and Processing Instructions
One of the common problems application developers face when using a traditional
relational model to manage the contents of XML documents is how to preserve this
information. Table 32 compares DOM delity in structured and unstructured
storage:
Structured Storage: XML Schema-Based Storage of XMLType
Logically, an XML document consists of a collection of elements and attributes.
Elements can be either of the following:
I complexTypes, containing child elements and attributes
I simpleTypes, containing scalar values
An XML schema denes the set of elements and attributes that can exist in a
particular class of XML document and denes the relationships between them.
Table 32 DOM Fidelity: Unstructured and Structured Storage
DOM Fidelity with Unstructured Storage DOM Fidelity with Structured Storage
Relational systems do not provide any implicit
ordering, nor do they provide the exibility to
make it easy to preserve out of band data such as
comments and processing instructions. With a
typical relational database, the only way to
preserve DOM Fidelity is to store the source
document using unstructured storage techniques
Oracle XML DB can preserve DOMFidelity even
with structured storage. When an XML
Document is shredded and stored using
structured storage techniques, the Comments,
Processing Instructions, and any ordering
information implicit in the source document is
preserved as part of the SQL objects that are
created when the document is shredded. When
the document is retrieved this information is
incorporated back into the generated XML
document.
Structured Storage: XML Schema-Based Storage of XMLType
Using Oracle XML DB 3-29
During XML schema registration, Oracle XML DB generates an SQL Object Type for
each complexType dened in the XML schema. The denition of the SQL object
mirrors the denition of the complexType.
Each child element and attribute dened by the complexType maps to an attribute
of the SQL object type.
I If a child element in the complexType is itself a complexType, the datatype of
the corresponding SQL attribute will be the appropriate SQL type.
I If the child element is a simpleType or attribute, based on one of the scalar
datatypes dened by the W3C XML Schema recommendation, then the
datatype of the corresponding SQL attribute will be the appropriate primitive
SQL data type.
XML Schema Names and Defining Oracle XML DB Namespace
By default SQL Objects generated when an XML schema is registered are given
system-generated names. However, with Oracle XML DB you can specify the names
of SQL objects by annotating the schema. To annotate an XML schema, you must
rst include the Oracle XML DB namespace in the XMLSchema tag, dened as:
http://xmlns.oracle.com/xdb
Hence an XML schema using Oracle XML DB annotations, must contain the
following attributes in the XMLSchema tag:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema
xmlns:xdb="http://xmlns.oracle.com/xdb" >
...
</xs:schema>
Once Oracle XML DB namespace has been dened, the annotations dened by
Oracle XML DB can be used.
Example 323 Dening the Name of SQL Objects Generated from complexTypes
This example uses xdb:SQLType to dene the name of the SQL object generated
fromcomplexType PurchaseOrder, as XML_PURCHASEORDER_TYPE.
<xs:element name="PurchaseOrder">
<xs:complexType type="PurchaseOrderType"
xdb:SQLType="XML_PURCHASEORDER_TYPE">
<xs:sequence>
<xs:element ref="Reference"/>
<xs:element name="Actions" type="ActionsType"/>
Structured Storage: XML Schema-Based Storage of XMLType
3-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<xs:element name="Reject" type="RejectType" minOccurs="0"/>
<xs:element ref="Requestor"/>
<xs:element ref="User"/>
<xs:element ref="CostCenter"/>
<xs:element name="ShippingInstructions"
type="ShippingInstructionsType"/>
<xs:element ref="SpecialInstructions"/>
<xs:element name="LineItems" type="LineItemsType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
So executing the following statement:
DESCRIBE XML_PURCHASEORDER_TYPE
XML_PURCHASEORDER_TYPE is NOT FINAL;
Returns the following structure:
Name Null? Type
------------------------------ -------- ----------------------------
SYS_XDBPD$ XDB.XDB$RAW_LIST_T
Reference VARCHAR2(26)
Actions XML_ACTIONS_TYPE
Reject XML_REJECTION_TYPE
Requestor VARCHAR2(128)
User VARCHAR2(10)
CostCenter VARCHAR2(4)
ShippingInstructions XML_SHIPPINGINSTRUCTIONS_TYPE
SpecialInstructions VARCHAR2(2048)
LineItems XML_LINEITEMS_TYPE
Using xdb:SQLName to Override Default Names
Oracle XML DB uses a predened algorithm to generate valid SQL names from the
names of the XML elements, attributes, and types dened in the XML schema. The
xdb:SQLName annotation can be used to override the default algorithmand supply
explicit names for these items.
Note: In the preceding example, xdb:SQLType annotation was
also used to assign names to the SQL types that correspond to the
complexTypes: ActionsType, ShippingInstructionsType
and LineItemsType.
Structured Storage: XML Schema-Based Storage of XMLType
Using Oracle XML DB 3-31
Using xdb:SQLType to Override Default Mapping
Oracle XML DB also provides a default mapping between scalar datatypes dened
by the XML Schema recommendation and the primitive datatype dened by SQL.
Where possible the size of the SQL datatype is derived from restrictions dened for
the XML datatype. If required, the xdb:SQLType annotation can be used to
override this default mapping:
Example 324 Using xdb:SQLType and xdb:SQLName to Specify the Name and
Mapping of Objects Generated from complexTypes
This example shows how to override the name and type used for the
SpecialInstructions element and the effect these changes have on the
generated SQL Object type.
<xs:element name="SpecialInstructions" xdb:SQLType="CLOB" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="0"/>
<xs:maxLength value="2048"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="PurchaseOrder">
<xs:complexType type="PurchaseOrderType"
xdb:SQLType="XML_PURCHASEORDER_TYPE">
<xs:sequence>
<xs:element ref="Reference"/>
<xs:element name="Actions" type="ActionsType"/>
<xs:element name="Reject" type="RejectType" minOccurs="0"/>
<xs:element ref="Requestor"/>
<xs:element ref="User"/>
<xs:element ref="CostCenter"/>
<xs:element name="ShippingInstructions"
type="ShippingInstructionsType"/>
<xs:element ref="SpecialInstructions"
xdb:SQLName="SPECINST"/>
<xs:element name="LineItems" type="LineItemsType"/>
Note: The override for the name of the SpecialInstructions
element is applied where the element is used, inside the
PurchaseOrderType, not where it is dened
Structured Storage: XML Schema-Based Storage of XMLType
3-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</xs:sequence>
</xs:complexType>
</xs:element>
On executing the following statement:
DESCRIBE XML_PURCHASEORDER_TYPE
XML_PURCHASEORDER_TYPE is NOT FINAL
The following structure is returned:
Name Null? Type
------------------------------ -------- ----------------------------
SYS_XDBPD$ XDB.XDB$RAW_LIST_T
Reference VARCHAR2(26)
Actions XML_ACTIONS_TYPE
Reject XML_REJECTION_TYPE
Requestor VARCHAR2(128)
User VARCHAR2(10)
CostCenter VARCHAR2(4)
ShippingInstructions XML_SHIPPINGINSTRUCTIONS_TYPE
SPECINST CLOB
LineItems XML_LINEITEMS_TYPE
Structured Storage: Storing complexType Collections
One issue you must consider when selecting structured storage, is what techniques
to use to manage Collections. Different approaches are available and each approach
offers different benets. Generally, you can handle Collections in ve ways:
I CLOBS. If a complexType is dened with xdb:SQLType=CLOB then the
type, and all child elements are stored using unstructured storage techniques
I Inline VARRAYS. If no other information is given for a complexType which
occurs more than once, the members of the collection are stored as a set of
serialized objects in-line as part of the SQL object for the parent element. You
cannot create B*Tree indexes on elements or attributes which are part of
collection
I Nested Object Tables. The members of the collection are stored in a nested
object table. The SQL object, as in previous option, contains an attribute of type
VARRAY, but is stored as a table. The parent row contains a unique setid (set
identier) value which is used to associate with the corresponding nested table
rows.
Structured Storage: XML Schema-Based Storage of XMLType
Using Oracle XML DB 3-33
I Separate XMLType Table. The members of the collection are stored as a
separate XMLType table. Each member of the collection is stored as a row in the
table. The Parent SQL object contains an array of refs which point to the rows in
the child table which belong to this parent. All data is XMLType.
I Creating multiple XMLType columns based on the XML schema
I Linking from a child to the corresponding parent
I Separate XMLType Table with Link Table. The members of the collection are
stored as a separate XMLType table. An link table is created which cross
references which member in the child table are linked to which members of the
parent. Table. All data is visible as XMLTypes. Possible to link from the child
back to the parent. Problems with creating multiple XMLType columns based on
the Schema.
Structured Storage: Data Integrity and Constraint Checking
In addition to schema-validation, structured storage makes it possible to introduce
traditional relational constraints on to XMLType columns and Tables. With database
integrity checking you can perform instance validation beyond what is achievable
with XML Schema-based validation.
The W3C XML Schema Recommendation only allows for validation based on
cross-referencing of values with an instance document. With database integrity
checking you can enforce other kinds of validation, such as enforcing the
uniqueness of a element or attribute across a collection of documents, or validating
the value of a element or attribute against information stored elsewhere in the
database.
Example 325 Adding a Unique and Referential Constraint to Table Purchaseorder
The following example shows how you can introduce a Unique and Referential
Constraint on the PurchaseOrder table.
XMLDATA.SQLAttributeName
alter table XML_PURCHASEORDER
add constraint REFERENCE_IS_UNQIUE
-- unique(extractValue(/PurchaseOrder/Reference))
See Also: Chapter 5, "Structured Mapping of XMLType"
Note: In Oracle9i Release 2 (9.2) constraints have to be specied
using object-relational syntax.
Structured Storage: XML Schema-Based Storage of XMLType
3-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
unique (xmldata."Reference");
alter table XML_PURCHASEORDER
add constraint USER_IS_VALID
-- foreign key extractValue(/PurchaseOrder/User) references
SCOTT.EMP(ENAME)
foreign key (xmldata."User") references SCOTT.EMP(ENAME);
As can be seen, when an attempt is made to insert an XML Document that contains
a duplicate value for the element /PurchaseOrder/Reference into the table, the
database detects that the insert would violate the unique constraint, and raises the
appropriate error.
insert into xml_purchaseorder values (
xmltype(getDocument(ADAMS-20011127121040988PST.xml))
);
This returns:
1 row created.
insert into xml_purchaseorder values (
xmltype(getDocument(ADAMS-20011127121040988PST.xml))
);
insert into xml_purchaseorder values (
*
This returns:
ERROR at line 1:
ORA-00001: unique constraint (DOC92.REFERENCE_IS_UNQIUE) violated
Example 326 How Oracle9i Database Enforces Referential Constraint User_Is_Valid
The following example shows how the database will enforce the referential
constraint USER_IS_VALID, which states that the value of the element
/PurchaseOrder/User, that translates to the SQLAttribute xmldata.user,
must match one of the values of ENAME in SCOTT.EMP.
insert into xml_purchaseorder values (
xmltype(getDocument(HACKER-20011127121040988PST.xml))
);
insert into xml_purchaseorder values (
*
Oracle XML DB Repository
Using Oracle XML DB 3-35
This returns:
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.USER_IS_VALID)
violated - parent key notfound
Oracle XML DB Repository
XML documents are by nature hierarchical animals. The information they contain is
represented by a hierarchy of elements, child elements, and attributes. XML
documents also view the world around them as a hierarchy. When an XML
document refers to another XML document, or any other kind of document, it does
so using a URL. URLs can be either relative or absolute. In either case, the URL
denes a path to the target document. The path is expressed in terms of a folder
hierarchy.
Oracle XML DB Repository makes it possible to view all of XML content stored in
the database using a File / Folder metaphor. The Repository provides support for
basic operations such as creating les and folders as well as more advanced features
such as version and access control.
The Repository is fully accessible, queryable, and updatable through SQL. It can
also be directly accessed through industry standard protocols such as HTTP,
WebDAV, and FTP.
Introducing the IETF WebDAV Standard
WebDAV is an Internet Engineering Task Force (IETF) Standard for Distributed
Authoring and Versioning of content. The standard is implemented by extending
the HTTP protocol allowing a Web Server to act as a File Server in a distributed
environment.
Oracle XML DB Repository is Based on WebDAV
Oracle XML DB Repository is based on the model dened by the WebDAV
standard. It uses the WebDAV resource model to dene the basic metadata that is
maintained for each document stored in the Repository. The WebDAV protocol uses
XML to transport metadata between the client and the server.
Hence, you can easily create, edit, and access documents stored in Oracle XML DB
Repository using standard tools. For example, you can use:
I Microsoft Web Folders
See Also: Chapter 13, "Oracle XML DB Foldering"
Oracle XML DB Repository
3-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Other WebDAV-enabled products, such as Microsoft Ofce, Macromedia, and
the Adobe range of authoring tools.
WebDAV uses the termResource to dene a le or folder. It denes a set of basic
operations that can be performed on a Resource. These operations require a
WebDAV server to maintain a set of basic metadata for each Resource. Oracle XML
DB exposes this metadata as a set of XML Documents in the following form:
Example 327 Oracle XML DB Exposes WebDAV Resource Metadata as XML
Documents
<Resource xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"
Hidden="false" Invalid="false" Container="false"
CustomRslv="false">
<CreationDate> 2002-02-14T16:01:01.066324000</CreationDate>
<ModificationDate> 2002-02-14T16:01:01.066324000</ModificationDate>
<DisplayName>testFile.xml</DisplayName>
<Language>us english</Language>
<CharacterSet>utf-8</CharacterSet>
<ContentType>text/xml</ContentType>
<RefCount>1</RefCount>
<ACL>
<acl description="/sys/acls/all_all_acl.xml"
xmlns="http://xmlns.oracle.com/xdb/acl.xsd"
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation="http://xmlns.oracle.com/xdb/acl.xsd
http://xmlns.oracle.com/xdb/acl.xsd">
<ace>
<grant>true</grant>
<privilege>
<all/>
</privilege>
<principal>PUBLIC</principal>
</ace>
</acl>
</ACL>
<Owner>DOC92</Owner>
<Creator>DOC92</Creator>
<LastModifier>DOC92</LastModifier>
<SchemaElement>
http://xmlns.oracle.com/xdb/XDBSchema.xsd#binary
</SchemaElement>
<Contents>
<binary>02C7003802C77B7000081000838B1C240000000002C71E7C</binary>
</Contents>
Query-Based Access to Oracle XML DB Repository
Using Oracle XML DB 3-37
</Resource>
Query-Based Access to Oracle XML DB Repository
Oracle XML DB exposes the Repository to SQL developers as two views:
I RESOURCE_VIEW
I PATH_VIEW
It also provides a set of SQL functions and PL/SQL packages for performing
Repository operations.
Using RESOURCE_VIEW
RESOURCE_VIEW is the primary way for querying Oracle XML DB Repository.
There is one entry in the RESOURCE_VIEW for each document stored in the
Repository. The RES column contains the resource entry for the document, the ANY_
PATH entry provides a valid folder path from the root to the resource.
The denition of the RESOURCE_VIEW is:
SQL> describe RESOURCE_VIEW
Name Null? Type
------------------------------- -------- ----------------------------
RES SYS.XMLTYPE
ANY_PATH VARCHAR2(4000)
Using PATH_VIEW
PATH_VIEW contains an entry for each Path in the Repository. Since a Resource can
be linked into more than one folder, PATH_VIEW shows all possible Paths in the
Repository and the resources they point to. The denition of the PATH_VIEW is:
SQL> describe PATH_VIEW
Name Null? Type
------------------------------- -------- ----------------------------
PATH VARCHAR2(1024)
RES SYS.XMLTYPE
LINK SYS.XMLTYPE
See Also: Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
Query-Based Access to Oracle XML DB Repository
3-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Creating New Folders and Documents
You can create new folders and documents using methods provided by DBMS_XDB
package. For example, a new folder can be created using the procedure
createFolder() and a le can be uploaded into that folder using
createResource(). The following examples show you how to do this:
Example 328 Creating a Repository Resource and Folder
SQL> declare
2 result boolean;
3 begin
4 result := dbms_xdb.createFolder('/public/testFolder');
5 end;
6 /
PL/SQL procedure successfully completed.
SQL> declare
2 result boolean;
3 begin
4 result := dbms_xdb.createResource(
5 '/public/testFolder/testFile.xml',
6 getDocument('testFile.xml')
7 );
8 end;
9 /
PL/SQL procedure successfully completed.
Querying Resource Documents
RESOURCE_VIEW can be queried just like any other view. Oracle XML DB provides
a new operator, UNDER_PATH, that provides a way for you to restrict queries to a
particular folder tree within the RESOURCE_VIEW.
extractValue() and existsNode() can be used on the Resource documents
when querying the RESOURCE_VIEW and PATH_VIEW Resource documents.
Updating Resources
You can update Resources using updateXML().
Query-Based Access to Oracle XML DB Repository
Using Oracle XML DB 3-39
Example 329 Updating Repository Resources
For example, the following query updates the OWNER and NAME of the document
created in the previous example.
update RESOURCE_VIEW
set RES=updateXML(RES,
/Resource/DisplayName/text(),RenamedFile,
/Resource/Owner/text(),SCOTT
)
where any_path = /public/testFolder/testFile.xml;
-- 1 row updated.
select r.res.getClobVal()
from RESOURCE_VIEW r
where ANY_PATH = /public/testFolder/testFile.xml
/
-- Results in:
-- R.RES.GETCLOBVAL()
-- ----------------------------------------------------------------------
-- <Resource xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"
-- Hidden="false" Invalid="false" Container="false"
-- CustomRslv="false">
-- <CreationDate> 2002-02-14T16:01:01.066324000</CreationDate>
-- <ModificationDate> 2002-02-14T21:36:39.579663000</ModificationDate>
-- <DisplayName>RenamedFile</DisplayName>
-- <Language>us english</Language>
-- <CharacterSet>utf-8</CharacterSet>
-- <ContentType>text/xml</ContentType>
-- <RefCount>1</RefCount>
-- <ACL>
-- ...
-- </ACL>
-- <Owner>SCOTT</Owner>
-- <Creator>DOC92</Creator>
-- <LastModifier>DOC92</LastModifier>
-- </Resource>
Deleting Resources
Resource can be deleted using deleteResource(). If the resource is a folder then
the folder must be empty before it can be deleted.
Storage Options for Resources
3-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 330 Deleting Repository Resources
The following examples show the use of the deleteResource() procedure.
call dbms_xdb.deleteResource('/public/testFolder')
/
call dbms_xdb.deleteResource('/public/testFolder')
*
ERROR at line 1:
ORA-31007: Attempted to delete non-empty container /public//testFolder
ORA-06512: at "XDB.DBMS_XDB", line 151
ORA-06512: at line 1
call dbms_xdb.deleteResource('/public/testFolder/testFile.xml')
/
Call completed.
call dbms_xdb.deleteResource('/public/testFolder')
/
Call completed.
Storage Options for Resources
RESOURCE_VIEW and PATH_VIEW are based on tables stored in Oracle XML DB
database schema. The metadata exposed through RESOURCE_VIEW and PATH_
VIEW is stored and managed using a set of tables in Oracle XML DB-supplied XML
schema, XDBSchema.xsd. The contents of the les are stored as BLOB or CLOB
columns in this XML schema.
Dening Your Own Default Table Storage for XML Schema-Based
Documents
There is an exception to this storage paradigm when storing XML schema-based
XML documents. When an XML schema is registered with Oracle XML DB you can
de ne a default storage table for each root element dened in the XML schema.
You can dene your own default storage tables by adding an xdb:defaultTable
attribute to the denition of the top level element When the schema is registered,
Oracle XML DB establishes a link between the Repository and the default tables
See Also: Appendix G, "Example Setup scripts. Oracle XML DB -
Supplied XML Schemas", "xdbcong.xsd: XML Schema for
Conguring Oracle XML DB" on page G-18
Defining Your Own Default Table Storage for XML Schema-Based Documents
Using Oracle XML DB 3-41
dened by your XML schema. You can choose to generate the default tables as part
of the XML schema registration.
Your Default Table is an XMLType Table and Hierarchically Enabled
A default table is an XMLType table, that is, it is an object table based on the
XMLType datatype. When an XML document, with a root element and XML schema
that match your default tables root element and XML schema, is inserted into the
Repository, the XML content is stored as a row in the specied default table. A
resource is created that contains a reference to the appropriate row in the default
table.
One of the special features of an XMLType table is that it can be hierarchically enabled.
Default Tables, created as part of XML schema registration are automatically
hierarchically enabled. When a table is hierarchically enabled DML operations on
the default table may cause corresponding operations on the Oracle XML DB
Repository. For example, when a row is deleted from the default table, any entries
in the Repository which reference that row are deleted.
Example 331 Adding the xdb:defaultTable Attribute to the XML Schemas Element
Denition
The following example shows the result of adding an xdb:defaultTable
attribute to the XML schema denitions PurchaseOrder element and then
registering the XML schema with the Create Table option set to TRUE:
<xs:element name="PurchaseOrder" xdb:defaultTable="XML_PURCHASEORDER">
<xs:complexType type="PurchaseOrderType"
xdb:SQLType="XML_PURCHASEORDER_TYPE">
<xs:sequence>
<xs:element ref="Reference"/>
<xs:element name="Actions" type="ActionsType"/>
<xs:element name="Reject" type="RejectType" minOccurs="0"/>
<xs:element ref="Requestor"/>
<xs:element ref="User"/>
<xs:element ref="CostCenter"/>
<xs:element name="ShippingInstructions"
type="ShippingInstructionsType"/>
<xs:element ref="SpecialInstructions"
xdb:SQLName="SPECINST"/>
<xs:element name="LineItems" type="LineItemsType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Defining Your Own Default Table Storage for XML Schema-Based Documents
3-42 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
SQL> begin
2 dbms_xmlschema.registerSchema(
3 'http://www.oracle.com/xsd/purchaseOrder.xsd',
4 getDocument('purchaseOrder3.xsd'),
5 TRUE, TRUE, FALSE, TRUE
6 );
7
8 end;
9 /
PL/SQL procedure successfully completed.
SQL> describe XML_PURCHASEORDER
Name Null? Type
------------------------------- -------- ----------------------------
TABLE of SYS.XMLTYPE(XMLSchema
http://www.oracle.com/xsd/purchaseOrder.xsd Element "PurchaseOrder")
STORAGE Object-relational TYPE "XML_PURCHASEORDER_TYPE"
Example 332 Inserting an XML Document into Oracle XML DB Repository Causes a
Insertion of a Row into the Table
The following example shows how, once the XML schema is registered, and the
default table created, when inserting an XML document into Oracle XML DB
Repository causes a row to be inserted into the designated default table:
select count(*) from XML_PURCHASEORDER;
Results in:
COUNT(*)
----------
0
-- create testFolder
declare
result boolean;
begin
result := dbms_xdb.createFolder(/public/testFolder);
end;
/
declare
result boolean;
begin
Defining Your Own Default Table Storage for XML Schema-Based Documents
Using Oracle XML DB 3-43
result := dbms_xdb.createResource(
/public/testFolder/purchaseOrder1.xml,
getDocument(purchaseOrder1.xml)
);
end;
/
-- PL/SQL procedure successfully completed.
commit;
-- Commit complete.
select count(*) from XML_PURCHASEORDER;
Results in:
COUNT(*)
----------
1
Example 333 Deleting a Row Causes Deletion of Corresponding Entry from the
Repository
This example shows when deleting a row from the hierarchy-enabled default table,
the corresponding entry is deleted from the hierarchy:
select extractValue(res,'Resource/DisplayName') "Filename"
from RESOURCE_VIEW where under_path(res,'/public/testFolder') = 1;
/
Results in:
Filename
----------------------------------------------------------------------
purchaseOrder1.xml
delete from XML_PURCHASEORDER;
1 row deleted.
SQL> commit;
Commit complete.
select extractValue(res,'Resource/DisplayName') "Filename"
from RESOURCE_VIEW where under_path(res,'/public/testFolder') = 1
/
Results in:
Accessing XML Schema-Based Content
3-44 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
no rows selected
Accessing XML Schema-Based Content
When a resource describes XML content that has been stored in a default table the
resource entry itself simply contains a reference to the appropriate row in the
default table. This reference can be used to perform join operations between the
resource and its content. This can be seen in the following example.
Accessing Non-Schema-Based Content With XDBUriType
XDBUriType can be used to access the contents of a le stored in the Repository
using a logical path. The following example shows how to access a resource
associated with a JPEG le. The JPEG le has been inserted into the Repository. The
example uses Oracle interMedia ordsys.ordimage class to extract the metadata
associated with the JPEG le.
create or replace function getImageMetaData (uri varchar2)
return xmltype deterministic
is
resType xmltype;
resObject xdb.xdb$resource_t;
attributes CLOB;
xmlAttributes xmltype;
begin
DBMS_LOB.CREATETEMPORARY(attributes, FALSE, DBMS_LOB.CALL);
-- ordsys.ordimage.getProperties(xdburitype(uri).getBlob(),
-- attributes);
select res into resType from resource_view where any_path = uri;
resType.toObject(resObject);
ordsys.ordimage.getProperties(resObject.XMLLOB,attributes);
xmlAttributes := xmltype(attributes);
DBMS_LOB.FREETEMPORARY(attributes);
return xmlAttributes;
end;
/
Oracle XML DB Protocol Servers
Oracle XML DB includes three protocol servers through which you can access the
Repository directly from standard le-based applications.
Oracle XML DB Protocol Servers
Using Oracle XML DB 3-45
Using FTP Protocol Server
The FTP Protocol Server allows standard FTP clients to access content stored in the
Repository as if it were content behind a regular FTP server. FTP Protocol Server
works with standard FTP clients, including:
I Command line clients, such as the command line clients supplied with Unix
and Windows Command Prompt
I Graphical clients, such as WS-FTP
I Web Browsers that support the FTP protocol
Figure 36, Figure 37, Figure 38, and Figure 39 show examples of how you can
access the root level of the Repository using various of standard FTP clients.
Figure 36 Accessing the Repository Root Level from the DOS Command Prompt Command Line
See Also: Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
Oracle XML DB Protocol Servers
3-46 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 37 Accessing the Repository Root Level fro m IE Browser Web Folder Menu
Oracle XML DB Protocol Servers
Using Oracle XML DB 3-47
Figure 38 Accessing the Repository Root Level fro m WS_FTP95LE FTP Interface Program
Oracle XML DB Protocol Servers
3-48 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 39 Accessing the Repository Root Level from a Telnet Session
Oracle XML DB Protocol Servers
Using Oracle XML DB 3-49
Using HTTP/WebDAV Protocol Server
Oracle XML DB Repository can also be accessed using HTTP and WebDAV.
WebDAV support allows applications such as a Microsofts Web Folders client,
Microsoft Ofce, and Macromedias Dreamweaver to directly access Oracle XML
DB Repository. Figure 310 and Figure 311 are examples of using HTTP and
WebDAV to access the Repository.
Figure 310 Accessing the Repository Using HTTP/WebDAV from Microsoft Windows Explorer
Oracle XML DB Protocol Servers
3-50 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 311 Accessing the Repository Using HTTP/WebDAV Protocol Server from Microsoft Web
Folders Client
By providing support for standard industry protocols, Oracle XML DB makes it
possible to upload and access data and documents stored in Oracle9i database
using standard, familiar interfaces.
Part II
Storing and Retrieving XML Data in Oracle
XML DB
Part II of this manual introduces you to ways you can store, retrieve, validate, and
transform XML data using Oracle XML DB. It contains the following chapters:
I Chapter 4, "Using XMLType"
I Chapter 5, "Structured Mapping of XMLType"
I Chapter 6, "Transforming and Validating XMLType Data"
I Chapter 7, "Searching XML Data with Oracle Text"
Using XMLType 4-1
4
Using XMLType
This chapter describes how to use the XMLType datatype, create and manipulate
XMLType tables and columns, and query on them. It contains the following
sections:
I What Is XMLType?
I When to Use XMLType
I Storing XMLType Data in Oracle XML DB
I XMLType Member Functions
I How to Use the XMLType API
I Guidelines for Using XMLType Tables and Columns
I Manipulating XML Data in XMLType Columns/Tables
I Inserting XML Data into XMLType Columns/Tables
I Selecting and Querying XML Data
I Updating XML Instances and Data in Tables and Columns
I Deleting XML Data
I Using XMLType In Triggers
I Indexing XMLType Columns
What Is XMLType?
4-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
What Is XMLType?
Oracle9i Release 1 (9.0.1) introduced a new datatype, XMLType, to facilitate native
handling of XML data in the database. The following summarizes XMLType:
I XMLType can be used in PL/SQL stored procedures as parameters, return
values, and variables.
I XMLType can represent an XML document as an instance (of XMLType) in SQL.
I XMLType has built-in member functions that operate on XML content. For
example, you can use XMLType functions to create, extract, and index XML data
stored in Oracle9i database.
I Functionality is also available through a set of Application Program Interfaces
(APIs) provided in PL/SQL and Java.
With XMLType and these capabilities, SQL developers can leverage the power of the
relational database while working in the context of XML. Likewise, XML
developers can leverage the power of XML standards while working in the context
of a relational database.
XMLType datatype can be used as the datatype of columns in tables and views.
Variables of XMLType can be used in PL/SQL stored procedures as parameters,
return values, and so on. You can also use XMLType in SQL, PL/SQL, and Java
(through JDBC).
Note:
I Non-schema-based: XMLType tables and columns described in
this chapter are not based on XML schema. You can, however,
use the techniques and examples provided in this chapter
regardless of which storage option you choose for your
XMLType tables and columns. See Chapter 3, "Using Oracle
XML DB" for further storage recommendations.
I XML schema-based: Appendix B, "XML Schema Primer" and
Chapter 5, "Structured Mapping of XMLType" describe how to
work with XML schema-based XMLType tables and columns.
What Is XMLType?
Using XMLType 4-3
A number of useful functions that operate on XML content are provided. Many of
these are provided as both SQL and member functions of XMLType. For example,
the extract() function extracts a specic node(s) from an XMLType instance.
You can use XMLType in SQL queries in the same way as any other user-dened
datatypes in the system.
Benets of the XMLType Data Type and API
The XMLType datatype and API provides signicant advantages. It enables SQL
operations on XML content, as well as XML operations on SQL content:
I Versatile API . XMLType has a versatile API for application development, as it
includes built-in functions, indexing support, navigation, and so on.
I XMLType and SQL. You can use XMLType in SQL statements combined with
other columns and datatypes. For example, you can query XMLType columns
and join the result of the extraction with a relational column, and then Oracle
can determine an optimal way to execute these queries.
I Optimized evaluation using XMLType. XMLType is optimized to not
materialize the XML data into a tree structure unless needed. Therefore when
SQL selects XMLType instances inside queries, only a serialized form is
exchanged across function boundaries. These are exploded into tree format only
when operations such as extract() and existsNode() are performed. The
internal structure of XMLType is also an optimized DOM-like tree structure.
Note: In Oracle9i Release 1 (9.0.1), XMLType was only supported
in the server in SQL, PL/SQL, and Java. In Oracle9i Release 2 (9.2),
XMLType is also supported on the client side through SQL, Java,
and protocols such as FTP and HTTP/WebDav.
See Also:
I "Oracle XML DB Offers Faster Storage and Retrieval of
Complex XML Documents" on page 1-20
I Chapter 26, "Oracle XML DB Basic Demo"
I Oracle9i SQL Reference Appendix D, Using XML in SQL
Statements
When to Use XMLType
4-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I I ndexing. Oracle Text index has been enhanced to support XMLType columns.
You can also create function-based indexes on existsNode() and extract()
functions to speed up query evaluation.
When to Use XMLType
Use XMLType when you need to perform the following:
I SQL queries on part of or the whole XML document: The functions
existsNode() and extract() provide the necessary SQL query functions
over XML documents.
I Strong typing inside SQL statements and PL/SQL functions: Strong typing
implies that you ensure that the values passed in are XML values and not any
arbitrary text string.
I XPath functionality provided by extract() and existsNode() functions:
Note that XMLType uses the built-in C XML parser and processor and hence
provides better performance and scalability when used inside the server.
I Indexing on XPath searches on documents: XMLType has member functions
that you can use to create function-based indexes to optimize searches.
I To shield applications from storage models. Using XMLType instead of CLOBs
or relational storage allows applications to gracefully move to various storage
alternatives later without affecting any of the query or DML statements in the
application.
I To prepare for future optimizations. New XML functionality will support
XMLType. Since Oracle9i database is natively aware that XMLType can store
XML data, better optimizations and indexing techniques can be done. By
writing applications to use XMLType, these optimizations and enhancements
can be easily achieved and preserved in future releases without your needing to
rewrite applications.
Storing XMLType Data in Oracle XML DB
XMLType data can be stored in two ways or a combination thereof:
I I n Large Objects (LOBs). LOB storage maintains content accuracy to the
original XML (whitespaces and all). Here the XML documents are stored
composed as whole documents like les. In this release, for non-schema-based
storage, XMLType offers a CLOB storage option. In future releases, Oracle may
See Also: Chapter 10, "Generating XML Data from the Database"
Storing XMLType Data in Oracle XML DB
Using XMLType 4-5
provide other storage options, such as BLOBs, NCLOBS, and so on. You can
also create a CLOB-based storage for XML schema-based storage.
When you create an XMLType column without any XML schema specication, a
hidden CLOB column is automatically created to store the XML data. The
XMLType column itself becomes a virtual column over this hidden CLOB
column. It is not possible to directly access the CLOB column; however, you can
set the storage characteristics for the column using the XMLType storage clause.
I I n Structured storage (in tables and views). Structured storage maintains DOM
(Document Object Model) delity. Here the XML documents are broken up
(decomposed) into object- relational tables or views. XMLType achieves DOM
delity by maintaining information that SQL or Java objects normally do not
provide for, such as:
I Ordering of child elements and attributes.
I Distinguishing between elements and attributes.
I Unstructured content declared in the schema. For example,
content="mixed or <any> declarations.
I Undeclared data in instance documents, such as processing instructions,
comments, and namespace declarations.
I Support for basic XML datatypes not available in SQL (Boolean, QName,
and so on).
I Support for XML constraints (facets) not supported directly by SQL, such as
enumerated lists.
Native XMLType instances contain hidden columns that store this extra information
that does not quite t in the SQL object model. This information can be accessed
through APIs in SQL or Java, using member functions, such as extractNode().
Changing XMLType storage from structured storage to LOB, or vice versa, is
possible using database IMPORT and EXPORT. Your application code does not
have to change. You can then change XML storage options when tuning your
application, since each storage option has its own benets.
Pros and Cons of XML Storage Options in Oracle XML DB
Table 41 summarizes some advantages and disadvantages to consider when
selecting your Oracle XML DB storage option.
Storing XMLType Data in Oracle XML DB
4-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
When to Use CLOB Storage for XMLType
Use CLOB storage for XMLType in the following cases:
I You need to store XML as a whole document in the database and retrieve it as a
whole document.
I You do not need to perform piece-wise updates on XML documents.
Table 41 XML Storage Options in Oracle XML DB
Feature LOB Storage (with Oracle Text index) Structured Storage (with B*Tree index)
Database schema
exibility
Very exible when schemas change. Limited exibility for schema changes. Similar
to the ALTER TABLE restrictions.
Data integrity
and accuracy
Maintains the original XML byte for byte -
important in some applications.
Trailing new lines, whites pace within tags, and
data format for non-string datatypes is lost. But
maintains DOM delity.
Performance Mediocre performance for DML. Excellent DML performance.
Access to SQL Some accessibility to SQL features. Good accessibility to existing SQL features,
such as constraints, indexes, and so on
Space needed Can consume considerable space. Needs less space in particular when used with
an Oracle XML DB registered XML schema.
Note: XMLType and Varray:
I You cannot create VARRAYs of XMLType and store them in the
database since VARRAYs do not support CLOBs when stored
in tables.
I You cannot create columns of VARRAY types that contain
XMLType. This is because Oracle does not support LOB locators
inside VARRAYs.
See Also:
I Chapter 2, "Getting Started with Oracle XML DB"
I Chapter 3, "Using Oracle XML DB", "Storing XML: Structured
or Unstructured Storage" on page 3-24
I Chapter 10, "Generating XML Data from the Database", for
information on how to generate XMLType data.
How to Use the XMLType API
Using XMLType 4-7
XMLType Member Functions
Oracle9i Release 1 (9.0.1) introduced several SQL functions and XMLType member
functions that operate on XMLType values. Oracle9i Release 2 (9.2) has expanded
functionality. It provides several new SQL functions and XMLType member
functions.
All XMLType functions use the built-in C parser and processor to parse XML data,
validate it, and apply XPath expressions on it. They also use an optimized
in-memory DOM tree for processing, such as extracting XML documents or
fragments.
How to Use the XMLType API
You can use the XMLType API to create tables and columns. The createXML()
static function of the XMLType API can be used to create XMLType instances for
insertion. By storing your XML documents as XMLType, XML content can be
readily searched using standard SQL queries.
Figure 41 shows the syntax for creating an XMLType table:
CREATE TABLE [schema.] table OF XMLTYPE
[XMLTYPE XMLType_storage] [XMLSchema_spec];
See Also:
I Appendix F, "Oracle XML DB XMLType API, PL/SQL and
Resource PL/SQL APIs: Quick Reference"
I Oracle9i XML API Reference - XDK and Oracle XML DB for a list
of all XMLType and member functions, their syntax, and
descriptions.
See Also: Appendix C, "XPath and Namespace Primer"
How to Use the XMLType API
4-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 41 Creating an XMLType Table
This section shows some simple examples of howto create an XMLType column and
use it in a SQL statement, and how to create XMLType tables.
Creating, Adding, and Dropping XMLType Columns
The following are examples of creating, adding, and dropping XMLType columns:
Example 41 Creating XMLType: Creating XMLType Columns
The XMLType column can be created like any other user-dened type column:
CREATE TABLE warehouses(
warehouse_id NUMBER(4),
warehouse_spec XMLTYPE,
warehouse_name VARCHAR2(35),
location_id NUMBER(4));
Example 42 Creating XMLType: Creating XMLType Columns
As explained, you can create XMLType columns by simply using the XMLType as
the datatype. The following statement creates a purchase order document column,
poDoc, of XMLType:
CREATE TABLE po_xml_tab(
poid number,
poDoc XMLTYPE);
CREATE TABLE po_xtab of XMLType; -- this creates a table of XMLType. The default
-- is CLOB based storage.
Example 43 Adding XMLType Columns
You can alter tables to add XMLType columns as well. This is similar to any other
datatype. The following statement adds a new customer document column to the
table:
CREATE TABLE
schema .
table OF XMLTYPE
XMLTYPE XMLType_storage XMLSchema_spec
How to Use the XMLType API
Using XMLType 4-9
ALTER TABLE po_xml_tab add (custDoc XMLType);
Example 44 Dropping XMLType Columns
You can alter tables to drop XMLType columns, similar to any other datatype. The
following statement drops column custDoc:
ALTER TABLE po_xml_tab drop (custDoc);
Inserting Values into an XMLType Column
To insert values into the XMLType column, you need to bind an XMLType instance.
Example 45 Inserting into XMLTYpe Using the XMLType() Constructor
An XMLType instance can be easily created from a VARCHAR or a Character Large
Object (CLOB) by using the XMLType() constructor:
INSERT INTO warehouses VALUES
( 100, XMLType(
<Warehouse whNo="100">
<Building>Owned</Building>
</Warehouse>), Tower Records, 1003);
This example creates an XMLType instance from a string literal. The input to
createXML() can be any expression that returns a VARCHAR2 or CLOB.
createXML() also checks that the input XML is well-formed.
Using XMLType in an SQL Statement
The following simple SELECT statement shows how you can use XMLType in an
SQL statement:
Example 46 Using XMLType and in a SELECT Statement
SELECT
w.warehouse_spec.extract('/Warehouse/Building/text()').getStringVal()
"Building"
FROM warehouses w;
where warehouse_spec is an XMLType column operated on by member function
extract(). The result of this simple query is a string (varchar2):
Building
-----------------
How to Use the XMLType API
4-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Owned
Updating an XMLType Column
An XML document in an XMLType can be stored packed in a CLOB. Then updates
have to replace the whole document in place.
Example 47 Updating XMLType
To update an XML document, you can execute a standard SQL UPDATE statement.
You need to bind an XMLType instance, as follows:
UPDATE warehouses SET warehouse_spec = XMLType
(<Warehouse whono="200">
<Building>Leased</Building>
</Warehouse>);
This example created an XMLType instance froma string literal and updates column
warehouse_spec with the new value.
Deleting a Row Containing an XMLType Column
Deleting a row containing an XMLType column is no different from deleting a row
containing any other datatype.
Example 48 Deleting an XMLType Column Row
You can use extract() and existsNode() functions to identify rows to delete
as well. For example to delete all warehouse rows for which the warehouse
building is leased, you can write a statement such as:
DELETE FROM warehouses e
WHERE e.warehouse_spec.extract(//Building/text()).getStringVal()
= Leased;
See Also: "How to Use the XMLType API" on page 4-7.
Note: Any triggers would get red on the UPDATE statement
You can see and modify the XML value inside the triggers.
Guidelines for Using XMLType Tables and Columns
Using XMLType 4-11
Guidelines for Using XMLType Tables and Columns
The following are guidelines for storing XML data in XMLType tables and columns:
Define table/column of XMLType
First, dene a table/column of XMLType. You can include optional storage
characteristics with the table/column denition.
Create an XMLType Instance
Use the XMLType constructor to create the XMLType instance before inserting into
the column/table. You can also use a variety of other functions that return
XMLType.
Select or Extract a Particular XMLType Instance
You can select out the XMLType instance from the column. XMLType also offers a
choice of member functions, such as extract() and existsNode(), to extract a
particular node and to check to see if a node exists respectively. See the table of
XMLType member functions in Oracle9i XML API Reference - XDK and Oracle XML
DB.
Note: In this release, Oracle supports XMLType as a public
synonym for sys.XMLType. XMLType now also supports a set of
user-dened constructors (mirroring the createXML static
functions). For example:
I In Oracle9i Release 1 (9.0.1), you could use the following
syntax: sys.XMLType.createXML(<Warehouse
whNo=100>...)
I In Oracle9i Release 2 (9.2), you can use the following
abbreviated version: XMLType(<Warehouse
whNo=100>...).
Note: This release of Oracle supports creating tables of XMLType.
You can create object references (REFs) to these tables and use them
in the object cache.
See Also: "SYS_XMLGEN(): Converting an XMLType Instance"
on page 10-48, for an example.
Guidelines for Using XMLType Tables and Columns
4-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
You can Define an Oracle Text Index
You can dene an Oracle Text index on XMLType columns. This enables you to use
CONTAINS, HASPATH, INPATH, and other text operators on the column. All the
Oracle Text operators and index functions that operate on LOB columns also work
on XMLType columns.
You Can Define XPath Index, CTXXPATH
In this release, a new Oracle Text index type, CTXXPATH is introduced. This helps
existsNode() implement indexing and optimizes the evaluation of
existsNode() in a predicate.
Specifying Storage Characteristics on XMLType Columns
XML data in an XMLType column can be stored as a CLOB column. Hence you can
also specify LOB storage characteristics for that column. In example, "Creating
XMLType: Creating XMLType Columns" on page 4-8, the warehouse_spec
column is an XMLType column.
Example 49 Specifying Storage When Creating an XMLType Table
You can specify storage characteristics on this column when creating the table as
follows:
CREATE TABLE po_xml_tab(
poid NUMBER(10),
poDoc XMLTYPE
)
XMLType COLUMN poDoc
See Also:
I "Selecting XMLType Columns using getClobVal()" on page 4-18
I "Extracting Fragments from XMLType Using extract()" on
page 4-30
See Also:
I "Indexing XMLType Columns" on page 4-39
I Chapter 7, "Searching XML Data with Oracle Text"
I Chapter 10, "Generating XML Data from the Database"
I Oracle9i Application Developers Guide - Large Objects (LOBs)
Guidelines for Using XMLType Tables and Columns
Using XMLType 4-13
STORE AS CLOB (
TABLESPACE lob_seg_ts
STORAGE (INITIAL 4096 NEXT 4096)
CHUNK 4096 NOCACHE LOGGING
);
The STORE AS clause is also supported when adding columns to a table.
Example 410 Adding an XMLType Columns and Specifying Storage
To add a newXMLType column to this table and specify the storage clause for that
column, you can use the following SQL statement:
ALTER TABLE po_xml_tab add(
custDoc XMLTYPE
)
XMLType COLUMN custDoc
STORE AS CLOB (
TABLESPACE lob_seg_ts
STORAGE (INITIAL 4096 NEXT 4096)
CHUNK 4096 NOCACHE LOGGING
);
Changing Storage Options on an XMLType Column Using XMLData
In non- schema-based storage, you can use XMLDATA to change storage
characteristics on an XMLType column.
Example 411 Changing Storage Characteristics on an XMLType Column Using
XMLDATA
For example, consider table foo_tab:
CREATE TABLE foo_tab (a xmltype);
To change the storage characteristics of LOB column a in foo_tab, you can use
the following statement:
ALTER TABLE foo_tab MODIFY LOB (a.xmldata) (storage (next 5K) cache);
XMLDATA identies the internal storage column. In the case of CLOB-based storage
this corresponds to the CLOB column. The same holds for XML schema-based
storage. You can use XMLDATA to explore structured storage and modify the values.
Manipulating XML Data in XMLType Columns/Tables
4-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
You can use the XMLDATA attribute in constraints and indexes, in addition to
storage clauses.
Specifying Constraints on XMLType Columns
You can specify NOT NULL constraint on an XMLType column.
Example 412 Specifying Constraints on XMLType Columns
CREATE TABLE po_xml_tab (
poid number(10),
poDoc XMLType NOT NULL
);
prevents inserts such as:
INSERT INTO po_xml_tab (poDoc) VALUES (null);
Example 413 Using ALTER TABLE to Change NOT NULL of XMLType Columns
You can also use the ALTER TABLE statement to change NOT NULL information
of an XMLType column, in the same way you would for other column types:
ALTER TABLE po_xml_tab MODIFY (poDoc NULL);
ALTER TABLE po_xml_tab MODIFY (poDoc NOT NULL);
You can also dene check constraints on XMLType columns. Other default values
are not supported on this datatype.
Manipulating XML Data in XMLType Columns/Tables
Since XMLType is a user-dened data type with functions dened on it, you can
invoke functions on XMLType and obtain results. You can use XMLType wherever
you use a user-dened type, including for table columns, views, trigger bodies, and
type denitions.
Note: In this release, the XMLDATA attribute helps access the
XMLTypes internal storage columns so that you can specify storage
characteristics, constraints, and so on directly on that column.
See also: Oracle9i Application Developers Guide - Large Objects
(LOBs) f and Oracle9i SQL Reference for more information about LOB
storage options
Inserting XML Data into XMLType Columns/Tables
Using XMLType 4-15
You can perform the following manipulations or Data Manipulation Language
(DML) on XML data in XMLType columns and tables:
I Inserting XML Data into XMLType Columns/Tables
I Selecting and Querying XML Data
I Updating XML Instances and Data in Tables and Columns
I Deleting XML Data
Inserting XML Data into XMLType Columns/Tables
You can insert data into XMLType columns in the following ways:
I By using the INSERT statement (in SQL, PL/SQL, and Java)
I By using SQL*Loader. See Chapter 22, "Loading XML Data into Oracle XML
DB"
XMLType columns can only store well-formed XML documents. Fragments and
other non-well-formed XML cannot be stored in XMLType columns.
Using INSERT Statements
To use the INSERT statement to insert XML data into XMLType, you need to rst
create XML documents to perform the insert with. You can create the insertable
XML documents as follows:
I By using XMLType constructors. This can be done in SQL, PL/SQL, and Java.
I By using SQL functions like XMLElement(), XMLConcat(), and XMLAGG().
This can be done in SQL, PL/SQL, and Java.
Example 414 Inserting XML Data Using createXML() with CLOB
The following examples use INSERT...SELECT and the XMLType constructor to rst
create an XML document and then insert the document into the XMLType columns.
Consider table po_clob_tab that contains a CLOB, poClob, for storing an XML
document:
CREATE TABLE po_clob_tab
(
poid number,
poClob CLOB
);
Inserting XML Data into XMLType Columns/Tables
4-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
-- some value is present in the po_clob_tab
INSERT INTO po_clob_tab
VALUES(100, <?xml version="1.0"?>
<PO pono="1">
<PNAME>Po_1</PNAME>
<CUSTNAME>John</CUSTNAME>
<SHIPADDR>
<STREET>1033, Main Street</STREET>
<CITY>Sunnyvalue</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>');
Example 415 Inserting XML Data Using an XMLType Instance
You can insert a purchase order XML document into table, po_xml_tab, by simply
creating an XML instance from the CLOB data stored in the other po_clob_tab:
INSERT INTO po_xml_tab
SELECT poid, XMLType(poClob)
FROM po_clob_tab;
Example 416 Inserting XML Data Using XMLType() with String
This example inserts a purchase order into table po_tab using the XMLType
constructor:
INSERT INTO po_xml_tab
VALUES(100, XMLType(<?xml version="1.0"?>
<PO pono="1">
<PNAME>Po_1</PNAME>
<CUSTNAME>John</CUSTNAME>
<SHIPADDR>
<STREET>1033, Main Street</STREET>
<CITY>Sunnyvalue</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>'));
Note: You can also get the CLOB value from any expression,
including functions that can create temporary CLOBs or select out
CLOBs from other table or views.
Selecting and Querying XML Data
Using XMLType 4-17
Example 417 Inserting XML Data Using XMLElement()
This example inserts a purchase order into table po_xml_tab by generating it
using the XMLElement() SQL function. Assume that the purchase order is an
object view that contains a purchase order object. The whole denition of the
purchase order view is given in "DBMS_XMLGEN: Generating a Purchase Order
from the Database in XML Format" on page 10-34.
INSERT INTO po_xml_tab
SELECT XMLelement("po", value(p))
FROM po p
WHERE p.pono=2001;
XMLElement() creates an XMLType from the purchase order object, which is then
inserted into table po_xml_tab. You can also use SYS_XMLGEN() in the INSERT
statement.
Selecting and Querying XML Data
You can query XML data fromXMLType columns in the following ways:
I By selecting XMLType columns through SQL, PL/SQL, or Java
I By querying XMLType columns directly and using extract() and
existsNode()
I By using Oracle Text operators to query the XML content. See "Indexing
XMLType Columns" on page 4-39 and Chapter 7, "Searching XML Data with
Oracle Text".
SQL Functions for Manipulating XML data
SQL functions such as existsNode(), extract(), XMLTransform(), and
updateXML() operate on XML data inside SQL. XMLType datatype supports most
of these as member functions. You can use either the selsh style of invocation or
the SQL functions.
Selecting XML Data
You can select XMLType data using PL/SQL or Java. You can also use the
getClobVal(), getStringVal(), or getNumberVal() functions to retrieve
XML as a CLOB, VARCHAR, or NUMBER, respectively.
Selecting and Querying XML Data
4-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 418 Selecting XMLType Columns using getClobVal()
This example shows how to select an XMLType column using SQL*Plus:
SET long 2000
SELECT e.poDoc.getClobval() AS poXML
FROM po_xml_tab e;
POXML
---------------------
<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>Nance</CUSTNAME>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
Querying XML Data
You can query XMLType data and extract portions of it using the existsNode()
and extract() functions. Both these functions use a subset of the W3C XPath
recommendation to navigate the document.
Using XPath Expressions for Searching XML Documents
XPath is a W3C recommendation for navigating XML documents. XPath models the
XML document as a tree of nodes. It provides a rich set of operations to walk the
tree and to apply predicates and node test functions. Applying an XPath expression
to an XML document can result in a set of nodes. For instance, /PO/PONO selects
out all PONO child elements under the PO root element of the document.
Table 42 lists some common constructs used in XPath.
Selecting and Querying XML Data
Using XMLType 4-19
The XPath must identify a single or a set of element, text, or attribute nodes. The
result of the XPath cannot be a boolean expression.
Querying XML Data Using XMLType Member Functions
You can select XMLType data through PL/SQL, OCI, or Java. You can also use the
getClobVal(), getStringVal(), or getNumberVal() functions to retrieve the
XML as a CLOB, VARCHAR or a number, respectively.
Example 419 Retrieving an XML Document as a CLOB Using getClobVal() and
existsNode()
This example shows how to select an XMLType column using getClobVal() and
existsNode():
set long 2000
SELECT e.poDoc.getClobval() AS poXML
FROM po_xml_tab e
WHERE e.poDoc.existsNode(/PO[PNAME = "po_2"]) = 1;
Table 42 Some Common XPath Constructs
XPath Construct Description
/ Denotes the root of the tree in an XPath expression. For example, /PO refers to the
child of the root node whose name is PO.
/ Also used as a path separator to identify the children node of any given node. For
example, /PO/PNAME identies the purchase order name element, a child of the root
element.
// Used to identify all descendants of the current node. For example, PO//ZIP matches
any zip code element under the PO element.
"* Used as a wildcard to match any child node. For example, /PO/*/STREET matches
any street element that is a grandchild of the PO element.
[ ] Used to denote predicate expressions. XPath supports a rich list of binary operators
such as OR, AND, and NOT. For example, /PO[PONO=20 and PNAME=PO_
2]/SHIPADDR select out the shipping address element of all purchase orders whose
purchase order number is 20 and whose purchase order name is PO_2. [ ] is also
used for denoting an index into a list. For example, /PO/PONO[2] identies the
second purchase order number element under the PO root element.
See Also: Appendix C, "XPath and Namespace Primer"
Selecting and Querying XML Data
4-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
POXML
---------------------
<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>Nance</CUSTNAME>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
existsNode Function
The syntax for the existsNode() function is described in Figure 42 and also as
follows:
existsNode(XMLType_instance IN XMLType,
XPath_string IN VARCHAR2, namespace_string IN varchar2 := null)
RETURN NUMBER
Figure 42 existsNode() Syntax
existsNode() function on XMLType checks if the given XPath evaluation results
in at least a single XML element or text node. If so, it returns the numeric value 1,
otherwise, it returns a 0. Namespace can be used to identify the mapping of
prex(es) specied in the XPath_string to the corresponding namespace(s).
Example 420 Using existsNode() on XMLType
For example, consider an XML document such as:
<PO>
<PONO>100</PONO>
<PNAME>Po_1</PNAME>
<CUSTOMER CUSTNAME="John"/>
<SHIPADDR>
<STREET>1033, Main Street</STREET>
<CITY>Sunnyvalue</CITY>
EXISTSNODE ( XMLType_instance , XPath_string
namespace
)
,
Selecting and Querying XML Data
Using XMLType 4-21
<STATE>CA</STATE>
</SHIPADDR>
</PO>
An XPath expression such as /PO/PNAME results in a single node. Therefore,
existsNode() will return 1 for that XPath. This is the same with
/PO/PNAME/text(), which results in a single text node.
An XPath expression such as /PO/POTYPE does not return any nodes. Therefore, an
existsNode() on this would return the value 0.
To summarize, existsNode() member function can be used in queries and to
create function-based indexes to speed up evaluation of queries.
Example 421 Using existsNode() to Find a node
The following example tests for the existence of the /Warehouse/Dock node in the
warehouse_spec column XML path of the sample table oe.warehouses:
SELECT warehouse_id, EXISTSNODE(warehouse_spec, /Warehouse/Docks)
"Loading Docks"
FROM warehouses
WHERE warehouse_spec IS NOT NULL;
WAREHOUSE_ID Loading Docks
------------ -------------
1 1
2 1
3 0
4 1
Using Indexes to Evaluate existsNode()
You can create function-based indexes using existsNode() to speed up the
execution. You can also create a CTXXPATH index to help speed up arbitrary XPath
searching.
extract () Function
The extract() function is similar to the existsNode() function. It applies a
VARCHAR2 XPath string with an optional namespace parameter and returns an
See Also: "Creating XPath Indexes on XMLType Columns:
CTXXPATH Index" on page 4-41
Selecting and Querying XML Data
4-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XMLType instance containing an XML fragment. The syntax is described in
Figure 43 and as follows:
extract(XMLType_instance IN XMLType, XPath_string IN VARCHAR2,
namespace_string In varchar2 := null) RETURN XMLType;
Figure 43 extract() Syntax
extract() on XMLType extracts the node or a set of nodes from the document
identied by the XPath expression. The extracted nodes can be elements, attributes,
or text nodes. When extracted out, all text nodes are collapsed into a single text
node value. Namespace can be used to supply namespace information for prexes
in the XPath string.
The XMLType resulting from applying an XPath through extract() need not be a
well-formed XML document but can contain a set of nodes or simple scalar data in
some cases. You can use the getStringVal() or getNumberVal() methods on
XMLType to extract this scalar data.
For example, the XPath expression /PO/PNAME identies the PNAME element inside
the XML document shown previously. The expression /PO/PNAME/text(), on the
other hand, refers to the text node of the PNAME element.
Use text() node test function to identify text nodes in elements before using the
getStringVal() or getNumberVal() to convert them to SQL data. Not having
the text() node would produce an XML fragment.
For example, XPath expressions:
I /PO/PNAME identies the fragment <PNAME>PO_1</PNAME>
I /PO/PNAME/text() identies the text value PO_1
Note: The latter is still considered an XMLType. In other words,
extract(poDoc,/PO/PNAME/text()) still returns an
XMLtype instance although the instance may actually contain only
text. You can use getStringVal() to get the text value out as a
VARCHAR2 result.
EXTRACT ( XMLType_instance , XPath_string
namespace
)
,
Selecting and Querying XML Data
Using XMLType 4-23
You can use the index mechanism to identify individual elements in case of
repeated elements in an XML document. For example, if you have an XML
document such as:
<PO>
<PONO>100</PONO>
<PONO>200</PONO>
</PO>
you can use:
I //PONO[1] to identify the rst PONO element (with value 100).
I //PONO[2] to identify the second PONO element (with value 200).
The result of extract() is always an XMLType. If applying the XPath produces an
empty set, then extract() returns a NULL value.
Hence, extract() member function can be used in a number of ways, including
the following:
I Extracting numerical values on which function-based indexes can be created to
speed up processing
I Extracting collection expressions to be used in the FROM clause of SQL
statements
I Extracting fragments to be later aggregated to produce different documents
Example 422 Using extract() to Extract the Value of a Node
This example extracts the value of node, /Warehouse/Docks, of column,
warehouse_spec in table oe.warehouses:
SELECT warehouse_name,
extract(warehouse_spec, /Warehouse/Docks).getStringVal()
"Number of Docks"
FROM warehouses
WHERE warehouse_spec IS NOT NULL;
WAREHOUSE_NAME Number of Docks
-------------------- --------------------
Southlake, Texas <Docks>2</Docks>
San Francisco <Docks>1</Docks>
New Jersey <Docks/>
Seattle, Washington <Docks>3</Docks>
Selecting and Querying XML Data
4-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
extractValue() Function
The extractValue() function takes as arguments an XMLType instance and an
XPath expression. It returns a scalar value corresponding to the result of the XPath
evaluation on the XMLType instance. extractValue() syntax is also described in
Figure 44.
I XML schema-based documents. For documents based on XML schema, if
Oracle9i can infer the type of the return value, then a scalar value of the
appropriate type is returned. Otherwise, the result is of type VARCHAR2.
I Non- schema-based documents. For documents not based on XML schemas,
the return type is always VARCHAR2.
extractValue() tries to infer the proper return type fromthe XML schema of the
document. If the XMLType is non- schema-based or the proper return type cannot
be determined, Oracle XML DB returns a VARCHAR2.
Figure 44 extractValue() Syntax
A Shortcut Function
extractValue() permits you to extract the desired value more easily than when
using the equivalent extract function. It is an ease-of-use and shortcut function. So
instead of using:
extract(x,'path/text()').get(string|num)val()
you can replace extract().getStringVal() or
extract().getnumberval() with extractValue() as follows:
extractValue(x, path/text())
With extractValue() you can leave off the text(), but ONLY if the node
pointed to by the 'path' part has only one child and that child is a text node.
Otherwise, an error is thrown.
extractValue() syntax is the same as extract().
EXTRACTVALUE ( XMLType_instance , XPath_string
, value_expr
)
Selecting and Querying XML Data
Using XMLType 4-25
extractValue() Characteristics
extractValue() has the following characteristics:
I It always returns only scalar content, such as NUMBER...VARCHAR2, and so
on.
I It cannot return XML nodes or mixed content. It raises an error at compile or
run time if it gets XML nodes as the result.
I It always returns VARCHAR2 by default. If the nodes value is bigger than 4K,
a runtime error would occur.
I In the presence of XML schema information, at compile time,
extractValue() can automatically return the appropriate datatype based on
the XML schema information, if it can detect so at compile time of the query.
For instance, if the XML schema information for the path /PO/POID indicates
that this is a numerical value, then extractValue() returns a NUMBER.
I If the XPath identies a node, it automatically gets the scalar content from its
text child. The node must have exactly one text child. For example:
extractValue(xmlinstance, /PO/PNAME)
extracts out the text child of PNAME. This is equivalent to:
extract(xmlinstance, /PO/PNAME/text()).getstringval()
Example 423 Extracting the Scalar Value of an XML Fragment Using extractValue()
The following example takes as input the same arguments as the example for
extract () Function on page 4-21. Instead of returning an XML fragment, as
extract() does, it returns the scalar value of the XML fragment:
SELECT warehouse_name,
extractValue(e.warehouse_spec, /Warehouse/Docks)
"Docks"
FROM warehouses e
WHERE warehouse_spec IS NOT NULL;
WAREHOUSE_NAME Docks
-------------------- ------------
Southlake, Texas 2
San Francisco 1
New Jersey
Seattle, Washington 3
Selecting and Querying XML Data
4-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
ExtractValue() automatically extracted out the text child of Docks element and
returned that value. You can also write this using extract() as follows:
extract(e.warehouse_spec, /Warehouse/Docks/text()).getstringval()
More SQL Examples That Query XML
The following SQL examples illustrate ways you can query XML.
Example 424 Querying XMLType Using extract() and existsNode()
Assume the po_xml_tab table, which contains the purchase order identication
and the purchase order XML columns, and assume that the following values are
inserted into the table:
INSERT INTO po_xml_tab values (100,
xmltype(<?xml version="1.0"?>
<PO>
<PONO>221</PONO>
<PNAME>PO_2</PNAME>
</PO>));
INSERT INTO po_xml_tab values (200,
xmltype(<?xml version="1.0"?>
<PO>
<PONAME>PO_1</PONAME>
</PO>));
Now you can extract the numerical values for the purchase order numbers using
extract():
SELECT e.poDoc.extract(//PONO/text()).getNumberVal() as pono
FROM po_xml_tab e
WHERE e.podoc.existsnode(/PO/PONO) = 1 AND poid > 1;
Here extract() extracts the contents of tag, purchase order number, PONO.
existsNode() nds nodes where PONO exists as a child of PO.
Note: Here text() function is only used to return the text
nodes. getNumberVal() function can convert only text values
into numerical quantity
Selecting and Querying XML Data
Using XMLType 4-27
Example 425 Querying Transient XMLType Data
The following example shows how you can select out the XML data and query it
inside PL/SQL: create a transient instance from the purchase order table and then
perform some extraction on it. Assume po_xml_tab contains the data shown in
Example 416, "Inserting XML Data Using XMLType() with String", modied:
set serverout on
declare
poxml XMLType;
cust XMLType;
val VARCHAR2(200);
begin
-- select the adt instance
select poDoc into poxml
from po_xml_tab p where p.poid = 100;
-- do some traversals and print the output
cust := poxml.extract('//SHIPADDR');
-- do something with the customer XML fragment
val := cust.getStringVal();
dbms_output.put_line(' The customer XML value is '|| val);
end;
/
Example 426 Extracting Data from an XML Document and Inserting It Into a Table
Using extract()
The following example shows how you can extract out data from an XML purchase
order and insert it into an SQL relational table. Consider the following relational
tables:
CREATE TABLE cust_tab
(
custid number primary key,
custname varchar2(20)
);
INSERT INTO cust_tab values (1001, 'John Nike');
See Also: "XMLType Member Functions" on page 4-7
Selecting and Querying XML Data
4-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
CREATE TABLE po_rel_tab
(
pono number,
pname varchar2(100),
custid number references cust_tab,
shipstreet varchar2(100),
shipcity varchar2(30),
shipzip varchar2(20)
);
You can write a simple PL/SQL block to transform XML of the form:
<?xml version = '1.0'?>
<PO>
<PONO>2001</PONO>
<PNAME>Po_1</PNAME>
<CUSTOMER CUSTNAME="John Nike"/>
<SHIPADDR>
<STREET>323 College Drive</STREET>
<CITY>Edison</CITY>
<STATE>NJ</STATE>
<ZIP>08820</ZIP>
</SHIPADDR>
</PO>
into the relational tables, using extract().
Here is an SQL example assuming that the XML described in the previous example
is present in the po_xml_tab:
INSERT INTO po_rel_tab
SELECT p.poDoc.extract('/PO/PONO/text()').getnumberval() as pono,
p.poDoc.extract('/PO/PNAME/text()').getstringval() as pname,
-- get the customer id corresponding to the customer name
( SELECT c.custid
FROM cust_tab c
WHERE c.custname = p.poDoc.extract('/PO/CUSTOMER/@CUSTNAME').getstringval()
) as custid,
p.poDoc.extract('/PO/SHIPADDR/STREET/text()').getstringval() as shipstreetr,
p.poDoc.extract('//CITY/text()').getstringval() as shipcity,
p.poDoc.extract('//ZIP/text()').getstringval() as shipzip
FROM po_xml_tab p;
Table po_tab should now have the following values:
Selecting and Querying XML Data
Using XMLType 4-29
PONO PNAME CUSTID SHIPSTREET SHIPCITY SHIPZIP
----------------------------------------------------------------
2001 Po_1 1001 323 College Drive Edison 08820
Example 427 Extracting Data from an XML Document and Inserting It Into a Table
Using extract() In a PL/SQL Block
You can do the same in an equivalent fashion inside a PL/SQL block, as follows:
DECLARE
poxml XMLType;
cname varchar2(200);
pono number;
pname varchar2(100);
shipstreet varchar2(100);
shipcity varchar2(30);
shipzip varchar2(20);
BEGIN
-- select the adt instance
SELECT poDoc INTO poxml FROM po_xml_tab p;
cname := poxml.extract('//CUSTOMER/@CUSTNAME').getstringval();
pono := poxml.extract('/PO/PONO/text()').getnumberval();
pname := poxml.extract('/PO/PNAME/text()').getstringval();
shipstreet := poxml.extract('/PO/SHIPADDR/STREET/text()').getstringval();
shipcity := poxml.extract('//CITY/text()').getstringval();
shipzip := poxml.extract('//ZIP/text()').getstringval();
INSERT INTO po_rel_tab
VALUES (pono, pname,
(SELECT custid FROM cust_tab c WHERE custname = cname),
shipstreet, shipcity, shipzip);
END;
/
Note: PNAME is null, since the input XML document did not have
the element called PNAME under PO. Also, the preceding example
used //CITY to search for the city element at any depth.
Selecting and Querying XML Data
4-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 428 Searching XML Data with extract() and existsNode()
Using extract() and existsNode() functions, you can perform a variety of
search operations on the column, as follows:
SELECT e.poDoc.extract('/PO/PNAME/text()').getStringVal() PNAME
FROM po_xml_tab e
WHERE e.poDoc.existsNode('/PO/SHIPADDR') = 1 AND
e.poDoc.extract('//PONO/text()').getNumberVal() = 300 AND
e.poDoc.extract('//@CUSTNAME').getStringVal() like '%John%';
This SQL statement extracts the purchase order name PNAME frompurchase order
element PO, from all XML documents containing a shipping address with a
purchase order number of 300, and a customer name CUSTNAME containing the
string John.
Example 429 Searching XML Data with extractValue()
Using extractValue(), you can rewrite the preceding query as:
SELECT extractvalue(e.poDoc, '/PO/PNAME') PNAME
FROM po_xml_tab e
WHERE e.poDoc.existsNode('/PO/SHIPADDR') = 1 AND
extractvalue(e.poDoc,'//PONO') = 300 AND
extractvalue(e.poDoc,'//@CUSTNAME') like '%John%';
Example 430 Extracting Fragments from XMLType Using extract()
extract() member function extracts nodes identied by the XPath expression and
returns an XMLType containing the fragment. Here, the result of the traversal may
be a set of nodes, a singleton node, or a text value. You can check if the result is a
fragment by using the isFragment() function on the XMLType. For example:
SELECT e.poDoc.extract('/PO/SHIPADDR/STATE').isFragment()
FROM po_xml_tab e;
The previous SQL statement returns 0, since the extraction /PO/SHIPADDR/STATE
returns a singleton well-formed node which is not a fragment.
Note: You cannot insert fragments into XMLType columns. You
can use SYS_XMLGEN() to convert a fragment into a
well-formed document by adding an enclosing tag. See "SYS_
XMLGEN() Function" on page 10-42. You can, however, query
further on the fragment using the various XMLType functions.
Updating XML Instances and Data in Tables and Columns
Using XMLType 4-31
On the other hand, an XPath such as /PO/SHIPADDR/STATE/text() is
considered a fragment, since it is not a well-formed XML document.
Updating XML Instances and Data in Tables and Columns
This section talks about updating transient XML instances and XML data stored in
tables.
With CLOB-based storage, in this release, an update effectively replaces the whole
document. Use the SQL UPDATE statement to update the whole XML document.
The right hand side of the UPDATEs SET clause must be an XMLType instance.
This can be created using the SQL functions and XML constructors that return an
XML instance, or using the PL/SQL DOM APIs for XMLType or Java DOM API,
that change and bind existing XML instances.
updateXML() SQL Function
updateXML() function takes in a source XMLType instance, and a set of XPath
value pairs. It returns a new XML instance consisting of the original XMLType
instance with appropriate XML nodes updated with the given values. The optional
namespace parameter species the namespace mapping of prex(es) in the XPath
parameters.
updateXML() can be used to update, replace elements, attributes and other nodes
with new values. They cannot be directly used to insert new nodes or delete
existing ones. The containing parent element should be updated with the new
values instead.
updateXML() updates only the transient XML instance in memory. Use an SQL
UPDATE statement to update data stored in tables. The updateXML() syntax is:
UPDATEXML(xmlinstance, xpath1, value_expr1
[, xpath2, value_expr2]...[,namespace_string]);
Example 431 Updating XMLType Using the UPDATE Statement
This example updates the XMLType using the UPDATE statement. It updates only
those documents whose purchase order number is 2001.
UPDATEXML ( XMLType_instance , XPath_string , value_expr
,
, namespace_string
)
Updating XML Instances and Data in Tables and Columns
4-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
UPDATE po_xml_tab e
SET e.poDoc = XMLType(
'<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>Nance</CUSTNAME>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>')
WHERE e.poDoc.EXTRACT('/PO/PONO/text()').getNumberVal() = 2001;
Example 432 Updating XMLType Using UPDATE and updateXML()
To update the XML document in the table instead of creating a new one, you can
use the updateXML() in the right hand side of an UPDATE statement to update
the document.
UPDATE po_xml_tab
SET poDoc = UPDATEXML(poDoc,
/PO/CUSTNAME/text(), John);
1 row updated
SELECT e.poDoc.getstringval() AS newpo
FROM po_xml_tab e;
NEWPO
--------------------------------------------------------------------
<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>John</CUSTNAME>
<SHIPADDR>
Note: Updates for non- schema based XML documents always
update the whole XML document.
Note: This will also update the whole document, not just the part
updated.
Updating XML Instances and Data in Tables and Columns
Using XMLType 4-33
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
Example 433 Updating Multiple Elements in the Column Using updateXML()
You can update multiple elements within a single updateXML() expression. For
instance, you can use the same UPDATE statement as shown in the preceding
example and update purchase order, po:
UPDATE emp_tab e
SET e.emp_col = UPDATEXML(e.emp_col,
'/EMPLOYEES/EMP[EMPNAME="Joe"]/SALARY/text()',100000,
'//EMP[EMPNAME="Jack"]/EMPNAME/text()','Jackson',
'//EMP[EMPNO=217]',XMLTYPE.CREATEXML(
'<EMP><EMPNO>217</EMPNO><EMPNAME>Jane</EMPNAME></EMP>'))
WHERE EXISTSNODE(e.emp_col, '//EMP') = 1;
This updates all rows that have an employee element with the new values.
Example 434 Updating Customer Name in Purchase Order XML Document Using
updateXML()
The following example updates the customer name in the purchase order XML
document, po:
SELECT
UPDATEXML(poDoc,
/PO/CUSTNAME/text(), John).getstringval() AS updatedPO
FROM po_xml_tab;
UPDATEDPO
--------------------------------------------------------------------
<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>John</CUSTNAME>
Note: This example only selects the document and the update
occurs on a transient XMLType instance. The original document is
not affected.
Updating XML Instances and Data in Tables and Columns
4-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
Example 435 Updating Multiple Transient XML Instances Using updateXML()
You can also use updateXML() to update multiple pieces of a transient instance.
For example, consider the following XML document stored in column emp_col of
table, emp_tab:
<EMPLOYEES>
<EMP>
<EMPNO>112</EMPNO>
<EMPNAME>Joe</EMPNAME>
<SALARY>50000</SALARY>
</EMP>
<EMP>
<EMPNO>217</EMPNO>
<EMPNAME>Jane</EMPNAME>
<SALARY>60000</SALARY>
</EMP>
<EMP>
<EMPNO>412</EMPNO>
<EMPNAME>Jack</EMPNAME>
<SALARY>40000</SALARY>
</EMP>
</EMPLOYEES>
To generate a newdocument with Joes salary updated to 100,000, update the Name
of Jack to Jackson, and modify the Employee element for 217, to remove the salary
element. You can write a query such as:
SELECT UPDATEXML(emp_col, '/EMPLOYEES/EMP[EMPNAME="Joe"]/SALARY/text()', 100000,
'//EMP[EMPNAME="Jack"]/EMPNAME/text()','Jackson',
'//EMP[EMPNO=217]',
XMLTYPE.CREATEXML('<EMP><EMPNO>217</EMPNO><EMPNAME>Jane</EMPNAME>'))
FROM emp_tab e;
This generates the following updated XML:
<EMPLOYEES>
<EMP>
<EMPNO>112</EMPNO>
Updating XML Instances and Data in Tables and Columns
Using XMLType 4-35
<EMPNAME>Joe</EMPNAME>
<SALARY>100000</SALARY>
</EMP>
<EMP>
<EMPNO>217</EMPNO>
<EMPNAME>Jane</EMPNAME>
</EMP>
<EMP>
<EMPNO>412</EMPNO>
<EMPNAME>Jackson</EMPNAME>
<SALARY>40000</SALARY>
</EMP>
</EMPLOYEES>
Creating Views of XML Data with updateXML()
You can use updateXML() to create new views of XML data. This can be useful
when you do not want a particular set of users to see sensitive data such as
SALARY.
Example 436 Creating Views Using updateXML()
A view such as:
CREATE VIEW new_emp_view
AS SELECT
UPDATEXML(emp_col, '/EMPLOYEES/EMP/SALARY/text()', 0) emp_view_col
FROM emp_tab e;
ensures that users selecting from view, new_emp_view, do not see the SALARY
eld for any employee.
Optimization of updateXML()
In most cases, updateXML() materializes the whole input XML document in
memory and updates the values. However, it is optimized for UPDATE statements
on XML schema-based object-relationally stored XMLType tables and columns so
that the function updates the value directly in the column.
The conditions for rewrite are explained in Chapter 5, "Structured Mapping of
XMLType", "Query Rewrite with XML Schema-Based Structured Storage" on
page 5-51, in detail. If all of the rewrite conditions are met, then the updateXML()
is rewritten to update the object-relational columns directly with the values. For
example, the following UPDATE statement:
Updating XML Instances and Data in Tables and Columns
4-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
UPDATE po_xml_tab
SET poDoc = UPDATEXML(poDoc,
/PO/CUSTNAME/text(), John);
could get rewritten (if the rewrite rules are satised) to an UPDATE of the
custname column directly:
UPDATE po_xml_tab p
SET p.xmldata.CUSTNAME = John;
updateXML() and NULL Values
If you update an XML element to null, Oracle removes the attributes and children of
the element, and the element becomes empty. The type and namespace properties of
the element are retained. A NULL value for an element update is equivalent to
setting the element to empty.
If you update the text node of an element to null, Oracle removes the text value of
the element, and the element itself remains but is empty. For example, if you update
node, '/empno/text()' with a NULL value, the text values for the empno
element are removed and the empno element becomes empty.
Setting an attribute to NULL, similarly sets the value of the attribute to the empty
string.
You cannot use updateXML() to remove, add, or delete a particular element or an
attribute. You have to update the containing element with a new value.
Example 437 NULL Updates with updateXML()
Consider the XML document:
<PO>
<pono>21</pono>
<shipAddr gate="xxx">
<street>333</street>
<city>333</city>
</shipAddr>
</PO>
The clause:
Note: Setting 'empno' to NULL has the same effect as setting
'empno/text()' to NULL, if empno is a simple scalar element with
no attributes.
Updating XML Instances and Data in Tables and Columns
Using XMLType 4-37
updateXML(xmlcol,'/PO/shipAddr',null)
is equivalent to making it:
<PO>
<pono>21</pono>
<shipAddr/>
</PO>
If you update the text node to NULL, then this is equivalent to removing the text
value alone. For example:
UPDATEXML(xmlcol,'/PO/shipAddr/street/text()', null)
results in:
<PO>
<pono>21</pono>
<shipAddr>
<street/>
<city>333</city>
</shipAddr>
</PO>
Updating the Same XML Node More Than Once
You can update the same XML node more than once in the updateXML()
statement. For example, you can update both /EMP[EMPNO=217] and
/EMP[EMPNAME=Jane]/EMPNO, where the rst XPath identies the EMPNO node
containing it as well. The order of updates is determined by the order of the XPath
expressions in left-to-right order. Each successive XPath works on the result of the
previous XPath update.
XMLTransform() Function
The XMLTransform() function takes in an XMLType instance and an XSLT
stylesheet. It applies the stylesheet to the XML document and returns a transformed
XML instance. See Figure 45.
Figure 45 XMLTransform() Syntax
XMLTRANSFORM ( XMLType_instance , XMLType_instance )
Deleting XML Data
4-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XMLTransform() is explained in detail in Chapter 6, "Transforming and
Validating XMLType Data".
Deleting XML Data
DELETEs on the row containing the XMLType column are handled in the same way
as any other datatype.
Example 438 Deleting Rows Using extract()
For example, to delete all purchase order rows with a purchase order name of Po_
2, execute a statement such as:
DELETE FROM po_xml_tab e
WHERE e.poDoc.extract('/PO/PNAME/text()').getStringVal()='Po_2';
Using XMLType In Triggers
You can use the new and old binds inside triggers to read and modify the XMLType
column values. For INSERT and UPDATE statements, you can modify the new
value to change the value being inserted.
Example 439 Creating XMLType Triggers
For example, you can write a trigger to change the purchase order if it does not
contain a shipping address:
CREATE OR REPLACE TRIGGER po_trigger
BEFORE INSERT OR UPDATE ON po_xml_tab FOR EACH ROW
declare
pono Number;
begin
if inserting then:
if :NEW.poDoc.existsnode('//SHIPADDR') = 0 then
:NEW.poDoc := xmltype('<PO>INVALID_PO</PO>'); end if;
end if;
when updating, if the old poDoc has purchase order number different fromthe new
one then make it an invalid PO.
if updating then:
if :OLD.poDoc.extract('//PONO/text()').getNumberVal() !=
Indexing XMLType Columns
Using XMLType 4-39
:NEW.poDoc.extract('//PONO/text()').getNumberVal() then
:NEW.poDoc := xmltype('<PO>INVALID_PO</PO>');
end if;
end if;
end;
/
This example is only an illustration. You can use the XMLType value to perform
useful operations inside the trigger, such as validation of business logic or rules that
the XML document should conform to, auditing, and so on.
Indexing XMLType Columns
You can create the following indexes when using XMLType. Indexing speeds up
query evaluation.
Creating Function-Based Indexes on XMLType Columns
You can speed up by queries by building function-based indexes on
existsNode() or those portions of the XML document that use extract().
Example 440 Creating a Function-Based Index on an extract() Function
For example, to speed up the search on the query,
SELECT * FROM po_xml_tab e
WHERE e.poDoc.extract(//PONO/text()).getNumberVal()= 100;
you can create a function-based index on the extract() function as follows:
CREATE INDEX city_index ON po_xml_tab
(poDoc.extract('//PONO/text()').getNumberVal());
The SQL query uses this function-based index, to evaluate the predicate instead of
parsing the XML document row by row, and evaluating the XPath expression.
Example 441 Creating a Function-Based index on an existsNode() Function
You can also create bitmapped function-based indexes to speed up the evaluation of
the operators. existsNode() is suitable, since it returns a value of 1 or 0
depending on whether the XPath is satised in the XML document or not.
Indexing XMLType Columns
4-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
For example, to speed up a query that searches whether the XML document
contains an element called Shipping address (SHIPADDR) at any level:
SELECT * FROM po_xml_tab e
WHERE e.poDoc.existsNode(//SHIPADDR) = 1;
you can create a bitmapped function-based index on the existsNode() function
as follows:
CREATE BITMAP INDEX po_index ON po_xml_tab
(poDoc.existsNode('//SHIPADDR'));
This speeds up the query processing.
Creating Oracle Text Indexes on XMLType Columns
Oracle Text index works on CLOB and VARCHAR columns. It has been extended
in Oracle9i to also work on XMLType columns. The default behavior of Oracle Text
index is to automatically create XML sections, when dened over XMLType
columns. Oracle Text also provides the CONTAINS operator which has been
extended to support XPath.
In general, Oracle Text indexes can be created using the CREATE INDEX SQL
statement with the INDEXTYPE specied as for other CLOB or VARCHAR columns.
Oracle Text indexes on XMLType columns, however, are created as function-based
indexes.
Example 442 Creating an Oracle Text Index
CREATE INDEX po_text_index ON
po_xml_tab(poDoc) indextype is ctxsys.context;
You can also perform Oracle Text operations such as CONTAINS and SCORE. on
XMLType columns. In Oracle9i Release (9.0.1), the CONTAINS operator was
enhanced to support XPath using two new operators, INPATH and HASPATH:
I INPATH checks if the given word appears within the path specied.
I HASPATH checks if the given XPath is present in the XML document.
Example 443 Searching XML Data Using HASPATH
For example:
SELECT * FROM po_xml_tab w
WHERE CONTAINS(w.poDoc,
Indexing XMLType Columns
Using XMLType 4-41
'haspath(/PO[./@CUSTNAME="John Nike"])') > 0;
QUERY_REWRITE PRIVILEGE Is No Longer Needed
In Oracle9i Release (9.0.1), to create and use Oracle Text index in queries, in
addition to having the privileges for creating indexes and for creating Oracle Text
indexes, you also needed privileges and settings for creating function-based
indexes:
I QUERY_REWRITE privilege. You must have this privilege granted to create text
indexes on XMLType columns in your own schema.
I GLOBAL_QUERY_REWRITE privilege. If you need to create Oracle Text indexes
on XMLType columns in other schemas or on tables residing in other schemas,
you must have this privilege granted.
Oracle Text index uses the PATH_SECTION_GROUP as the default section group
when indexing XMLType columns. This default can be overridden during Oracle
Text index creation.
With this release, you no longer need the additional QUERY_REWRITE privileges
when creating Oracle Text indexes.
Creating XPath Indexes on XMLType Columns: CTXXPATH Index
existsNode() SQL function, unlike the CONTAINS operator, cannot use Oracle
Text indexes to speed up its evaluation. To improve the performance of XPath
searches in existsNode(), this release introduces a new index type, CTXXPATH.
CTXXPATH index is a newindextype provided by Oracle Text. It is designed to serve
as a primary lter for existsNode() processing, that is, it produces a superset of
See Also:
I Chapter 7, "Searching XML Data with Oracle Text"
I Chapter 10, "Generating XML Data from the Database"
I Oracle Text Reference
I Oracle Text Application Developers Guide
Note: The QUERY_REWRITE_INTEGRITY and QUERY_REWRITE_
ENABLED session settings are no longer needed to create Oracle
Text or other function-based indexes on XMLType columns.
Indexing XMLType Columns
4-42 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
the results that would be produced by the existNode() function. The
existsNode() functional implementation is then applied on the results to return
the correct set of rows.
CTXXPATH index can handle XPath path searching, wildcards, and string equality
predicates.
Example 444 Using CTXXPATH Index or existsNode() for XPath Searching
CREATE INDEX po_text_index ON
po_xml_tab(poDoc) indextype is ctxsys.ctxxpath;
For example, a query such as:
SELECT *
FROM po_xml_doc w
WHERE existsNode(w.poDoc,/PO[@CUSTNAME="John Nike"]) = 1;
could potentially use CTXXPATH indexing to satisfy the existsNode() predicate.
Differences Between CONTAINS and existsNode()/extract()
The differences in XPath support when using CONTAINS compared to XPath
support with existsNode() and extract() functions are:
I Since Oracle Text index ignores spaces, the XPath expression may not yield
accurate results when spaces are signicant.
I Oracle Text index also supports certain predicate expressions with string
equality, but cannot support numerical and range comparisons.
I Oracle Text index may give wrong results if the XML document only has tag
names and attribute names without any text. For example, consider the
following XML document:
<A>
<B>
<C>
</C>
</B>
<D>
See Also:
I Chapter 7, "Searching XML Data with Oracle Text"
I Chapter 10, "Generating XML Data from the Database"
Indexing XMLType Columns
Using XMLType 4-43
<E>
</E>
</D>
</A>
the XPath expression - A/B/E falsely matches the preceding XML document.
I Both the function-based indexes and Oracle Text indexes support navigation.
Thus you can use the Oracle Text index as a primary lter, to lter out all
documents that potentially match the criterion, efciently, and then apply
secondary lters such as existsNode() or extract() operations on the
remainder of the XML documents.
See Also: Chapter 7, "Searching XML Data with Oracle Text",
Table 76, "Using CONTAINS() and existsNode() to Search
XMLType Data" on page 7-38
Indexing XMLType Columns
4-44 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Structured Mapping of XMLType 5-1
5
Structured Mapping of XMLType
This chapter introduces XML Schema and explains how XML schema are used in
Oracle XML DB applications. It describes how to register your XML schema and
create storage structures for storing schema-based XML. It explains in detail the
mapping from XML to SQL storage types, including techniques for maintaining the
DOM delity of XML data.This chapter also describes how queries over XMLType
tables and columns based on this mapping are optimized using query rewrite
techniques. It discusses the mechanism for generating XML schemas from existing
object types.
This chapter contains the following sections:
I Introducing XML Schema
I XML Schema and Oracle XML DB
I Using Oracle XML DB and XML Schema
I Introducing DBMS_XMLSCHEMA
I Registering Your XML Schema Before Using Oracle XML DB
I Deleting Your XML Schema Using DBMS_XMLSCHEMA
I Guidelines for Using Registered XML Schemas
I Generating XML Schema Using DBMS_XMLSCHEMA.generateSchema()
I XML Schema-Related Methods of XMLType
I Managing and Storing XML Schema
I DOM Fidelity
I Creating XMLType Tables and Columns Based on XML Schema
I Specifying SQL Object Type Names with SQLName, SQLType Attributes
5-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Mapping of Types Using DBMS_XMLSCHEMA
I XML Schema: Mapping SimpleTypes to SQL
I XML Schema: Mapping complexTypes to SQL
I Oracle XML DB complexType Extensions and Restrictions
I Further Guidelines for Creating XML Schema-Based XML Tables
I Query Rewrite with XML Schema-Based Structured Storage
I Creating Default Tables During XML Schema Registration
I Ordered Collections in Tables (OCTs)
I Cyclical References Between XML Schemas
I Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
XML Schema and Oracle XML DB
Structured Mapping of XMLType 5-3
Introducing XML Schema
The XML Schema Recommendation was created by the World Wide Web
Consortium (W3C) to describe the content and structure of XML documents in
XML. It includes the full capabilities of Document Type Denitions (DTDs) so that
existing DTDs can be converted to XML schema. XML schemas have additional
capabilities compared to DTDs.
XML Schema and Oracle XML DB
XML Schema is a schema denition language written in XML. It can be used to
describe the structure and various other semantics of conforming instance
documents. For example, the following XML schema denition, po.xsd, describes
the structure and other properties of purchase order XML documents.
This manual refers to an XML schema denition as an XML schema.
Example 51 XML Schema Denition, po.xsd
The following is an example of an XML schema denition, po.xsd:
<schema targetNamespace="http://www.oracle.com/PO.xsd"
xmlns:po="http://www.oracle.com/PO.xsd"
xmlns="http://www.w3.org/2001/XMLSchema">
<complexType name="PurchaseOrderType">
<sequence>
<element name="PONum" type="decimal"/>
<element name="Company">
<simpleType>
<restriction base="string">
<maxLength value="100"/>
</restriction>
</simpleType>
</element>
<element name="Item" maxOccurs="1000">
<complexType>
<sequence>
<element name="Part">
<simpleType>
<restriction base="string">
<maxLength value="1000"/>
</restriction>
</simpleType>
See Also: Appendix B, "XML Schema Primer"
XML Schema and Oracle XML DB
5-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</element>
<element name="Price" type="float"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<element name="PurchaseOrder" type="po:PurchaseOrderType"/>
</schema>
Example 52 XML Document, po.xml Conforming to XML Schema, po.xsd
The following is an example of an XML document that conforms to XML schema
po.xsd:
<PurchaseOrder xmlns="http://www.oracle.com/PO.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/PO.xsd
http://www.oracle.com/PO.xsd">
<PONum>1001</PONum>
<Company>Oracle Corp</Company>
<Item>
<Part>9i Doc Set</Part>
<Price>2550</Price>
</Item>
</PurchaseOrder>
Using Oracle XML DB and XML Schema
Structured Mapping of XMLType 5-5
Using Oracle XML DB and XML Schema
Oracle XML DB uses annotated XML schema as metadata, that is, the standard
XML Schema denitions along with several Oracle XML DB-dened attributes.
These attributes are in a different namespace and control how instance documents
get mapped into the database. Since these attributes are in a different namespace
fromthe XML schema namespace, such annotated XML schemas are still legal XML
schema documents:
When using Oracle XML DB, you must rst register your XML schema. You can
then use the XML schema URLs while creating XMLType tables, columns, and
views.
Oracle XML DB provides XML Schema support for the following tasks:
I Registering any W3C-compliant XML schemas.
Note:
The URL http://www.oracle.com/PO.xsd used here is
simply a name that uniquely identies the registered XML schema
within the database and need not be the physical URL at the which
the XML schema document is located. Also, the target namespace
of the XML schema is another URL, different fromthe XML schema
location URL, that species an abstract namespace within which
elements and types get declared.
An XML schema can optionally specify the target namespace URL.
If this attribute is omitted, the XML schema has no target
namespace. Note: The targetnamespace is commonly the same
as XML schemas URL.
An XML instance document must specify both the namespace of
the root element (same as the XML schemas target namespace) and
the location (URL) of the XML schema that denes this root
element. The location is specied with attribute
xsi:schemaLocation. When the XML schema has no target
namespace, use attribute xsi:noNamespaceSchemaLocation to
specify the XML schema URL.
See Also: Namespace of XML Schema constructs:
http://www.w3.org/2001/XMLSchema
Using Oracle XML DB and XML Schema
5-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Validating your XML documents against a registered XML schema denitions.
I Registering local and global XML schemas.
I Generating XML schema from object types.
I Referencing an XML schema owned by another user.
I Explicitly referencing a global XML schema when a local XML schema exists
with the same name.
I Generating a structured database mapping from your XML schemas during
XML schema registration. This includes generating SQL object types, collection
types, and default tables, and capturing the mapping information using XML
schema attributes.
I Specifying a particular SQL type mapping when there are multiple legal
mappings.
I Creating XMLType tables, views and columns based on registered XML
schemas.
I Performing manipulation (DML) and queries on XML schema-based XMLType
tables.
I Automatically inserting data into default tables when schema-based XML
instances are inserted into Oracle XML DB Repository using FTP,
HTTP/WebDav protocols and other languages.
Why Do We Need XML Schema?
As described in Chapter 4, "Using XMLType", XMLType is a datatype that facilitates
storing XML in columns and tables in the database. XML schemas further facilitate
storing XML columns and tables in the database, and they offer you more storage
and access options for XML data along with space- performance-saving options.
For example, you can use XML schema to declare which elements and attributes can
be used and what kinds of element nesting, and datatypes are allowed in the XML
documents being stored or processed.
XML Schema Provides Flexible XML-to-SQL Mapping Setup
Using XML schema with Oracle XML DB provides a exible setup for XML storage
mapping. For example:
See Also: Chapter 26, "Oracle XML DB Basic Demo"
Using Oracle XML DB and XML Schema
Structured Mapping of XMLType 5-7
I If your data is highly structured (mostly XML), each element in the XML
documents can be stored as a column in a table.
I If your data is unstructured (all or mostly non-XML data), the data can be
stored in a Character Large Object (CLOB).
Which storage method you choose depends on how your data will be used and
depends on the queriability and your requirements for querying and updating your
data. In other words. Using XML schema gives you more exibility for storing
highly structured or unstructured data.
XML Schema Allows XML Instance Validation
Another advantage of using XML schema with Oracle XML DB is that you can
perform XML instance validation according to the XML schema and with respect to
Oracle XML Repository requirements for optimal performance. For example, an
XML schema can check that all incoming XML documents comply with denitions
declared in the XML schema, such as allowed structure, type, number of allowed
item occurrences, or allowed length of items.
Also, by registering XML schema in Oracle XML DB, when inserting and storing
XML instances using Protocols, such as FTP or HTTP, the XML schema information
can inuence how efciently XML instances are inserted.
When XML instances must be handled without any prior information about them,
XML schema can be useful in predicting optimum storage, delity, and access.
DTD Support in Oracle XML DB
In addition to supporting XML schema that provide a structured mapping to object-
relational storage, Oracle XML DB also supports DTD specications in XML
instance documents. Though DTDs are not used to derive the mapping, XML
processors can still access and interpret the DTDs.
Inline DTD Definitions
When an XML instance document has an inline DTD denition, it is used during
document parsing. Any DTD validations and entity declaration handling is done at
this point. However, once parsed, the entity references are replaced with actual
values and the original entity reference is lost.
Introducing DBMS_XMLSCHEMA
5-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
External DTD Definitions
Oracle XML DB also supports external DTD denitions if they are stored in the
Repository. Applications needing to process an XML document containing an
external DTD denition such as /public/ights.dtd, must rst ensure that the
DTD document is stored in Oracle XML DB at the path /public/ights.xsd.
Introducing DBMS_XMLSCHEMA
Oracle XML DBs XML schema functionality is available through the PL/SQL
supplied package, DBMS_XMLSCHEMA, a server-side component that handles the
registration of XML schema denitions for use by Oracle XML DB applications.
Two of the main DBMS_XMLSCHEMA functions are:
I registerSchema(). This registers an XML schema given:
I XML schema source, which can be in a variety of formats, including string,
LOB, XMLType, and URIType
I Its schema URL or XMLSchema name
I deleteSchema(). This deletes a previously registered XML schema,
identied by its URL or XMLSchema name.
Registering Your XML Schema Before Using Oracle XML DB
An XML schema must be registered before it can be used or referenced in any
context by Oracle XML DB. XML schema are registered by using DBMS_
XMLSCHEMA.registerSchema() and specifying the following:
I The XML schema source document as a VARCHAR, CLOB, XMLType, or
URIType.
I The XML schema URL. This is a name for the XML schema that is used within
XML instance documents to specify the location of the XML schema to which
they conform.
After registration has completed:
I XML documents conforming to this XML schema, and referencing it using the
XML schemas URL within the XML document, can be processed by Oracle
XML DB.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Registering Your XML Schema Before Using Oracle XML DB
Structured Mapping of XMLType 5-9
I Tables and columns can be created for root XML elements dened by this XML
schema to store the conforming XML documents.
Registering Your XML Schema Using DBMS_XMLSCHEMA
Use DBMS_XMLSCHEMA to register your XML schema. This involves specifying the
XML schema document and its URL, also known as the XML schema location.
Example 53 Registering an XML Schema That Declares a complexType Using
DBMS_XMLSCHEMA
Consider the following XML schema. It declares a complexType called
PurchaseOrderType and an element PurchaseOrder of this type. The schema
is stored in the PL/SQL variable doc. The following registers the XML schema at
URL: http://www.oracle.com/PO.xsd:
declare
doc varchar2(1000) := <schema
targetNamespace="http://www.oracle.com/PO.xsd"
xmlns:po="http://www.oracle.com/PO.xsd"
xmlns="http://www.w3.org/2001/XMLSchema">
<complexType name="PurchaseOrderType">
<sequence>
<element name="PONum" type="decimal"/>
<element name="Company">
<simpleType>
<restriction base="string">
<maxLength value="100"/>
</restriction>
</simpleType>
</element>
<element name="Item" maxOccurs="1000">
<complexType>
<sequence>
<element name="Part">
<simpleType>
<restriction base="string">
<maxLength value="1000"/>
</restriction>
</simpleType>
</element>
<element name="Price" type="float"/>
</sequence>
</complexType>
Registering Your XML Schema Before Using Oracle XML DB
5-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</element>
</sequence>
</complexType>
<element name="PurchaseOrder" type="po:PurchaseOrderType"/>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
The registered schema can be used to created XML schema-Based tables, or XML
schema-based columns. For example, the following statement creates an a table
with an XML schema-based column.
create table po_tab(
id number,
po sys.XMLType
)
xmltype column po
XMLSCHEMA "http://www.oracle.com/PO.xsd"
element "PurchaseOrder";
The following shows an XMLType instance that conforms to the preceding XML
schema being inserted into the preceding table. The schemaLocation attribute
species the schema URL:
insert into po_tab values (1,
xmltype('<po:PurchaseOrder xmlns:po="http://www.oracle.com/PO.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/PO.xsd
http://www.oracle.com/PO.xsd">
<PONum>1001</PONum>
<Company>Oracle Corp</Company>
<Item>
<Part>9i Doc Set</Part>
<Price>2550</Price>
</Item>
<Item>
<Part>8i Doc Set</Part>
<Price>350</Price>
</Item>
</po:PurchaseOrder>'));
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Registering Your XML Schema Before Using Oracle XML DB
Structured Mapping of XMLType 5-11
Local and Global XML Schemas
XML schemas can be registered as local or global:
I Local XML schema: An XML schema registered as a local schema is, by default,
visible only to the owner.
I Global XML schema: An XML schema registered as a global schema is, by
default, visible and usable by all database users.
When you register an XML schema, DBMS_XMLSCHEMA adds an Oracle XML DB
resource corresponding to the XML schema into the Oracle XML DB Repository.
The XML schema URL determines the path name of the resource in Oracle XML DB
Repository according to the following rules:
Local XML Schema
In Oracle XML DB, local XML schema resources are created under the
/sys/schemas/<username> directory. The rest of the path name is derived from
the schema URL.
Example 54 A Local XML Schema
For example, a local XML schema with schema URL:
http://www.myco.com/PO.xsd
registered by SCOTT, is given the path name:
/sys/schemas/SCOTT/www.myco.com/PO.xsd.
Database users need appropriate permissions (ACLs) to create a resource with this
path name in order to register the XML schema as a local XML schema.
By default, an XML schema belongs to you after registering the XML schema with
Oracle XML DB. A reference to the XML schema document is stored in Oracle XML
DB Repository, in directory:
/sys/schemas/<username>/....
For example, if you, SCOTT, registered the preceding XML schema, it is mapped to
the le:
/sys/schemas/SCOTT/www.oracle.com/PO.xsd
See Also: Chapter 18, "Oracle XML DB Resource Security"
Registering Your XML Schema Before Using Oracle XML DB
5-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Such XML schemas are referred to as local. In general, they are usable only by you to
whom they belong.
Global XML Schema
In contrast to local schema, privileged users can register an XML schema as a global
XML schema by specifying an argument in the DBMS_XMLSCHEMA registration
function.
Global schemas are visible to all users and stored under the
/sys/schemas/PUBLIC/ directory in Oracle XML DB Repository.
You can register a local schema with the same URL as an existing global schema. A
local schema always hides any global schema with the same name (URL).
Example 55 A Global XML Schema
For example, a global schema registered by SCOTT with the URL:
www.myco.com/PO.xsd
is mapped to Oracle XML DB Repository at:
Note: Typically, only the owner of the XML schema can use it to
dene XMLType tables, columns, or views, validate documents, and
so on. However, Oracle supports fully qualied XML schema URLs
which can be specied as:
http://xmlns.oracle.com/xdb/schemas/SCOTT/www.orac
le.com/PO.xsd
This extended URL can be used by privileged users to specify XML
schema belonging to other users.
Note: Access to this directory is controlled by Access Control Lists
(ACLs) and, by default, is writable only by a DBA. You need
WRITE privileges on this directory to register global schemas.
XDBAdmin role also provides WRITE access to this directory,
assuming that it is protected by the default protected ACL.
See also Chapter 18, "Oracle XML DB Resource Security" for further
information on privileges and for details on XDBAdmin role.
Deleting Your XML Schema Using DBMS_XMLSCHEMA
Structured Mapping of XMLType 5-13
/sys/schemas/PUBLIC/www.myco.com/PO.xsd
Database users need appropriate permissions (ACLs) to create this resource in order
to register the XML schema as global.
Registering Your XML Schema: Oracle XML DB Sets Up the Storage and Access
Infrastructure
As part of registering an XML schema, Oracle XML DB also performs several other
steps to facilitate storing, accessing, and manipulating XML instances that conform
to the XML schema. These steps include:
I Creating types: When an XML schema is registered, Oracle creates the
appropriate SQL object types that enable the structured storage of XML
documents that conform to this XML schema. You can use Oracle XML
DB-dened attributes in XML schema documents to control how these object
types are generated.
I Creating default tables: As part of XML schema registration, Oracle XML DB
generates default XMLType tables for all root elements. You can also specify any
column and table level constraints for use during table creation.
Deleting Your XML Schema Using DBMS_XMLSCHEMA
You can delete your registered XML schema by using the DBMS_
XMLSCHEMA.deleteSchema procedure. When you attempt to delete an XML
schema, DBMS_XMLSCHEMA checks:
I That the current user has the appropriate privileges (ACLs) to delete the
resource corresponding to the XML schema within Oracle XML DB Repository.
You can thus control which users can delete which XML schemas by setting the
appropriate ACLs on the XML schema resources.
I For dependents. If there are any dependents, it raises an error and the deletion
operation fails. This is referred to as the RESTRICT mode of deleting XML
schemas.
See Also:
I "Specifying SQL Object Type Names with SQLName, SQLType
Attributes" on page 5-24
I Chapter 3, "Using Oracle XML DB"
Guidelines for Using Registered XML Schemas
5-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
FORCE Mode
A FORCE mode option is provided while deleting XML schemas. If you specify the
FORCE mode option, the XML schema deletion proceeds even if it fails the
dependency check. In this mode, XML schema deletion marks all its dependents as
invalid.
CASCADE Mode
The CASCADE mode option drops all generated types and default tables as part of a
previous call to register XML schema.
Example 56 Deleting the XML Schema Using DBMS_XMLSCHEMA
The following example deletes XML schema PO.xsd. First, the dependent table
po_tab is dropped. Then, the schema is deleted using the FORCE and CASCADE
modes with DBMS_XMLSCHEMA.DELETESCHEMA:
drop table po_tab;
EXEC dbms_xmlschema.deleteSchema(http://www.oracle.com/PO.xsd,
dbms_xmlschema.DELETE_CASCADE_FORCE);
Guidelines for Using Registered XML Schemas
The following sections describe guidelines for registering XML schema with Oracle
XML DB.
Objects That Depend on Registered XML Schemas
The following objects depend on a registered XML schemas:
I Tables or views that have an XMLType column that conforms to some element
in the XML schema.
I XML schemas that include or import this schema as part of their denition.
I Cursors that reference the XML schema name, for example, within DBMS_
XMLGEN operators. Note that these are purely transient objects.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
the chapter on DBMS_XMLSCHEMA.
Guidelines for Using Registered XML Schemas
Structured Mapping of XMLType 5-15
Creating XMLType Tables, Views, or Columns
After an XML schema has been registered, it can be used to create XML
schema-based XMLType tables, views, and columns by referencing the following:
I The XML schema URL of a registered XML schema
I The name of the root element
Example 57 Post-Registration Creation of an XMLType Table
For example you can create an XML schema-based XMLType table as follows:
CREATE TABLE po_tab OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/PO.xsd" ELEMENT "PurchaseOrder";
The following statement inserts XML schema-conformant data:
insert into po_tab values (
xmltype(<PurchaseOrder xmlns="http://www.oracle.com/PO.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/PO.xsd
http://www.oracle.com/PO.xsd">
<PONum>1001</PONum>
<Company>Oracle Corp</Company>
<Item>
<Part>9i Doc Set</Part>
<Price>2550</Price>
</Item>
<Item>
<Part>8i Doc Set</Part>
<Price>350</Price>
</Item>
</PurchaseOrder>));
Validating XML Instances Against the XML Schema: schemaValidate()
You can validate an XMLType instance against a registered XML schema by using
one of the validation methods.
See Also: Chapter 6, "Transforming and Validating XMLType
Data"
Guidelines for Using Registered XML Schemas
5-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 58 Validating XML Using schemaValidate()
The following PL/SQL example validates an XML instance against XML schema
PO.xsd:
declare
xmldoc xmltype;
begin
-- populate xmldoc (by fetching from table)
select value(p) into xmldoc from po_tab p;
-- validate against XML schema
xmldoc.schemavalidate();
if xmldoc.isschemavalidated() = 1 then
dbms_output.put_line(Data is valid);
else
dbms_output.put_line(Data is invalid);
end if;
end;
Fully Qualied XML Schema URLs
By default, XML schema URL names are always referenced within the scope of the
current user. In other words, when database users specify XML Schema URLs, they
are rst resolved as the names of local XML schemas owned by the current user.
I If there are no such XML schemas, then they are resolved as names of global
XML schemas.
I If there are no global XML schemas, then Oracle XML DB raises an error.
XML Schema That Users Cannot Reference
These rules imply that, by default, users cannot reference the following kinds of
XML schemas:
I XML schemas owned by a different database user
I Global XML schemas that have the same name as local XML schemas
Fully Qualified XML Schema URLs Permit Explicit Reference to XML Schema
URLs
To permit explicit reference to XML schemas in these cases, Oracle XML DB
supports a notion of fully quali ed XML schema URLs. In this form, the name of the
Generating XML Schema Using DBMS_XMLSCHEMA.generateSchema()
Structured Mapping of XMLType 5-17
database user owning the XML schema is also specied as part of the XML schema
URL, except that such XML schema URLs belong to the Oracle XML DB namespace
as follows:
http://xmlns.oracle.com/xdb/schemas/<database-user-name>/<schemaURL-
minus-protocol>
Example 59 Using Fully Qualied XML Schema URL
For example, consider the global XML schema with the following URL:
http://www.example.com/po.xsd
Assume that database user SCOTT has a local XML schema with the same URL:
http://www.example.com/po.xsd
User JOE can reference the local XML schema owned by SCOTT as follows:
http://xmlns.oracle.com/xdb/schemas/SCOTT/www.example.com/po.xsd
Similarly, the fully qualied URL for the global XML schema is:
http://xmlns.oracle.com/xdb/schemas/PUBLIC/www.example.com/po.xsd
Transactional Behavior of XML Schema Registration
Registration of an XML schema is non transactional and auto committed as with
other SQL DDL operations, as follows:
I If registration succeeds, the operation is auto committed.
I If registration fails, the database is rolled back to the state before the registration
began.
Since XML schema registration potentially involves creating object types and tables,
error recovery involves dropping any such created types and tables. Thus, the entire
XML schema registration is guaranteed to be atomic. That is, either it succeeds or
the database is restored to the state before the start of registration.
Generating XML Schema Using DBMS_XMLSCHEMA.generateSchema()
An XML schema can be generated from an object-relational type automatically
using a default mapping. The generateSchema() and generateSchemas()
functions in the DBMS_XMLSCHEMA package take in a string that has the object type
name and another that has the Oracle XML DB XML schema.
Generating XML Schema Using DBMS_XMLSCHEMA.generateSchema()
5-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I generateSchema() returns an XMLType containing an XML schema. It can
optionally generate XML schema for all types referenced by the given object
type or restricted only to the top-level types.
I generateSchemas() is similar, except that it returns an XMLSequenceType
of XML schemas, each corresponding to a different namespace. It also takes an
additional optional argument, specifying the root URL of the preferred XML
schema location:
http://xmlns.oracle.com/xdb/schemas/<schema>.xsd
They can also optionally generate annotated XML schemas that can be used to
register the XML schema with Oracle XML DB.
Example 510 Generating XML Schema: Using generateSchema()
For example, given the object type:
connect t1/t1
CREATE TYPE employee_t AS OBJECT
(
empno NUMBER(10),
ename VARCHAR2(200),
salary NUMBER(10,2)
);
You can generate the schema for this type as follows:
select dbms_xmlschema.generateschema(T1, EMPLOYEE_T) from dual;
This returns a schema corresponding to the type EMPLOYEE_T. The schema declares
an element named EMPLOYEE_T and a complexType called EMPLOYEE_TType.
The schema includes other annotation fromhttp://xmlns.oracle.com/xdb.
DBMS_XMLSCHEMA.GENERATESCHEMA(T1,EMPLOYEE_T)
--------------------------------------------------------------------------------
<xsd:schema targetNamespace="http://ns.oracle.com/xdb/T1" xmlns="http://ns.oracl
e.com/xdb/T1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xml
ns.oracle.com/xdb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:sch
emaLocation="http://xmlns.oracle.com/xdb http://xmlns.oracle.com/xdb/XDBSchema.x
sd">
<xsd:element name="EMPLOYEE_T" type="EMPLOYEE_TType" xdb:SQLType="EMPLOYEE_T"
xdb:SQLSchema="T1"/>
<xsd:complexType name="EMPLOYEE_TType">
<xsd:sequence>
<xsd:element name="EMPNO" type="xsd:double" xdb:SQLName="EMPNO" xdb:SQLTyp
Managing and Storing XML Schema
Structured Mapping of XMLType 5-19
e="NUMBER"/>
<xsd:element name="ENAME" type="xsd:string" xdb:SQLName="ENAME" xdb:SQLTyp
e="VARCHAR2"/>
<xsd:element name="SALARY" type="xsd:double" xdb:SQLName="SALARY" xdb:SQLT
ype="NUMBER"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
XML Schema-Related Methods of XMLType
Table 51 lists the XMLType APIs XML schema-related methods.
Managing and Storing XML Schema
XML schema documents are themselves stored in Oracle XML DB as XMLType
instances. XML schema-related XMLType types and tables are created as part of the
Oracle XML DB installation script, catxdbs.sql.
Root XML Schema, XDBSchema.xsd
The XML schema for XML schemas is called the root XML schema,
XDBSchema.xsd. XDBSchema.xsd describes any valid XML schema document
that can be registered by Oracle XML DB. You can access XDBSchema.xsd through
Oracle XML DB Repository at:
Table 51 XMLType API XML Schema-Related Methods
XMLType API Method Description
isSchemaBased() Returns TRUE if the XMLType instance is based on an XML schema, FALSE
otherwise.
getSchemaURL()
getRootElement()
getNamespace()
Returns the XML schema URL, name of root element, and the namespace for an
XML schema-based XMLType instance.
schemaValidate()
isSchemaValid()
is SchemaValidated()
setSchemaValidated()
An XMLType instance can be validated against a registered XML schema using
the validation methods. See Chapter 6, "Transforming and Validating
XMLType Data".
Managing and Storing XML Schema
5-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
/sys/schemas/PUBLIC/xmlns.oracle.com/xdb/XDBSchema.xsd
How Are XML Schema-Based XMLType Structures Stored?
XML Schema-based XMLType structures are stored in one of the following ways:
I I n underlying object type columns. This is the default storage mechanism.
SQL object types can be created optionally during the XML schema
registration process. See "Creating XMLType Tables and Columns Based on
XML Schema" on page 5-22.
See "Specifying SQL Object Type Names with SQLName, SQLType
Attributes" on page 5-24.
I I n a single underlying LOB column. Here the storage choice is specied in the
STORE AS clause of the CREATE TABLE statement:
CREATE TABLE po_tab OF xmltype
STORE AS CLOB
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder";
Design criteria for storing XML data are discussed inChapter 2, "Getting Started
with Oracle XML DB" and Chapter 3, "Using Oracle XML DB".
Specifying the Storage Mechanism
Instead of using the STORE AS clause, you can specify that the table and column be
stored according to a mapping based on a particular XML schema. You can specify
the URL for the XML schema used for the mapping.
Non-schema-based XML data can be stored in tables using CLOBs. However you
do not gain benets such as indexing, query-rewrite, and so on.
See Also:
I Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
I Appendix A, "Installing and Conguring Oracle XML DB"
DOM Fidelity
Structured Mapping of XMLType 5-21
DOM Fidelity
Document Object Model (DOM) delity is the concept of retaining the structure of a
retrieved XML document, compared to the original XML document, for DOM
traversals. DOM delity is needed to ensure the accuracy and integrity of XML
documents stored in Oracle XML DB.
How Oracle XML DB Ensures DOM Fidelity with XML Schema
All elements and attributes declared in the XML schema are mapped to separate
attributes in the corresponding SQL object type. However, some pieces of
information in XML instance documents are not represented directly by these
element or attributes, such as:
I Comments
I Namespace declarations
I Prex information
To ensure the integrity and accuracy of this data, for example, when regenerating
XML documents stored in the database, Oracle XML DB uses a data integrity
mechanism called DOM delity.
DOM delity refers to how identical the returned XML documents are compared to
the original XML documents, particularly for purposes of DOM traversals.
DOM Fidelity and SYS_XDBPD$
To guarantee that DOMdelity is maintained and that the returned XML documents
are identical to the original XML document for DOM traversals, Oracle XML DB
adds a system binary attribute, SYS_XDBPD$, to each created object type.
This positional descriptor attribute stores all pieces of information that cannot be
stored in any of the other attributes, thereby ensuring the DOM delity of all XML
documents stored in Oracle XML DB. Examples of such pieces of information
include: ordering information, comments, processing instructions, namespace
prexes, and so on. This is mapped to a Positional Descriptor (PD) column.
See Also: "Setting the SQLInLine Attribute to FALSE for
Out-of-Line Storage" on page 5-37
Creating XMLType Tables and Columns Based on XML Schema
5-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
How to Suppress SYS_XDBPD$
If DOMdelity is not required, you can suppress SYS_XDBPD$ in the XML schema
denition by setting the attribute, maintainDOM=FALSE.
Creating XMLType Tables and Columns Based on XML Schema
Oracle XML DB creates XML schema-based XMLType tables and columns by
referencing:
I The XML schema URL of a registered XML schema
I The name of the root element
Figure 51 shows the syntax for creating an XMLType table:
CREATE TABLE [schema.] table OF XMLTYPE
[XMLTYPE XMLType_storage] [XMLSchema_spec];
Figure 51 Creating an XMLType Table
Note: The PD attribute is mainly intended for Oracle internal use
only. You should never directly access or manipulate this column.
Note: The attribute SYS_XDBPD$ is omitted in many examples
here for clarity. However, the attribute is always present as a
Positional Descriptor (PD) column in all SQL object types generated
by the XML schema registration process.
In general however, it is not a good idea to suppress the PD
attribute because the extra pieces of information, such as,
comments, processing instructions, and so on, could be lost if there
is no PD column.
CREATE TABLE
schema .
table OF XMLTYPE
XMLTYPE XMLType_storage XMLSchema_spec
Creating XMLType Tables and Columns Based on XML Schema
Structured Mapping of XMLType 5-23
A subset of the XPointer notation, shown in the following example, can also be used
to provide a single URL containing the XML schema location and element name.
Example 511 Creating XML Schema-Based XMLType Table
This example creates the XMLType table po_tab using the XML schema at the
given URL:
CREATE TABLE po_tab OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/PO.xsd" ELEMENT "PurchaseOrder";
An equivalent denition is:
CREATE TABLE po_tab OF XMLTYPE
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder";
SQL Object-Relational Types Store XML Schema-Based XMLType Tables
When an XML schema is registered, Oracle XML DB creates the appropriate SQL
object types that enable structured storage of XML documents that conform to this
XML schema. All SQL object types are created based on the current registered XML
schema, by default.
Example 512 Creating SQL Object Types to Store XMLType Tables
or example, when PO.xsd is registered with Oracle XML DB, the following SQL
types are created.
CREATE TYPE "Itemxxx_T" as object
(
part varchar2(1000),
price number
);
CREATE TYPE "Itemxxx_COLL" AS varray(1000) OF "Item_T";
CREATE TYPE "PurchaseOrderTypexxx_T" AS OBJECT
(
ponum number,
company varchar2(100),
Note: The names of the types are generated names, and will not
necessarily match Itemxxx_t, Itemxxx_COLL and
PurchaseOrderTypexxx_T, where xxx is a 3-digit integer.
Specifying SQL Object Type Names with SQLName, SQLType Attributes
5-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
item Item_varray_COLL
);
Specifying SQL Object Type Names with SQLName, SQLType Attributes
To specify specic names of SQL objects generated include the attributes SQLName
and SQLType in the XML schema denition prior to registering the XML schema.
I If you specify the SQLName and SQLType values, Oracle XML DB creates the
SQL object types using these names.
I If you do not specify these attributes, Oracle XML DB uses system-generated
names.
All annotations are in the form of attributes that can be specied within attribute
and element declarations. These attributes belong to the Oracle XML DB
namespace: http://xmlns.oracle.com/xdb
Table 52 lists Oracle XML DB attributes that you can specify in element and
attribute declarations.
Note: The names of the object types and attributes in the
preceding example can be system-generated.
I If the XML schema already contains the SQLName, SQLType,
or SQLColType attribute lled in (see "Specifying SQL Object
Type Names with SQLName, SQLType Attributes" for details),
this name is used as the object attribute's name.
I If the XML schema does not contain the SQLName attribute, the
name is derived from the XML name, unless it cannot be used
because of length or conict reasons.
If the SQLSchema attribute is used, Oracle XML DB attempts to
create the object type using the specied database schema. The
current user must have the necessary privileges to perform this.
Note: You do not have to specify values for any of these
attributes. Oracle XML DB lls in appropriate values during the
XML schema registration process. However, it is recommended
that you specify the names of at least the top-level SQL types so
that you can reference them later.
Specifying SQL Object Type Names with SQLName, SQLType Attributes
Structured Mapping of XMLType 5-25
Table 52 Attributes You Can Specify in Elements
Attribute Values Default Description
SQLName Any SQL identier Element name Species the name of the attribute within
the SQL object that maps to this XML
element.
SQLType Any SQL type name Name generated
from element name
Species the name of the SQL type
correspondingtothisXML
element declaration.
SQLCollType Any SQL collection
type name
Name generated
from element name
Species the name of the SQL collection
type corresponding to this XML element
that has maxOccurs > 1.
SQLSchema Any SQL username User registering
XML schema
Name of database user owning the type
specied by SQLType.
SQLCollSchema Any SQL username User registering
XML schema
Name of database user owning the type
specied by SQLCollType.
maintainOrder true | false true If true, the collection is mapped to a
VARRAY. If false, the collection is
mapped to a NESTED TABLE.
SQLInline true | false true If true this element is stored inline as an
embedded attribute (or a collection if
maxOccurs > 1). If false, a REF (or
collection of REFs if maxOccurs > 1) is
stored. This attribute will be forced to
false in certain situations (like cyclic
references) where SQL will not support
inlining.
maintainDOM true | false true If true, instances of this element are
stored such that they retain DOM delity
on output. This implies that all comments,
processing instructions, namespace
declarations, and so on are retained in
addition to the ordering of elements. If
false, the output need not be guaranteed
to have the same DOM behavior as the
input.
Specifying SQL Object Type Names with SQLName, SQLType Attributes
5-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
columnProps Any valid column
storage clause
NULL Species the column storage clause that is
inserted into the default CREATE TABLE
statement. It is useful mainly for elements
that get mapped to tables, namely
top-level element declarations and
out-of-line element declarations.
tableProps Any valid table
storage clause
NULL Species the TABLE storage clause that is
appended to the default CREATE TABLE
statement. This is meaningful mainly for
global and out-of-line elements.
defaultTable Any table name Based on element
name.
Species the name of the table into which
XML instances of this schema should be
stored. This is most useful in cases when
the XML is being inserted from APIs
where table name is not specied, for
example, FTP and HTTP.
beanClassname Any Java class name Generated from
element name.
Can be used within element declarations.
If the element is based on a global
complexType, this name must be
identical to the beanClassname value
within the complexType declaration. If a
name is specied by the user, the bean
generation will generate a bean class with
this name instead of generating a name
from the element name.
JavaClassname Any Java class name None Used to specify the name of a Java class
that is derived from the corresponding
bean class to ensure that an object of this
class is instantiated during bean access. If
a JavaClassname is not specied,
Oracle XML DB will instantiate an object
of the bean class directly.
Table 52 Attributes You Can Specify in Elements(Cont.)
Attribute Values Default Description
Specifying SQL Object Type Names with SQLName, SQLType Attributes
Structured Mapping of XMLType 5-27
Table 53 Attributes You Can Specify in Elements Declaring Global complexTypes
Attribute Values Default Description
SQLType Any SQL type name Name generated from
element name
Species the name of the SQL type
correspondingtothisXML
element declaration.
SQLSchema Any SQL username User registering XML
schema
Name of database user owning the type
specied by SQLType.
beanClassname Any Java class name Generated from
element name.
Can be used within element declarations.
If the element is based on a global
complexType, this name must be
identical to the beanClassname value
within the complexType declaration. If a
name is specied by the user, the bean
generation will generate a bean class with
this name, instead of generating a name
from the element name.
maintainDOM true | false true If true, instances of this element are
stored such that they retain DOM delity
on output. This implies that all comments,
processing instructions, namespace
declarations,.and so on, are retained in
addition to the ordering of elements. If
false, the output need not be guaranteed
to have the same DOM behavior as the
input.
Table 54 Attributes You Can Specify in XML Schema Declarations
Attribute Values Default Description
mapUnboundedStringToLob true | false false If true, unbounded strings are mapped to
CLOB by default. Similarly, unbounded
binary data gets mapped to BLOB, by
default. If false, unbounded strings are
mapped to VARCHAR2(4000) and
unbounded binary components are
mapped to RAW(2000).
storeVarrayAsTable true | false false If true, the VARRAY is stored as a table
(OCT). If false, the VARRAY is stored in a
LOB.
Specifying SQL Object Type Names with SQLName, SQLType Attributes
5-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
SQL Mapping Is Specied in the XML Schema During Registration
Information regarding the SQL mapping is stored in the XML schema document.
The registration process generates the SQL types, as described in "Mapping of
Types Using DBMS_XMLSCHEMA" on page 5-31 and adds annotations to the XML
schema document to store the mapping information. Annotations are in the form of
new attributes.
Example 513 Capturing SQL Mapping Using SQLType and SQLName Attributes
The following XML schema denition shows how SQL mapping information is
captured using SQLType and SQLName attributes:
declare
doc varchar2(3000) := <schema
targetNamespace="http://www.oracle.com/PO.xsd"
xmlns:po="http://www.oracle.com/PO.xsd" xmlns:xdb="http://xmlns.oracle.com/xdb"
xmlns="http://www.w3.org/2001/XMLSchema">
<complexType name="PurchaseOrderType">
<sequence>
<element name="PONum" type="decimal" xdb:SQLName="PONUM"
xdb:SQLType="NUMBER"/>
<element name="Company" xdb:SQLName="COMPANY" xdb:SQLType="VARCHAR2">
<simpleType>
<restriction base="string">
<maxLength value="100"/>
</restriction>
</simpleType>
</element>
<element name="Item" xdb:SQLName="ITEM" xdb:SQLType="ITEM_T"
maxOccurs="1000">
<complexType>
<sequence>
<element name="Part" xdb:SQLName="PART" xdb:SQLType="VARCHAR2">
<simpleType>
<restriction base="string">
<maxLength value="1000"/>
</restriction>
</simpleType>
</element>
<element name="Price" type="float" xdb:SQLName="PRICE"
xdb:SQLType="NUMBER"/>
</sequence>
</complexType>
</element>
Specifying SQL Object Type Names with SQLName, SQLType Attributes
Structured Mapping of XMLType 5-29
</sequence>
</complexType>
<element name="PurchaseOrder" type="po:PurchaseOrderType"/>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
Figure 52 shows how Oracle XML DB creates XML schema-based XMLType tables
using an XML document and mapping specied in an XML schema. An XMLType
table is rst created and depending on how the storage is specied in the XML
schema, the XML document is mapped and stored either as a CLOB in one
XMLType column, or stored object-relationally and spread out across several
columns in the table.
Specifying SQL Object Type Names with SQLName, SQLType Attributes
5-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 52 How Oracle XML DB Maps XML Schema-Based XMLType Tables
An XMLType table is rst created and depending on how the storage is specied in
the XML schema, the XML document is mapped and stored either as a CLOB in one
XMLType column, or stored object-relationally and spread out across several
columns in the table.
XML data: employee_2002.xml
...
<employee>
<first_name>Scott</first_name>
<last_name>Tiger</last_name>
<email>[email protected]</email>
...
<hire_date>040402</hire_date>
...
<department_id>1234</department_id>
</employee>
...
XML schema definition: employee.xsd
...
<sequence>
<element name="first name" type="string"/>
<element name="last name" type="string"/>
<element name="email" type="string"/>
...
<element name="hire_date" type="date"/>
...
<element name="department_id" type="integer"/>
</sequence>
...
Create
XMLType
Table
employee_2002 tables
. . . XMLType Column . . . . . .
scott tiger CLOB
CLOB
CLOB
CLOB
CLOB
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
employee_2002 tables
first_name last_name email dept_id
...1234 tiger
scott
Store as CLOB
Structured
Storage
Here the XML elements are mapped
to columns in tables.
Here the whole XML document or parts
of it are stored in CLOBs in tables.
Mapping of Types Using DBMS_XMLSCHEMA
Structured Mapping of XMLType 5-31
Mapping of Types Using DBMS_XMLSCHEMA
Use DBMS_XMLSCHEMA to set the mapping of type information for attributes and
elements.
Setting Attribute Mapping Type Information
An attribute declaration can have its type specied in terms of one of the following:
I Primitive type
I Global simpleType, declared within this XML schema or in an external XML
schema
I Reference to global attribute (ref=".."), declared within this XML schema or
in an external XML schema
I Local simpleType
In all cases, the SQL type and associated information (length and precision) as well
as the memory mapping information, are derived from the simpleType on which
the attribute is based.
Overriding SQL Types
You can explicitly specify an SQLType value in the input XML schema document.
In this case, your specied type is validated. This allows for the following specic
forms of overrides:
I If the default type is a STRING, you can override it with any of the following:
CHAR, VARCHAR, or CLOB.
I If the default type is RAW, you can override it with RAW or BLOB.
Setting Element Mapping Type Information
An element declaration can specify its type in terms of one of the following:
I Any of the ways for specifying type for an attribute declaration. See "Setting
Attribute Mapping Type Information" on page 5-31.
I Global complexType, specied within this XML schema document or in an
external XML schema.
I Reference to a global element (ref="..."), which could itself be within this
XML schema document or in an external XML schema.
Mapping of Types Using DBMS_XMLSCHEMA
5-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Local complexType.
Overriding SQL Type
An element based on a complexType is, by default, mapped to an object type
containing attributes corresponding to each of the sub-elements and attributes.
However, you can override this mapping by explicitly specifying a value for
SQLType attribute in the input XML schema. The following values for SQLType are
permitted in this case:
I VARCHAR2
I RAW
I CLOB
I BLOB
These represent storage of the XML in a text or unexploded form in the database.
The following special cases are handled:
I If a cycle is detected, as part of processing the complexTypes used to declare
elements and elements declared within the complexType), the SQLInline
attribute is forced to be false and the correct SQL mapping is set to REF
XMLTYPE.
I If maxOccurs > 1, a VARRAY type may need to be created.
If SQLInline ="true", a varray type is created whose element type is the
SQL type previously determined.
* Cardinality of the VARRAY is determined based on the value of
maxOccurs attribute.
* The name of the VARRAY type is either explicitly specied by the user
using SQLCollType attribute or obtained by mangling the element
name.
If SQLInline="false", the SQL type is set to XDB.XDB$XMLTYPE_REF_
LIST_T, a predened type representing an array of REFs to XMLType.
I If the element is a global element, or if SQLInline="false, a default table
needs to be created. It is added to the table creation context. The name of the
default table has either been specied by the user, or derived by mangling the
element name.
XML Schema: Mapping SimpleTypes to SQL
Structured Mapping of XMLType 5-33
XML Schema: Mapping SimpleTypes to SQL
This section describes how XML schema denitions map XML schema
simpleType to SQL object types. Figure 53 shows an example of this.
Table 55 through Table 58 list the default mapping of XML schema simpleType
to SQL, as specied in the XML schema denition. For example:
I An XML primitive type is mapped to the closest SQL datatype. For example,
DECIMAL, POSITIVEINTEGER, and FLOAT are all mapped to SQL NUMBER.
I An XML enumeration type is mapped to an object type with a single RAW(n)
attribute. The value of n is determined by the number of possible values in the
enumeration declaration.
I An XML list or a union datatype is mapped to a string (VARCHAR2/CLOB)
datatype in SQL.
Figure 53 Mapping simpleType: XML Strings to SQL VARCHAR2 or CLOBs
. . .
Employee_tab of type OBJ_T
. . . Resume
CLOB
. . .
. . . . . . . . .
Entire resume
value is stored
in the CLOB
<element name = "Resume" type = "string">
.
.
.
.
.
.
XML Schema: Mapping SimpleTypes to SQL
5-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Table 55 Mapping XML String Datatypes to SQL
XMLPrimitive
Type
Length or
MaxLength
Facet
Default Mapping Compatible Datatype
string n VARCHAR2(n) if n < 4000, else
VARCHAR2(4000)
CHAR, VARCHAR2,
CLOB
string -- VARCHAR2(4000) if
mapUnboundedStringToLob="false,
CLOB
CHAR, VARCHAR2, CLOB
Table 56 Mapping XML Binary Datatypes (hexBinary/base64Binary) to SQL
XMLPrimitive
Type
Length or
MaxLength
Facet
Default Mapping Compatible Datatype
hexBinary,
base64Binary
n RAW(n) if n < 2000, else RAW(2000) RAW, BLOB
hexBinary,
base64Binary
- RAW(2000) if
mapUnboundedStringToLob=false,
BLOB
RAW, BLOB
Table 57 Default Mapping of Numeric XML Primitive Types to SQL
XML Simple Type
Default
Oracle
DataType
totalDigits (m), fractionDigits(n)
Specied
Compatible Datatypes
oat NUMBER NUMBER(m,n) NUMBER, FLOAT, DOUBLE
double NUMBER NUMBER(m,n) NUMBER, FLOAT, DOUBLE
decimal NUMBER NUMBER(m,n) NUMBER, FLOAT, DOUBLE
integer NUMBER NUMBER(m,n) NUMBER, FLOAT, DOUBLE
nonNegativeInteger NUMBER NUMBER(m,n) NUMBER, FLOAT, DOUBLE
positiveInteger NUMBER NUMBER(m,n) NUMBER, FLOAT, DOUBLE
nonPositiveInteger NUMBER NUMBER(m,n) NUMBER, FLOAT, DOUBLE
XML Schema: Mapping SimpleTypes to SQL
Structured Mapping of XMLType 5-35
negativeInteger NUMBER NUMBER(m,n) NUMBER, FLOAT, DOUBLE
long NUMBER(20) NUMBER(m,n) NUMBER, FLOAT, DOUBLE
unsignedLong NUMBER(20) NUMBER(m,n) NUMBER, FLOAT, DOUBLE
int NUMBER(10) NUMBER(m,n) NUMBER, FLOAT, DOUBLE
unsignedInt NUMBER(10) NUMBER(m,n) NUMBER, FLOAT, DOUBLE
short NUMBER(5) NUMBER(m,n) NUMBER, FLOAT, DOUBLE
unsignedShort NUMBER(5) NUMBER(m,n) NUMBER, FLOAT, DOUBLE
byte NUMBER(3) NUMBER(m,n) NUMBER, FLOAT, DOUBLE
unsignedByte NUMBER(3) NUMBER(m,n) NUMBER, FLOAT, DOUBLE
Table 58 Mapping XML Date Datatypes to SQL
XML Primitive Type Default Mapping Compatible Datatypes
datetime TIMESTAMP DATE
time TIMESTAMP DATE
date DATE DATE
gDay DATE DATE
gMonth DATE DATE
gYear DATE DATE
gYearMonth DATE DATE
gMonthDay DATE DATE
duration VARCHAR2(4000) none
Table 57 Default Mapping of Numeric XML Primitive Types to SQL(Cont.)
XML Simple Type
Default
Oracle
DataType
totalDigits (m), fractionDigits(n)
Specied
Compatible Datatypes
XML Schema: Mapping SimpleTypes to SQL
5-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
simpleType: Mapping XML Strings to SQL VARCHAR2 Versus CLOBs
If the XML schema species the datatype to be string with a maxLength value of
less than 4000, it is mapped to a VARCHAR2 attribute of the specied length.
However, if maxLength is not specied in the XML schema, it can only be mapped
to a LOB. This is sub-optimal when most of the string values are small and only a
small fraction of them are large enough to need a LOB.
Table 59 Default Mapping of Other XML Primitive Datatypes to SQL
XML Simple Type Default Oracle DataType Compatible Datatypes
boolean RAW(1) VARCHAR2
Language(string) VARCHAR2(4000) CLOB, CHAR
NMTOKEN(string) VARCHAR2(4000) CLOB, CHAR
NMTOKENS(string) VARCHAR2(4000) CLOB, CHAR
Name(string) VARCHAR2(4000) CLOB, CHAR
NCName(string) VARCHAR2(4000) CLOB, CHAR
ID VARCHAR2(4000) CLOB, CHAR
IDREF VARCHAR2(4000) CLOB, CHAR
IDREFS VARCHAR2(4000) CLOB, CHAR
ENTITY VARCHAR2(4000) CLOB, CHAR
ENTITIES VARCHAR2(4000) CLOB, CHAR
NOTATION VARCHAR2(4000) CLOB, CHAR
anyURI VARCHAR2(4000) CLOB, CHAR
anyType VARCHAR2(4000) CLOB, CHAR
anySimpleType VARCHAR2(4000) CLOB, CHAR
QName XDB.XDB$QNAME --
See Also: Table 55, "Mapping XML String Datatypes to SQL"
XML Schema: Mapping complexTypes to SQL
Structured Mapping of XMLType 5-37
XML Schema: Mapping complexTypes to SQL
Using XML schema, a complexType is mapped to an SQL object type as follows:
I XML attributes declared within the complexType are mapped to object
attributes. The simpleType dening the XML attribute determines the SQL
datatype of the corresponding attribute.
I XML elements declared within the complexType are also mapped to object
attributes. The datatype of the object attribute is determined by the
simpleType or complexType dening the XML element.
If the XML element is declared with attribute maxOccurs > 1, it is mapped to a
collection attribute in SQL. The collection could be a VARRAY (default) or
nested table if the maintainOrder attribute is set to false. Further, the default
storage of the VARRAY is in Ordered Collections in Tables (OCTs) instead of LOBs.
You can choose LOB storage by setting the storeAsLob attribute to true.
Setting the SQLInLine Attribute to FALSE for Out-of-Line Storage
By default, a sub-element is mapped to an embedded object attribute. However,
there may be scenarios where out-of-line storage offers better performance. In such
cases the SQLInline attribute can be set to false, and Oracle XML DB generates an
object type with an embedded REF attribute. REF points to another instance of
XMLType that corresponds to the XML fragment that gets stored out-of-line. Default
XMLType tables are also created to store the out-of-line fragments.
Figure 54 illustrates the mapping of a complexType to SQL for out-of-line
storage.
See Also: "Ordered Collections in Tables (OCTs)" on page 5-71
XML Schema: Mapping complexTypes to SQL
5-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 54 Mapping complexType to SQL for Out-of-Line Storage
Example 514 Oracle XML DB XML Schema: complexType Mapping - Setting
SQLInLine Attribute to False for Out-of-Line Storage
In this example element Addrs attribute, xdb:SQLInLine, is set to false.The
resulting object type OBJ_T2 has a column of type XMLType with an embedded
REF attribute. The REF attribute points to another XMLType instance created of
object type OBJ_T1 in table Addr_tab. Addr_tab has columns Street and City.
The latter XMLType instance is stored out-of-line.
declare
doc varchar2(3000) := <schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/emp.xsd"
xmlns:emp="http://www.oracle.com/emp.xsd"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<complexType name = "Employee" xdb:SQLType="OBJ_T2">
<sequence>
<element name = "Name" type = "string"/>
<element name = "Age" type = "decimal"/>
<element name = "Addr" xdb:SQLInline = "false">
<complexType xdb:SQLType="OBJ_T1">
<sequence>
<element name = "Street" type = "string"/>
<element name = "City" type = "string"/>
</sequence>
</complexType>
This XML fragment is
stored out-of-line Name
Employee_tab of type OBJ_T2
Age Addr REF XMLType
Addr_tab of type OBJ_T1
Street City
XMLType table
REF points
to another
XMLType
instance
<element name = "Addr" xdb : SQLInLine = "false">
.
.
.
.
.
.
XML Schema: Mapping complexTypes to SQL
Structured Mapping of XMLType 5-39
</element>
</sequence>
</complexType>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
On registering this XML schema, Oracle XML DB generates the following types and
XMLType tables:
CREATE TYPE OBJ_T1 AS OBJECT
(
SYS_XDBPD$ XDB.XDB$RAW_LIST_T,
Street VARCHAR2(4000),
City VARCHAR2(4000)
);
CREATE TYPE OBJ_T2 AS OBJECT
(
SYS_XDBPD$ XDB.XDB$RAW_LIST_T,
Name VARCHAR2(4000),
Age NUMBER,
Addr REF XMLType
);
Mapping XML Fragments to Large Objects (LOBs)
You can specify the SQLType for a complex element as a Character Large Object
(CLOB) or Binary Large Object (BLOB) as shown in Figure 55. Here the entire XML
fragment is stored in a LOB attribute. This is useful when parts of the XML
document are seldom queried but are mostly retrieved and stored as single pieces.
By storing XML fragments as LOBs, you can save on
parsing/decomposition/recomposition overheads.
Example 515 Oracle XML DB XML Schema: complexType Mapping XML Fragments
to LOBs
In the following example, the XML schema species that the XML fragments
element Addr is using the attribute SQLType="CLOB":
declare
doc varchar2(3000) := <schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/emp.xsd"
xmlns:emp="http://www.oracle.com/emp.xsd"
XML Schema: Mapping complexTypes to SQL
5-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
xmlns:xdb="http://xmlns.oracle.com/xdb">
<complexType name = "Employee" xdb:SQLType="OBJ_T2">
<sequence>
<element name = "Name" type = "string"/>
<element name = "Age" type = "decimal"/>
<element name = "Addr" xdb:SQLType = "CLOB">
<complexType >
<sequence>
<element name = "Street" type = "string"/>
<element name = "City" type = "string"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
On registering this XML schema, Oracle XML DB generates the following types and
XMLType tables:
CREATE TYPE OBJ_T AS OBJECT
(
SYS_XDBPD$ XDB.XDB$RAW_LIST_T,
Name VARCHAR2(4000),
Age NUMBER,
Addr CLOB
);
Oracle XML DB complexType Extensions and Restrictions
Structured Mapping of XMLType 5-41
Figure 55 Mapping complexType XML Fragments to Character Large Objects
(CLOBs)
Oracle XML DB complexType Extensions and Restrictions
In XML schema, complexTypes are declared based on complexContent and
simpleContent.
I simpleContent is declared as an extension of simpleType.
I complexContent is declared as one of the following:
I Base type
I complexType extension
I complexType restriction.
complexType Declarations in XML Schema: Handling Inheritance
For complexType, Oracle XML DB handles inheritance in the XML schema as
follows:
I For complexTypes declared to extend other complexTypes, the SQL type
corresponding to the base type is specied as the supertype for the current SQL
type. Only the additional attributes and elements declared in the
sub-complextype are added as attributes to the sub-object-type.
Name
Employee_tab of type OBJ_T
Age Addr
CLOB
Street and
city are stored
in the CLOB
<element name = "Addr" xdb : SQLType = "CLOB">
.
.
.
.
.
.
Oracle XML DB complexType Extensions and Restrictions
5-42 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I For complexTypes declared to restrict other complexTypes, the SQL type for the
sub-complex type is set to be the same as the SQL type for its base type. This is
because SQL does not support restriction of object types through the
inheritance mechanism. Any constraints are imposed by the restriction in XML
schema.
Example 516 Inheritance in XML Schema: complexContent as an Extension of
complexTypes
Consider an XML schema that denes a base complexType Address and two
extensions USAddress and IntlAddress.
declare
doc varchar2(3000) := <xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<xs:complexType name="Address" xdb:SQLType="ADDR_T">
<xs:sequence>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="USAddress" xdb:SQLType="USADDR_T">
<xs:complexContent>
<xs:extension base="Address">
<xs:sequence>
<xs:element name="zip" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="IntlAddress" final="#all" xdb:SQLType="INTLADDR_T">
<xs:complexContent>
<xs:extension base="Address">
<xs:sequence>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
Oracle XML DB complexType Extensions and Restrictions
Structured Mapping of XMLType 5-43
end;
create type ADDR_T as object (
SYS_XDBPD$ XDB.XDB$RAW_LIST_T,
"street" varchar2(4000),
"city" varchar2(4000)
) not final;
create type USADDR_T under ADDR_T (
"zip" varchar2(4000)
) not final;
create type INTLADDR_T under ADDR_T (
"country" varchar2(4000)
) final;
Example 517 Inheritance in XML Schema: Restrictions in complexTypes
Consider an XML schema that denes a base complexType Address and a
restricted type LocalAddress that prohibits the specication of country
attribute.
declare
doc varchar2(3000) := <xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<xs:complexType name="Address" xdb:SQLType="ADDR_T">
<xs:sequence>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="zip" type="xs:string"/>
<xs:element name="country" type="xs:string" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="LocalAddress" xdb:SQLType="USADDR_T">
<xs:complexContent>
<xs:restriction base="Address">
Note: Type INTLADDR_T is created as a nal type because the
corresponding complexType species the final attribute. By
default, all complexTypes can be extended and restricted by other
types, and hence, all SQL object types are created as not nal types.
Oracle XML DB complexType Extensions and Restrictions
5-44 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<xs:sequence>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="zip" type="xs:string"/>
<xs:element name="country" type="xs:string"
minOccurs="0" maxOccurs="0"/>
</xs:sequence>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
Since inheritance support in SQL does not support a notion of restriction, the SQL
type corresponding to the restricted complexType is a empty subtype of the parent
object type.For the preceding XML schema, the following SQL types are generated:
create type ADDR_T as object (
SYS_XDBPD$ XDB.XDB$RAW_LIST_T,
"street" varchar2(4000),
"city" varchar2(4000),
"zip" varchar2(4000),
"country" varchar2(4000)
) not final;
create type USADDR_T under ADDR_T;
Mapping complexType: simpleContent to Object Types
A complexType based on a simpleContent declaration is mapped to an object
type with attributes corresponding to the XML attributes and an extra SYS_
XDBBODY attribute corresponding to the body value. The datatype of the body
attribute is based on simpleType which denes the body's type.
Example 518 XML Schema complexType: Mapping complexType to simpleContent
declare
doc varchar2(3000) := <schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/emp.xsd"
xmlns:emp="http://www.oracle.com/emp.xsd"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<complexType name="name" xdb:SQLType="OBJ_T">
<simpleContent>
Oracle XML DB complexType Extensions and Restrictions
Structured Mapping of XMLType 5-45
<restriction base = "string">
</restriction>
</simpleContent>
</complexType>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/emp.xsd, doc);
end;
On registering this XML schema, Oracle XML DB generates the following types and
XMLType tables:
create type OBJ_T as object
(
SYS_XDBPD$ xdb.xdb$raw_list_t,
SYS_XDBBODY$ VARCHAR2(4000)
);
Mapping complexType: Any and AnyAttributes
Oracle XML DB maps the element declaration, any, and the attribute declaration,
anyAttribute, to VARCHAR2 attributes (or optionally to Large Objects (LOBs))
in the created object type. The object attribute stores the text of the XML fragment
that matches the any declaration.
I The namespace attribute can be used to restrict the contents so that they
belong to a specied namespace.
I The processContents attribute within the any element declaration, indicates
the level of validation required for the contents matching the any declaration.
Example 519 Oracle XML DB XML Schema: Mapping complexType to
Any/AnyAttributes
This XML schema example declares an any element and maps it to the column
SYS_XDBANY$, in object type OBJ_T. This element also declares that the attribute,
processContents, skips validating contents that match the any declaration.
declare
doc varchar2(3000) := <schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/any.xsd"
xmlns:emp="http://www.oracle.com/any.xsd"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<complexType name = "Employee" xdb:SQLType="OBJ_T">
<sequence>
Oracle XML DB complexType Extensions and Restrictions
5-46 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<element name = "Name" type = "string" />
<element name = "Age" type = "decimal"/>
<any namespace = "http://www/w3.org/2001/xhtml" processContents = "skip"/>
</sequence>
</complexType>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/emp.xsd, doc);
end;
It results in the following statement:
CREATE TYPE OBJ_T AS OBJECT
(
SYS_XDBPD$ xdb.xdb$raw_list_t,
Name VARCHAR2(4000),
Age NUMBER,
SYS_XDBANY$ VARCHAR2(4000)
);
Handling Cycling Between complexTypes in XML Schema
Cycles in the XML schema are broken while generating the object types, because
object types do not allow cycles, by introducing a REF attribute at the point at
which the cycle gets completed. Thus part of the data is stored out-of-line yet still
belongs to the parent XML document when it is retrieved.
Example 520 XML Schema: Cycling Between complexTypes
XML schemas permit cycling between denitions of complexTypes. Figure 56
shows this example, where the denition of complexType CT1 can reference
another complexType CT2, whereas the denition of CT2 references the rst type
CT1.
XML schemas permit cycling between denitions of complexTypes. This is an
example of cycle of length 2:
declare
doc varchar2(3000) := <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<xs:complexType name="CT1" xdb:SQLType="CT1">
<xs:sequence>
<xs:element name="e1" type="xs:string"/>
<xs:element name="e2" type="CT2"/>
</xs:sequence>
Oracle XML DB complexType Extensions and Restrictions
Structured Mapping of XMLType 5-47
</xs:complexType>
<xs:complexType name="CT2" xdb:SQLType="CT2">
<xs:sequence>
<xs:element name="e1" type="xs:string"/>
<xs:element name="e2" type="CT1"/>
</xs:sequence>
</xs:complexType>
</xs:schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/emp.xsd, doc);
end;
SQL types do not allow cycles in type denitions. However, they support weak
cycles, that is, cycles involving REF (references) attributes. Therefore, cyclic XML
schema denitions are mapped to SQL object types such that any cycles are avoided
by forcing SQLInline=false at the appropriate point. This creates a weak
cycle.
For the preceding XML schema, the following SQL types are generated:
create type CT1 as object
(
SYS_XDBPD$ xdb.xdb$raw_list_t,
"e1" varchar2(4000),
"e2" ref xmltype;
) not final;
create type CT2 as object
(
SYS_XDBPD$ xdb.xdb$raw_list_t,
"e1" varchar2(4000),
"e2" CT1
) not final;
Oracle XML DB complexType Extensions and Restrictions
5-48 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 56 Cross Referencing Between Different complexTypes in the Same XML
Schema
Example 521 XML Schema: Cycling Between complexTypes, Self-Referencing
Another example of a cyclic complexType involves the declaration of the
complexType having a reference to itself. The following is an example of type
<SectionT> that references itself:
declare
doc varchar2(3000) := <xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<xs:complexType name="SectionT" xdb:SQLType="SECTION_T">
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:choice maxOccurs="unbounded">
<xs:element name="body" type="xs:string" xdb:SQLCollType="BODY_COLL"/>
<xs:element name="section" type="SectionT"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/section.xsd, doc);
end;
The following SQL types are generated.
<xs:element name=
"e2" type = "CT2"/>
<xs:complexType name=
"CT1"...>
.
.
.
.
.
.
<xs:element name=
"e2" type="CT1"/>
<xs:complexType name=
"CT2"...>
.
.
.
.
.
.
XML schema, emp. xsd
Further Guidelines for Creating XML Schema-Based XML Tables
Structured Mapping of XMLType 5-49
create type BODY_COLL as varray(32767) of VARCHAR2(4000);
create type SECTION_T as object
(
SYS_XDBPD$ xdb.xdb$raw_list_t,
"title" varchar2(4000),
"body" BODY_COLL,
"section" XDB.XDB$REF_LIST_T
) not final;
Further Guidelines for Creating XML Schema-Based XML Tables
Assume that your XML schema, identied by
http://www.oracle.com/PO.xsd, has been registered. An XMLType table,
myPOs, can then be created to store instances conforming to element,
PurchaseOrder, of this XML schema, in an object-relational format as follows:
CREATE TABLE MyPOs OF XMLTYPE
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder";
Figure 57 illustrates schematically how a complexTypes can reference or cycle
itself.
Note: The section attribute is declared as a varray of REFs to
XMLType instances. Since there can be more than one occurrence of
embedded sections, the attribute is a VARRAY. And its a VARRAY
of REFs to XMLTypes in order to avoid forming a cycle of SQL
objects.
See Also: "Cyclical References Between XML Schemas" on
page 5-71
Further Guidelines for Creating XML Schema-Based XML Tables
5-50 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 57 complexType Self Referencing Within an XML Schema
Hidden columns are created. These correspond to the object type to which the
PurchaseOrder element has been mapped. In addition, an XMLExtra object
column is created to store the top-level instance data such as namespace
declarations.
Specifying Storage Clauses in XMLType CREATE TABLE Statements
To specify storage, the underlying columns can be referenced in the XMLType
storage clauses using either Object or XML notation:
I Object notation: XMLDATA.<attr1>.<attr2>....
For example:
CREATE TABLE MyPOs OF XMLTYPE
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder"
lob (xmldata.lobattr) STORE AS (tablespace ...);
I XML notation: extractValue(xmltypecol, '/attr1/attr2')
For example:
CREATE TABLE MyPOs OF XMLTYPE
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder"
lob (ExtractValue(MyPOs, '/lobattr')) STORE AS (tablespace ...);
Note: XMLDATA is a pseudo-attribute of XMLType that enables
direct access to the underlying object column. See Chapter 4, "Using
XMLType", under Changing the Storage Options on an XMLType
Column Using XMLData.
<xs:element name="section" type =
"SectionT"/>
<xs:complexType name=
"SectionT"...>
.
.
.
.
.
.
XML schema, emp. xsd
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-51
Referencing XMLType Columns Using CREATE INDEX
As shown in the preceding examples, columns underlying an XMLType column can
be referenced using either an object or XML notation in the CREATE TABLE
statements. The same is true in CREATE INDEX statements:
CREATE INDEX ponum_idx ON MyPOs (xmldata.ponum);
CREATE INDEX ponum_idx ON MyPOs p (ExtractValue(p, '/ponum');
Specifying Constraints on XMLType Columns
Constraints can also be specied for underlying XMLType columns, using either the
object or XML notation:
I Object notation
CREATE TABLE MyPOs OF XMLTYPE
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder"
(unique(xmldata.ponum));
I XML notation
CREATE TABLE MyPOs P OF XMLTYPE
ELEMENT
"http://www.oracle.com/PO.xsd#PurchaseOrder"(unique(ExtractValue(p,'/ponum')
);
Inserting New Instances into XMLType Columns
New instances can be inserted into an XMLType columns as follows:
INSERT INTO MyPOs VALUES
(xmltype.createxml('<PurchaseOrder>.....</PurchaseOrder>'));
Query Rewrite with XML Schema-Based Structured Storage
What Is Query Rewrite?
When the XMLType is stored in structured storage (object-relationally) using an
XML schema and queries using XPath are used, they are rewritten to go directly to
the underlying object-relational columns. This enables the use of B*Tree or other
indexes, if present on the column, to be used in query evaluation by the Optimizer.
This query rewrite mechanism is used for XPaths in SQL functions such as
existsNode(), extract(), extractValue(), and updateXML(). This enables
Query Rewrite with XML Schema-Based Structured Storage
5-52 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
the XPath to be evaluated against the XML document without having to ever
construct the XML document in memory.
Example 522 Query Rewrite
For example a query such as:
SELECT VALUE(p) FROM MyPOs p
WHERE extractValue(value(p),'/PurchaseOrder/Company) = 'Oracle';
is trying to get the value of the Company element and compare it with the literal
Oracle. Since the MyPOs table has been created with XML schema-based
structured storage, the extractValue operator gets rewritten to the underlying
relational column that stores the company information for the purchaseorder.
Thus the preceding query is rewritten to the following:
SELECT VALUE(p) FROM MyPOs p
WHERE p.xmldata.company = 'Oracle';
If there was a regular index created on the Company column, such as:
CREATE INDEX company_index ON MyPos e
(extractvalue(value(e),/PurchaseOrder/Company));
then the preceding query would use the index for its evaluation.
When Does Query Rewrite Occur?
Query rewrite happens for the following SQL functions:
I extract()
I existsNode()
I extractValue
I updateXML
The rewrite happens when these SQL functions are present in any expression in a
query, DML, or DDL statement. For example, you can use extractValue() to
create indexes on the underlying relational columns.
See Also: Chapter 4, "Using XMLType"
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-53
Example 523 SELECT Statement and Query Rewrites
This example gets the existing purchase orders:
SELECT EXTRACTVALUE(value(x),/PurchaseOrder/Company)
FROM MYPOs x
WHERE EXISTSNODE(value(x),/PurchaseOrder/Item[1]/Part) = 1;
Here are some examples of statements that get rewritten to use underlying columns:
Example 524 DML Statement and Query Rewrites
This example deletes all purchaseorders where the Company is not Oracle:
DELETE FROM MYPOs x
WHERE EXTRACTVALUE(value(x),/PurchaseOrder/Company) = Oracle Corp;
Example 525 CREATE INDEX Statement and Query Rewrites
This example creates an index on the Company column, since this is stored object
relationally and the query rewrite happens, a regular index on the underlying
relational column will be created:
CREATE INDEX company_index ON MyPos e
(extractvalue(value(e),/PurchaseOrder/Company));
In this case, if the rewrite of the SQL functions results in a simple relational column,
then the index is turned into a B*Tree or a domain index on the column, rather than
a function-based index.
What XPath Expressions Are Rewritten?
XPath involving simple expressions with no wild cards or descendant axes get
rewritten. The XPath may select an element or an attribute node. Predicates are
supported and get rewritten into SQL predicates.
Table 510 lists the kinds of XPath expressions that can be translated into
underlying SQL queries in this release.
Query Rewrite with XML Schema-Based Structured Storage
5-54 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Unsupported XPath Constructs The following XPath constructs do not get rewritten:
I XPath Functions
I XPath Variable references
I All axis other than child and attribute axis
I Wild card and descendant expressions
I UNION operations
Unsupported XML Schema Constructs The following XML schema constructs are not
supported. This means that if the XPath expression includes nodes with the
following XML schema construct then the entire expression will not get rewritten:
I XPath expressions accessing children of elements containing open content,
namely any content. When nodes contain any content, then the expression
cannot be rewritten, except when the any targets a namespace other than the
namespace specied in the XPath. any attributes are handled in a similar way.
I CLOB storage. If the XML schema maps part of the element denitions to an
SQL CLOB, then XPath expressions traversing such elements are not supported.
I Enumeration types.
I Substitutable elements.
Table 510 Supported XPath Expressions for Translation to Underlying SQL Queries
XPath Expression for Translation Description
Simple XPath expressions:
/PurchaseOrder/@PurchaseDate
/PurchaseOrder/Company
Involves traversals over object type attributes only, where the attributes
are simple scalar or object types themselves. The only axes supported
are the child and the attribute axes.
Collection traversal expressions:
/PurchaseOrder/Item/Part
Involves traversal of collection expressions. The only axes supported are
child and attribute axes. Collection traversal is not supported if the SQL
operator is used during CREATE INDEX or updateXML().
Predicates:
[Company="Oracle"]
Predicates in the XPath are rewritten into SQL predicates. Predicates are
not rewritten for updateXML()
List indexe:
lineitem[1]
Indexes are rewritten to access the nth item in a collection. These are
not rewritten for updateXML().
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-55
I Non-default mapping of scalar types. For example, number types mapped to
native storage, such as native integers, and so on.
I Child access for inherited complexTypes where the child is not a member of
the declared complexType.
For example, consider the case where we have a address complexType
which has a street element. We can have a derived type called shipAddr
which contains shipmentNumber element. If the PurchaseOrder had an
address element of type address, then an XPath like
"/PurchaseOrder/address/street" would get rewritten whereas
"/PurchaseOrder/address/shipmentNumber" would not.
I Non-coercible datatype operations, such as a boolean added with a number.
How are the XPaths Rewritten?
The following sections use the same purchaseorder XML schema explained
earlier in the chapter to explain how the functions get rewritten.
Example 526 Rewriting XPaths During Object Type Generation
Consider the following purchaseorder XML schema:
declare
doc varchar2(1000) := <schema
targetNamespace="http://www.oracle.com/PO.xsd"
xmlns:po="http://www.oracle.com/PO.xsd"xmlns="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<complexType name="PurchaseOrderType">
<sequence>
<element name="PONum" type="decimal"/>
<element name="Company">
<simpleType>
<restriction base="string">
<maxLength value="100"/>
</restriction>
</simpleType>
</element>
<element name="Item" maxOccurs="1000">
<complexType>
<sequence>
<element name="Part">
<simpleType>
<restriction base="string">
Query Rewrite with XML Schema-Based Structured Storage
5-56 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<maxLength value="1000"/>
</restriction>
</simpleType>
</element>
<element name="Price" type="float"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<element name="PurchaseOrder" type="po:PurchaseOrderType"/>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
-- A table is created conforming to this schema
CREATE TABLE MyPOs OF XMLTYPE
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder";
-- The inserted XML document is partially validated against the schema before
-- it is inserted.
insert into MyPos values (xmltype(<PurchaseOrder
xmlns="http://www.oracle.com/PO.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/PO.xsd
http://www.oracle.com/PO.xsd">
<PONum>1001</PONum>
<Company>Oracle Corp</Company>
<Item>
<Part>9i Doc Set</Part>
<Price>2550</Price>
</Item>
<Item>
<Part>8i Doc Set</Part>
<Price>350</Price>
</Item>
</PurchaseOrder>));
Since the XML schema did not specify anything about maintaining the ordering, the
default is to maintain the ordering and DOM delity. Hence the types have SYS_
XDBPD$ attribute to store the extra information needed to maintain the ordering of
nodes and to capture extra items such as comments, processing instructions and so
on.
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-57
The SYS_XDBPD$ attribute also maintains the existential information for the
elements (that is, whether the element was present or not in the input document).
This is needed for elements with scalar content, since they map to simple relational
columns. In this case, both empty and missing scalar elements map to NULL values
in the column and only the SYS_XDBPD$ attribute can help distinguish the two
cases. The query rewrite mechanism takes into account the presence or absence of
the SYS_XDBPD$ attribute and rewrites queries appropriately.
Assuming that this XML schema is registered with the schema URL:
http://www.oracle.com/PO.xsd
you can create the po_tab table with this schema as follows:
CREATE TABLE po_tab OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/PO.xsd" ELEMENT "PurchaseOrder";
Now this table has a hidden XMLData column of type "PurchaseOrder_T" that
stores the actual data.
Rewriting XPath Expressions: Mapping Types and Issues
XPath expression mapping of types and topics are described in the following
sections:
I "Mapping for a Simple XPath"
I "Mapping for Scalar Nodes"
I "Mapping of Predicates"
I "Mapping of Collection Predicates"
I "Document Ordering with Collection Traversals"
I "Collection Index"
I "Non-Satisable XPath Expressions"
I "Namespace Handling"
I "Date Format Conversions"
Mapping for a Simple XPath A rewrite for a simple XPath involves accessing the
attribute corresponding to the XPath expression. Table 511 lists the XPath map:
Query Rewrite with XML Schema-Based Structured Storage
5-58 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Mapping for Scalar Nodes An XPath expression can contain a text() operator which
maps to the scalar content in the XML document. When rewriting, this maps
directly to the underlying relational columns.
For example, the XPath expression /PurchaseOrder/PONum/text() maps to
the SQL column XMLData."PONum" directly.
A NULL value in the PONum column implies that the text value is not available,
either because the text node was not present in the input document or the element
itself was missing. This is more efcient than accessing the scalar element, since we
do not need to check for the existence of the element in the SYS_XBDPD$ attribute.
For example, the XPath /PurchaseOrder/PONum also maps to the SQL
attribute XMLData.PONum,
However, in this case, query rewrite also has to check for the existence of the
element itself, using the SYS_XDBPD$ in the XMLData column.
Mapping of Predicates Predicates are mapped to SQL predicate expressions.
Example 527 Mapping Predicates
For example the predicate in the XPath expression:
/PurchaseOrder[PONum=1001 and Company = "Oracle Corp"]
maps to the SQL predicate:
( XMLData."PONum" = 20 and XMLData."Company" = "Oracle Corp")
For example, the following query is rewritten to the structured (object-relational)
equivalent, and will not require Functional evaluation of the XPath.
select extract(value(p),/PurchaseOrder/Item).getClobval()
Table 511 Simple XPath Mapping for purchaseOrder XML Schema
XPath Expression Maps to
/PurchaseOrder column XMLData
/PurchaseOrder/@PurchaseDate column XMLData."PurchaseDate"
/PurchaseOrder/PONum column XMLData."PONum"
/PurchaseOrder/Item elements of the collection XMLData."Item"
/PurchaseOrder/Item/Part attirbute "Part" in the collection XMLData."Item"
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-59
from mypos p
where existsNode(value(p),/PurchaseOrder[PONum=1001 and Company = "Oracle
Corp"]) =1;
Mapping of Collection Predicates XPath expressions may involve relational operators
with collection expressions. In Xpath 1.0, conditions involving collections are
existential checks. In other words, even if one member of the collection satises the
condition, the expression is true.
Example 528 Mapping Collection Predicates
For example the collection predicate in the XPath:
/PurchaseOrder[Items/Price > 200]
-- maps to a SQL collection expression:
EXISTS ( SELECT null
FROM TABLE (XMLDATA."Item") x
WHERE x."Price" > 200 )
For example, the following query is rewritten to the structured equivalent.
select extract(value(p),/PurchaseOrder/Item).getClobval()
from mypos p
where existsNode(value(p),/PurchaseOrder[Item/Price > 400]) = 1;
More complicated rewrites occur when you have a collection <condition>
collection. In this case, if at least one combination of nodes fromthese two collection
arguments satisfy the condition, then the predicate is deemed to be satised.
Example 529 Mapping Collection Predicates, Using existsNode()
For example, consider a ctitious XPath which checks to see if a Purchaseorder
has Items such that the price of an item is the same as some part number:
/PurchaseOrder[Items/Price = Items/Part]
-- maps to a SQL collection expression:
EXISTS ( SELECT null
FROM TABLE (XMLDATA."Item") x
WHERE EXISTS ( SELECT null
FROM TABLE(XMLDATA."Item") y
WHERE y."Part" = x."Price"))
For example, the following query is rewritten to the structured equivalent:
select extract(value(p),/PurchaseOrder/Item).getClobval()
from mypos p
Query Rewrite with XML Schema-Based Structured Storage
5-60 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
where existsNode(value(p),/PurchaseOrder[Item/Price = Item/Part]) = 1;
Document Ordering with Collection Traversals Most of the rewrite preserves the original
document ordering. However, since the SQL systemdoes not guarantee ordering on
the results of subqueries, when selecting elements from a collection using the
extract() function, the resultant nodes may not be in document order.
Example 530 Document Ordering with Collection Traversals
For example:
SELECT extract(value(p),/PurchaseOrder/Item[Price>2100]/Part)
FROM mypos p;
is rewritten to use subqueries as shown in the following:
SELECT (SELECT XMLAgg( XMLForest(x."Part" AS "Part"))
FROM TABLE (XMLData."Item") x
WHERE x."Price" > 2100 )
FROM po_tab p;
Though in most cases, the result of the aggregation would be in the same order as
the collection elements, this is not guaranteed and hence the results may not be in
document order. This is a limitation that may be xed in future releases.
Collection Index An XPath expression can also access a particular index of a
collection For example, /PurchaseOrder/Item[1]/Part is rewritten to
extract out the rst Item of the collection and then access the Part attribute within
that.
If the collection has been stored as a VARRAY, then this operation retrieves the
nodes in the same order as present in the original document. If the mapping of the
collection is to a nested table, then the order is undetermined. If the VARRAY is
stored as an Ordered Collection Table (OCT), (the default for the tables created by
the schema compiler, if storeVarrayAsTable=true is set), then this collection
index access is optimized to use the IOT index present on the VARRAY.
Non-Satisable XPath Expressions An XPath expression can contain references to
nodes that cannot be present in the input document. Such parts of the expression
map to SQL NULLs during rewrite. For example the XPath expression:
/PurchaseOrder/ShipAddress cannot be satised by any instance document
conforming to the PO.xsd XML schema, since the XML schema does not allow for
ShipAddress elements under PurchaseOrder. Hence this expression would
map to a SQL NULL literal.
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-61
Namespace Handling Namespaces are handled in the same way as the function-based
evaluation. For schema based documents, if the function (like existsNode() or
extract()) does not specify any namespace parameter, then the target namespace
of the schema is used as the default namespace for the XPath expression.
Example 531 Handling Namespaces
For example, the XPath expression /PurchaseOrder/PONum is treated as
/a:PurchaseOrder/a:PONum with
xmlns:a="http://www.oracle.com/PO.xsd if the SQL function does not
explicitly specify the namespace prex and mapping. In other words:
SELECT * FROM po_tab p
WHERE EXISTSNODE(value(p), /PurchaseOrder/PONum) = 1;
is equivalent to the query:
SELECT * FROM po_tab p
WHERE EXISTSNODE(value(p),/PurchaseOrder/PONum,
xmlns="http://www.oracle.com/PO.xsd) = 1;
When performing query rewrite, the namespace for a particular element is matched
with that of the XML schema denition. If the XML schema contains
elementFormDefault=qualified then each node in the XPath expression
must target a namespace (this can be done using a default namespace specication
or by prexing each node with a namespace prex).
If the elementFormDefault is unqualied (which is the default), then only the
node that denes the namespace should contain a prex. For instance if the PO.xsd
had the element form to be unqualied, then the existsNode() function should
be rewritten as:
EXISTSNODE(value(p),/a:PurchaseOrder/PONum,
xmlns:a="http://www.oracle.com/PO.xsd") = 1;
Note: For the case where elementFormDefault is unqualied,
omitting the namespace parameter in the SQL function
existsNode() in the preceding example, would cause each node
to default to the target namespace. This would not match the XML
schema denition and consequently would not return any result.
This is true whether the function is rewritten or not.
Query Rewrite with XML Schema-Based Structured Storage
5-62 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Date Format Conversions The default date formats are different for XML schema and
SQL. Consequently, when rewriting XPath expressions involving comparisons with
dates, you need to use XML formats.
Example 532 Date Format Conversions
For example, the expression:
[@PurchaseDate="2002-02-01"]
cannot be simply rewritten as:
XMLData."PurchaseDate" = "2002-02-01"
since the default date format for SQL is not YYYY-MM-DD. Hence during query
rewrite, the XML format string is added to convert text values into date datatypes
correctly. Thus the preceding predicate would be rewritten as:
XMLData."PurchaseDate" = TO_DATE("2002-02-01","SYYYY-MM-DD");
Similarly when converting these columns to text values (needed for extract(),
and so on), XML format strings are added to convert them to the same date format
as XML.
XPath Expression Rewrites for existsNode()
existsNode() returns a numerical value 0 or 1 indicating if the XPath returns any
nodes (text() or element nodes). Based on the mapping discussed in the earlier
section, an existsNode() simply checks if a scalar element is non-NULL in the
case where the XPath targets a text() node or a non-scalar node and checks for
the existence of the element using the SYS_XDBPD$ otherwise. If the SYS_XDBPD$
attribute is absent, then the existence of a scalar node is determined by the NULL
information for the scalar column.
existsNode Mapping with Document Order Maintained Table 512 shows the mapping of
various XPaths in the case of existsNode() when document ordering is
preserved, that is, when SYS_XDBPD$ exists and maintainDOM="true in the
schema document.
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-63
Example 533 existsNode Mapping with Document Order Maintained
Using the preceding mapping, a query which checks whether the purchaseorder
with number 2100 contains a part with price greater than 2000:
SELECT count(*)
FROM mypos p
WHERE EXISTSNODE(value(p),/PurchaseOrder[PONum=1001 and Item/Price > 2000])=
1;
would become:
SELECT count(*)
Table 512 XPath Mapping for existsNode() with Document Ordering Preserved
XPath Expression Maps to
/PurchaseOrder CASE WHEN XMLData IS NOT NULL THEN 1 ELSE 0 END
/PurchaseOrder/@PurchaseDate CASE WHEN Check_Node_Exists(XMLData.SYS_XDBPD$, PurchaseDate) = 1
THEN 1 ELSE 0 END
/PurchaseOrder/PONum CASE WHEN Check_Node_Exists(XMLData.SYS_XDBPD$, PONum) = 1
THEN 1 ELSE 0 END
/PurchaseOrder[PONum = 2100] CASE WHEN XMLData."PONum" = 2100 THEN 1 ELSE 0
/PurchaseOrder[PONum =
2100]/@PurchaseDate
CASE WHEN XML Data."PONum" = 2100 AND Check_Node_Exists(XMLData.SYS_XDBPD$,
PurchaseDate) = 1
THEN 1 ELSE 0 END
/PurchaseOrder/PONum/text() CASE WHEN XMLData."PONum" IS NOT NULL THEN 1 ELSE 0
/PurchaseOrder/Item CASE WHEN EXISTS (
SELECT NULL FROM TABLE ( XMLData."Item" ) x
WHERE value(x) IS NOT NULL) THEN 1 ELSE 0 END
/PurchaseOrder/Item/Part CASE WHEN EXISTS (
SELECT NULL FROM TABLE (XMLData."Item" ) x
WHERE Check_Node_Exists(x.SYS_XDBPD$, Part) = 1)
THEN 1 ELSE 0 END
/PurchaseOrder/Item/Part/text() CASE WHEN EXISTS (
SELECT NULL FROM TABLE (XMLData."Item" ) x
WHERE x."Part" IS NOT NULL) THEN 1 ELSE 0 END
Query Rewrite with XML Schema-Based Structured Storage
5-64 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
FROM mypos p
WHERE CASE WHEN
p.XMLData."PONum" = 1001 AND
EXISTS ( SELECT NULL
FROM TABLE ( XMLData."Item") p
WHERE p."Price" > 2000 )) THEN 1 ELSE 0 END = 1;
The CASE expression gets further optimized due to the constant relational equality
expressions and this query becomes:
SELECT count(*)
FROM mypos p
WHERE p.XMLData."PONum" = 1001 AND
EXISTS ( SELECT NULL
FROM TABLE ( p.XMLData."Item") x
WHERE x."Price" > 2000 );
which would use relational indexes for its evaluation, if present on the Part and
PONum columns.
existsNode Mapping Without Maintaining Document Order If the SYS_XDBPD$ does not
exist (that is, if the XML schema species maintainDOM="false") then NULL
scalar columns map to non-existent scalar elements. Hence you do not need to
check for the node existence using the SYS_XDBPD$ attribute. Table 513 shows the
mapping of existsNode() in the absence of the SYS_XDBPD$ attribute.
Table 513 XPath Mapping for existsNode Without Document Ordering
XPath Expression Maps to
/PurchaseOrder CASE WHEN XMLData IS NOT NULL THEN 1 ELSE 0 END
/PurchaseOrder/@PurchaseDate CASE WHEN XMLData.PurchaseDate IS NOT NULL THEN 1 ELSE 0 END
/PurchaseOrder/PONum CASE WHEN XMLData."PONum" IS NOT NULL THEN 1 ELSE 0 END
/PurchaseOrder[PONum = 2100] CASE WHEN XMLData."PONum" = 2100 THEN 1 ELSE 0 END
/PurchaseOrder[PONum =
2100]/@PurchaseOrderDate
CASE WHEN XMLData."PONum" = 2100 AND
XMLData."PurchaseDate" NOT NULL THEN 1 ELSE 0 END
/PurchaseOrder/PONum/text() CASE WHEN XMLData."PONum" IS NOT NULL THEN 1 ELSE 0 END
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-65
Rewrite for extractValue()
extractValue() is a shortcut for extracting text nodes and attributes using
extract() and then using a getStringVal() or getNumberVal() to get the
scalar content. extractValue returns the text nodes for scalar elements or the
values of attribute nodes. extractValue() cannot handle returning multiple
values or non-scalar elements.
Table 514 shows the mapping of various XPath expressions in the case of
extractValue(). If an XPath expression targets an element, extractValue retrieves
the text node child of the element. Thus the two XPath expressions,
/PurchaseOrder/PONum and /PurchaseOrder/PONum/text() are handled
identically by extractValue and both of them retrieve the scalar content of
PONum.
/PurchaseOrder/Item CASE WHEN EXISTS (
SELECT NULL FROM TABLE (XMLData."Item" ) x
WHERE value(x) IS NOT NULL) THEN 1 ELSE 0 END
/PurchaseOrder/Item/Part CASE WHEN EXISTS (
SELECT NULL FROM TABLE (XMLData."Item") x
WHERE x."Part" IS NOT NULL) THEN 1 ELSE 0 END
/PurchaseOrder/Item/Part/text() CASE WHEN EXISTS (
SELECT NULL FROM TABLE (XMLData."Item") x
WHERE x."Part" IS NOT NULL) THEN 1 ELSE 0 END
Table 514 XPath Mapping for extractValue()
XPath Expression Maps to
/PurchaseOrder Not supported - ExtractValue can only retrieve values for scalar
elements and attributes
/PurchaseOrder/@PurchaseDate XMLData."PurchaseDate"
/PurchaseOrder/PONum XMLData."PONum"
/PurchaseOrder[PONum = 2100] (SELECT TO_XML(x.XMLData) FROM Dual WHERE x."PONum" =
2100)
Table 513 XPath Mapping for existsNode Without Document Ordering (Cont.)
XPath Expression Maps to
Query Rewrite with XML Schema-Based Structured Storage
5-66 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 534 Rewriting extractValue()
For example, an SQL query such as:
SELECT ExtractValue(value(p),/PurchaseOrder/PONum)
FROM mypos p
WHERE ExtractValue(value(p),/PurchaseOrder/PONum) = 1001;
would become:
SELECT p.XMLData."PONum"
FROM mypos p
WHERE p.XMLData."PONum" = 1001;
Since it gets rewritten to simple scalar columns, indexes if any, on the PONum
attribute may be used to satisfy the query.
Creating Indexes ExtractValue can be used in index expressions. If the expression
gets rewritten into scalar columns, then the index is turned into a B*Tree index
instead of a function-based index.
Example 535 Creating Indexes with extract
For example:
create index my_po_index on mypos x
(Extract(value(x),/PurchaseOrder/PONum/text()).getnumberval());
would get rewritten into:
create index my_po_index on mypos x ( x.XMLData."PONum");
/PurchaseOrder[PONum =
2100]/@PurchaseDate
(SELECT x.XMLData."PurchaseDate")
FROM Dual
WHERE x."PONum" = 2100)
/PurchaseOrder/PONum/text() XMLData."PONum"
/PurchaseOrder/Item Not supported - ExtractValue can only retrieve values for scalar
elements and attributes
/PurchaseOrder/Item/Part Not supported - ExtractValue cannot retrieve multiple scalar values
/PurchaseOrder/Item/Part/text() Not supported - ExtractValue cannot retrieve multiple scalar values
Table 514 XPath Mapping for extractValue() (Cont.)
XPath Expression Maps to
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-67
and thus becomes a regular B*Tree index. This is useful, since unlike a
function-based index, the same index can now satisfy queries which target the
column such as:
EXISTSNODE(value(x),/PurchaseOrder[PONum=1001]) = 1;
Rewrite for extract()
extract() retrieves the results of XPath as XML. The rewrite for extract() is
similar to that of extractValue() for those Xpath expressions involving text
nodes.
Extract Mapping with Document Order Maintained Table 515 shows the mapping of
various XPath in the case of extract() when document order is preserved (that is,
when SYS_XDBPD$ exists and maintainDOM="true" in the schema document).
Note: The examples showXMLElement() and XMLForest()
with an empty alias string "" to indicate that you create a XML
instance with only text values. This is shown for illustration only.
Table 515 XPath Mapping for extract() with Document Ordering Preserved
XPath Maps to
/PurchaseOrder XMLForest(XMLData as "PurchaseOrder")
/PurchaseOrder/@PurchaseDate CASE WHEN Check_Node_Exists(XMLData.SYS_XDBPD$, PurchaseDate) = 1
THEN XMLElement("" , XMLData."PurchaseDate") ELSE NULL END
/PurchaseOrder/PONum CASE WHEN Check_Node_Exists(XMLData.SYS_XDBPD$, PONum) = 1
THEN XMLElement("PONum" , XMLData."PONum") ELSE NULL END
/PurchaseOrder[PONum = 2100] (SELECT XMLForest(XMLData as "PurchaseOrder") from Dual
where x."PONum" = 2100)
/PurchaseOrder[PONum = 2100]/@PurchaseDate (SELECT CASE WHEN
Check_Node_Exists(x.XMLData.SYS_XDBPD$,PurchaseDate") = 1
THEN XMLElement("", XMLData."PurchaseDate")
ELSE NULL END
from Dual where x."PONum" = 2100)
Query Rewrite with XML Schema-Based Structured Storage
5-68 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 536 XPath Mapping for extract() with Document Ordering Preserved
Using the mapping in Table 515, a query that extracts the PONum element where
the purchaseorder contains a part with price greater than 2000:
SELECT Extract(value(p),/PurchaseOrder[Item/Part > 2000]/PONum)
FROM po_tab p;
would become:
SELECT (SELECT CASE WHEN Check_Node_Exists(p.XMLData.SYS_XDBPD$, PONum) = 1
THEN XMLElement("PONum", p.XMLData."PONum")
ELSE NULL END)
FROM DUAL
WHERE EXISTS( SELECT NULL
FROM TABLE ( XMLData."Item") p
WHERE p."Part" > 2000)
)
FROM po_tab p;
Check_Node_Exists is an internal function that is for illustration purposes only.
Extract Mapping Without Maintaining Document Order If the SYS_XDBPD$ does not exist,
that is, if the XML schema species maintainDOM="false", then NULL scalar
columns map to non-existent scalar elements. Hence you do not need to check for
the node existence using the SYS_XDBPD$ attribute. Table 516 shows the mapping
of existsNode() in the absence of the SYS_XDBPD$ attribute.
/PurchaseOrder/PONum/text() XMLElement("", XMLData.PONum)
/PurchaseOrder/Item (SELECT XMLAgg(XMLForest(value(p) as "Item"))
from TABLE ( x.XMLData."Item" ) p
where value(p) IS NOT NULL )
/PurchaseOrder/Item/Part (SELECT XMLAgg(
CASE WHEN Check_Node_Exists(p.SYS_XDBPD$,Part") = 1
THEN XMLForest(p."Part" as "Part") ELSE NULL END)
from TABLE ( x.XMLData."Item" ) p)
/PurchaseOrder/Item/Part/text() (SELECT XMLAgg(XMLElement(" ", p."Part") )
from TABLE ( x.XMLData."Item" ) x )
Table 515 XPath Mapping for extract() with Document Ordering Preserved (Cont.)
XPath Maps to
Query Rewrite with XML Schema-Based Structured Storage
Structured Mapping of XMLType 5-69
Optimizing Updates Using updateXML()
A regular update using updateXML() involves updating a value of the XML
document and then replacing the whole document with the newly updated
document.
When XMLType is stored object relationally, using XML schema mapping, updates
are optimized to directly update pieces of the document. For example, updating the
PONum element value can be rewritten to directly update the XMLData.PONum
column instead of materializing the whole document in memory and then
performing the update.
updateXML() must satisfy the following conditions for it to use the optimization:
I The XMLType column supplied to updateXML() must be the same column
being updated in the SET clause. For example:
UPDATE po_tab p SET value(p) = updatexml(value(p),...);
Table 516 XPath Mapping for extract() Without Document Ordering Preserved
XPath Equivalent to
/PurchaseOrder XMLForest(XMLData AS "PurchaseOrder")
/PurchaseOrder/@PurchaseDate XMLForest(XMLData."PurchaseDate" AS "")
/PurchaseOrder/PONum XMLForest(XMLData."PONum" AS "PONum")
/PurchaseOrder[PONum = 2100] (SELECT XMLForest(XMLData AS "PurchaseOrder")
from Dual where x."PONum" = 2100)
/PurchaseOrder[PONum =
2100]/@PurchaseDate
(SELECT XMLForest(XMLData."PurchaseDate" AS "")
from Dual where x."PONum" = 2100)
/PurchaseOrder/PONum/text() XMLForest(XMLData.PONum AS "")
/PurchaseOrder/Item (SELECT XMLAgg(XMLForest(value(p) as "Item")
from TABLE ( x.XMLData."Item" ) p
where value(p) IS NOT NULL )
/PurchaseOrder/Item/Part (SELECT XMLAgg(XMLForest(p."Part" AS "Part")
from TABLE ( x.XMLData."Item" ) p)
/PurchaseOrder/Item/Part/text() (SELECT XMLAgg( XMLForest(p. "Part" AS "Part") )
from TABLE ( x.XMLData."Item" ) p )
Creating Default Tables During XML Schema Registration
5-70 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I The XMLType column must have been stored object relationally using Oracle
XML DBs XML schema mapping.
I The XPath expressions must not involve any predicates or collection traversals.
I There must be no duplicate scalar expressions.
I All XPath arguments in the updateXML() function must target only scalar
content, that is, text nodes or attributes. For example:
UPDATE po_tab p SET value(p) =
updatexml(value(p),/PurchaseOrder/@PurchaseDate,2002-01-02,
/PurchaseOrder/PONum/text(), 2200);
If all the preceding conditions are satised, then the updateXML is rewritten into a
simple relational update. For example:
UPDATE po_tab p SET value(p) =
updatexml(value(p),/PurchaseOrder/@PurchaseDate,2002-01-02,
/PurchaseOrder/PONum/text(), 2200);
becomes:
UPDATE po_tab p
SET p.XMLData."PurchaseDate" = TO_DATE(2002-01-02,SYYYY-MM-DD),
p.XMLData."PONum" = 2100;
DATE Conversions Date datatypes such as DATE, gMONTH, gDATE, and so on, have
different format in XML schema and SQL. In such cases, if the updateXML() has a
string value for these columns, the rewrite automatically puts the XML format
string to convert the string value correctly. Thus string value specied for DATE
columns, must match the XML date format and not the SQL DATE format.
Creating Default Tables During XML Schema Registration
As part of XML schema registration, you can also create default tables. Default
tables are most useful when XML instance documents conforming to this XML
schema are inserted through APIs that do not have any table specication, such as
with FTP or HTTP. In such cases, the XML instance is inserted into the default table.
If you have given a value for attribute defaultTable, the XMLType table is
created with that name. Otherwise it gets created with an internally generated
name.
Further, any text specied using the tableProps and columnProps attribute are
appended to the generated CREATE TABLE statement.
Cyclical References Between XML Schemas
Structured Mapping of XMLType 5-71
Ordered Collections in Tables (OCTs)
Arrays in XML schemas (elements with maxOccurs > 1) are usually stored in
VARRAYs, which can be stored either in a Large Object (LOB) or in a separate store
table, similar to a nested table.
This allows the elements of a VARRAY to reside in a separate table based on an IOT.
The primary key of the table is (NESTED_TABLE_ID, ARRAY_INDEX). NESTED_
TABLE_ID is used to link the element with their containing parents while the
ARRAY_INDEX column keeps track of the position of the element within the
collection.
Using OCT for VARRAY Storage
There are two ways to specify an OCT storage:
I By means of the schema attribute storeVarrayAsTable. By default this is
false and VARRAYs are stored in a LOB. If this is set to true, all
VARRAYs, all elements that have maxOccurs > 1, will be stored as OCTs.
I By explicitly specifying the storage using the tableProps attribute. The
exact SQL needed to create an OCT can be used as part of the tableProps
attribute:
VARRAY xmldata.<array> STORE AS TABLE <myTable> ((PRIMARY KEY (NESTED_
TABLE_ID, ARRAY_INDEX)) ORGANIZATION INDEX)
The advantages of using OCTs for VARRAY storage include faster access to
elements and better queryability. Indexes can be created on attributes of the element
and these can aid in better execution for query rewrite.
Cyclical References Between XML Schemas
XML schema documents can have cyclic dependencies that can prevent them from
being registered one after the other in the usual manner. Examples of such XML
schemas follow:
Note: When elements of a VARRAY are stored in a separate table,
the VARRAY is referred to as an Ordered Collection in Tables
(OCT). In the following paragraphs, references to OCT also assume
that you are using Index Organized Table (IOT) storage for the
store table.
Cyclical References Between XML Schemas
5-72 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 537 Cyclic Dependencies
An XML schema that includes another xml schema cannot be created if the included
xml schema does not exist.
begin dbms_xmlschema.registerSchema(xm40.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:my="xm40"
targetNamespace="xm40">
<include schemaLocation="xm40a.xsd"/>
<!-- Define a global complextype here -->
<complexType name="Company">
<sequence>
<element name="Name" type="string"/>
<element name="Address" type="string"/>
</sequence>
</complexType>
<!-- Define a global element depending on included schema -->
<element name="Emp" type="my:Employee"/>
</schema>,
true, true, false, true); end;
/
It can however be created with the FORCE option:
begin dbms_xmlschema.registerSchema(xm40.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:my="xm40"
targetNamespace="xm40">
<include schemaLocation="xm40a.xsd"/>
<!-- Define a global complextype here -->
<complexType name="Company">
<sequence>
<element name="Name" type="string"/>
<element name="Address" type="string"/>
</sequence>
</complexType>
<!-- Define a global element depending on included schema -->
<element name="Emp" type="my:Employee"/>
</schema>,
true, true, false, true, true); end;
/
Attempts to use this schema and recompile will fail:
create table foo of sys.xmltype xmlschema "xm40.xsd" element "Emp";
Cyclical References Between XML Schemas
Structured Mapping of XMLType 5-73
Now create the second XML schema with FORCE option. This should also make the
rst XML schema valid:
begin dbms_xmlschema.registerSchema(xm40a.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:my="xm40"
targetNamespace="xm40">
<include schemaLocation="xm40.xsd"/>
<!-- Define a global complextype here -->
<complexType name="Employee">
<sequence>
<element name="Name" type="string"/>
<element name="Age" type="positiveInteger"/>
<element name="Phone" type="string"/>
</sequence>
</complexType>
<!-- Define a global element depending on included schema -->
<element name="Comp" type="my:Company"/>
</schema>,
true, true, false, true, true); end;
/
Both XML schemas can be used to create tables, and so on:
create table foo of sys.xmltype xmlschema "xm40.xsd" element "Emp";
create table foo2 of sys.xmltype xmlschema "xm40a.xsd" element "Comp";
To register both these XML schemas which have a cyclic dependency on each other,
you must use the FORCE parameter in DBMS_XMLSCHEMA.registerSchema as
follows:
1. Step 1: Register s1.xsd in FORCE mode:
dbms_xmlschema.registerSchema("s1.xsd", "<schema ...", ..., force => true)
At this point, s1.xsd is invalid and cannot be used.
2. Step 2: Register s2.xsd in FORCE mode:
dbms_xmlschema.registerSchema("s2.xsd", "<schema ..", ..., force => true)
The second operation automatically compiles s1.xsd and makes both XML
schemas valid.
See Figure 58. The preceding example is illustrated in the lower half of the gure.
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
5-74 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 58 Cyclical References Between XML Schemas
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based
Issues
Why Do I Appear to get Memory Leaks When Using Bind Variables for XPath
Expressions?
Consider the following simple XML document that is blown up to 3.6 Megabytes:
<?xml version="1.0"?>
<PurchaseOrder xmlns="http://www.vector.com/po.xsd"
xmlns:xdb="http://xmlns.oracle.com/xdb"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.vector.com/po.xsd
http://www.vector.com/po.xsd">
<PONum>1001</PONum>
<Company>Oracle Corp</Company>
XML schema 1, S1
S3
XML schema 2, S2
S1
XML schema 3, S3
S2
References
References References
XML schema 1, S1
S2
XML schema 2, S2
S1
References
References
OR
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
Structured Mapping of XMLType 5-75
<Item>
<Part>9i Doc Set</Part>
<Price>2550</Price>
</Item>
<Item>
<Part>8i Doc Set</Part>
<Price>350</Price>
</Item>
<Item>
<Part>7i Doc Set</Part>
<Price>50</Price>
</Item>
</PurchaseOrder>
This document is stored in an XMLTYPE table object-relationally. The XML schema
was not annotated.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="PONum" type="xsd:decimal"/>
<xsd:element name="Company">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Item" maxOccurs="2147483647">
<xsd:complexType>
<xsd:sequence>
...
Name Null? Type
----------------------------------------- -------- -------------------
FILENAME NOT NULL VARCHAR2(20)
CONTENT NOT NULL
XMLTYPE(XMLSchema "http://www.vector.com/po.xsd"
Element "PurchaseOrder") STORAGE Object-relational TYPE
"PurchaseOrderType1627_T"
The statement:
SQL> select existsnode(srp.content,'/PurchaseOrder/Item[Part="7i Doc Set"]')
into :i from xmltable srp where filename='po6.xml';
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
5-76 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
takes about 6 seconds on my laptop. When I use a bind variable such as:
SQL> var xpath varchar2(50)
SQL> exec :xpath:='/PurchaseOrder/Item[Part="7i Doc Set"]'
PL/SQL procedure successfully completed.
SQL> select existsnode(srp.content,:xpath) into :i from xmltable srp
where filename='po6.xml';
I wait ...The statement hangs; the CPU is busy by 100% and the memory
consumption is high:
Answer: If you use bind variables, Oracle does not rewrite the query, hence you are
seeing a full function-based XPath versus a relational rewrite.
Question 2: We need bind variables for SQL sharing. What happens if you set the
CURSOR_SHARING to FORCE?
Answer 2: Basically, query rewrite means that Oracle is changing the input XPath
expression into some underlying columns. This means that for a given XPath, there
is a particular set of columns/tables,... that will be referenced underneath. This has
to be a compile time operation, since the shared cursor has to knowexactly which
tables and columns, .... it references. This cannot change with each row or
instantiation of the cursor.
So if the XPath expression itself is a bind variable, Oracle cannot do any rewrite,
since each instantiation of the cursor can have totally different XPath. This is akin to
the user binding the name of the table/column in a SQL query. For example,
SELECT * FROM table(:1).
When CURSOR_SHARING is set to FORCE, by default all string constants including
XPath become a bind variable. At that time when Oracle encounters
extractvalue(),existsnode(),..., Oracle look at the XPath bind variables to
check if they are really constants. If so Oracle uses them and rewriteS the query.
Hence there the big difference inwhere the bind variable is used.
Note: You can specify bind variables in the right-hand side of the query
and that would work ne. For example:
SELECT * FROM purchaseorder p WHERE
extractvalue(value(p),'/PurchaseOrder/LineItems/LineIte
m/ItemNumber') = :1;
would use Oracles usual bind variable sharing. ...
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
Structured Mapping of XMLType 5-77
How Do I Check that Query Rewrite is Working Correctly?
I have a question about query rewrite with XML schema-Based object-relational
storage. How can I check that query rewrite is working correctly? Should I use an
SQL trace, events, and so on?
Answer: You can check query rewrites in two ways:
I Use an EXPLAIN plan. This shows you the use of indexes,... that prove the use
of query rewrites.
I Use EVENTS. For example:
Event 19027 - turns off query rewrite - no level information needed
Event19021-XMLoperations-generalevent.Usethiswithdifferentlevels
to get different behavior..
Level 0x1 - Turn off all functional evaluation..
Level 0x2 - Turn off functional evaluation of EXTRACT
Level 0x4 - Turn off functional evaluation of EXISTSNODE
Level 0x8 - Turn off functional evaluation of TRANSFORM
Level 0x10 - Turn off functional evaluation of EXTRACTVALUE
Level 0x20 - Turn off functional evaluation of UPDATEXML
Using the second event 19021, you can selectively, raise errors, if the functional
evaluation of these operators are chosen. For example:
ALTER SESSION SET EVENTS 19021 trace name context forever, level 1;
would turn off the functional evaluation of ALL XML operators listed above.
Hence when you re a query such as:
SELECT extract(value(x),/purchaseorder/reference)
FROM purchaseorder_xml_tab
if the query rewrite does not happen, then the extract() raises an
ORA-19022 XPath functions are disabled error;
Question 2: According to your suggestions,I used event 19021. Here is the test case
I used:
1--set event
SQL> alter session set events 19021 trace name context forever, level 2;
Session altered.
2--extract function used
I tried this with both XML schema-based and non-schema-based.
For XML schema-based object-relational storage:
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
5-78 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
SQL> SELECT value(x).extract(/a:PO/Company,
2 xmlns:a="http://www.oracle.com/PO")
3 FROM po_tab x;
But I get the following error:
ERROR:
ORA-19022: XML XPath functions are disabled
ORA-06512: at "SYS.XMLTYPE", line 0
ORA-06512: at line 1
For non-schema-based CLOB storage:
SQL> SELECT extract(value(p),/PO/PODATE)
2 FROM po_tab p;
results in the following error:
ERROR:
ORA-19022: XML XPath functions are disabled
This result indicates that query rewrite does not occur. Are there other ways to
check query rewrite?
Answer 2: You are doing the right thing. Setting event 19021 turns off functional
evaluation, so that all XMLType functions will be turned off, and if query rewrite
does not happen, you will get error ORA-19022 (XML XPath functions are
disabled).
The reason the second example (non-schema based) is not working is that query
rewrite can happen only for non-schema-based (NSB) XMLType views (XVs),
dened over objects. It does not happen for non-schema-based XMLType tables,
since the storage is CLOB-based.
The reason the rst example (schema-based) is not working is probably the
namespace parameter.
Query rewrite does not currently function for extract() or existsNode()
XMLType methods. You can however use the operator equivalents instead of the
XMLType methods. For example, use extract() operator instead of
xmltype.extract() method.
Why Does the XML DB Query Not Use My Index?
I ran the demo script that orchestrates running all the other scripts. It creates an
index like this:
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
Structured Mapping of XMLType 5-79
create index director_name on movies(
extractValue(movieDoc,/Movie/Director/Last) );
But when I try an Explain Plan on this query:
SELECT extractValue(movieDoc,/Movie/@Title)
FROM movies
WHERE extractValue(movieDoc,/Movie/Director/Last) = Minghella
It does not appear to use my index. Here is the EXPLAIN plan from the
JDeveloper9i Explain Plan GUI:
SELECT STATEMENT
- Filter
- Table Access (FULL) SCOTT.MOVIES
- Collection Iterator (PICKLER FETCH)
Is this because I do not have enough movies in my table, so the Optimizer decides
that a full table scan is fastest? I also tried:
SELECT /*+ INDEX(movies director_name) */
extractValue(movieDoc,/Movie/@Title)
FROMmovies
WHERE extractValue(movieDoc,/Movie/Director/Last) = Minghella
but it still does a full table scan of MOVIES.
Answer: When you create a non-schema-based index on XMLType, the indexes end
up as function-based indexes. You can check user_functional_indexes. For a
function-based index, the string must match exactly and you need to use ALTER
SESSION as follows:
ALTER SESSION SET query_rewrite_enabled=true
ALTER SESSION SET query_Rewrite_integrity=trusted
for it to detect the indexes.
How Do I Specify Attributes in a complexType XML Schema Declaration?
Answer: If you have an element based on a global complexType, the SQLType
(and SQLSchema) attributes should be specied for the complexType declaration.
In addition you can (optionally) include the same SQLType and SQLSchema
attributes within the element declaration.
The reason is that if you do not specify the SQLType for the global complexType,
XML DB creates an SQLType with an internally generated name. The elements that
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
5-80 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
reference this global type cannot then have a different value for SQLType. In other
words, this is ne:
<xsd:complexType name="PURCHASEORDERLINEITEM_TYPEType">
<xsd:sequence>
<xsd:element name="@LineNo" type="xsd:double" xdb:SQLName="@LineNo"
xdb:SQLType="NUMBER"/>
<xsd:element name="Decription" type="xsd:string"xdb:SQLName="Decription"
xdb:SQLType="VARCHAR2"/>
<xsd:element name="Part" type="PURCHASEORDERPART_TYPEType"xdb:SQLName="Part"
/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="PURCHASEORDERPART_TYPEType" xdb:SQLSchema="XMLUSER"
xdb:SQLType="PURCHASEORDERPART_TYPE">
<xsd:sequence>
<xsd:element name="@Id" type="xsd:string"
xdb:SQLName="@Id"xdb:SQLType="VARCHAR2"/>
<xsd:element name="@Quantity" type="xsd:double"xdb:SQLName="@Quantity"
xdb:SQLType="NUMBER"/>
<xsd:element name="@cost" type="xsd:double"
xdb:SQLName="@cost"xdb:SQLType="NUMBER"/>
</xsd:sequence>
</xsd:complexType>
The following is also okay:
<xsd:complexType name="PURCHASEORDERLINEITEM_TYPEType">
<xsd:sequence>
<xsd:element name="@LineNo" type="xsd:double" xdb:SQLName="@LineNo"
xdb:SQLType="NUMBER"/>
<xsd:element name="Decription" type="xsd:string"xdb:SQLName="Decription"
xdb:SQLType="VARCHAR2"/>
<xsd:element name="Part" type="PURCHASEORDERPART_TYPEType"xdb:SQLName="Part"
xdb:SQLSchema="XMLUSER"
xdb:SQLType="PURCHASEORDERPART_TYPE" />
</xsd:sequence>
</xsd:complexType>
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
Structured Mapping of XMLType 5-81
Why Do the XML Schema and Element Not Match?
Given this table denition
SQL> describe "rechnung";
Name Null? Type
------------------------ ----- ---------------
ID NOT NULL NUMBER(10)
rechnung
SYS.XMLTYPE(XMLSchema "http://cczarski.de.oracle.com/Rec
hnung/Test001.xsd"
Element "rechnung") STORAGE Object-relational TYPE "RECHNUNG_T"
DATUM DATE
And this schema
<?xml version="1.0" encoding="iso-8859-1"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://cczarski.de.oracle.com/Rechnung/Test001.xsd"
xmlns:xdb="http://xmlns.oracle.com/xdb"
xmlns:rechn="http://cczarski.de.oracle.com/Rechnung/Test001.xsd"
elementFormDefault="qualified"
version="1.0">
<!-- Zundchst wird der Kunde definiert --
Why does inserting this document:
<rechnung xmlns="http://.../Test001.xsd" xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://cczarski.d
e.oracle.com/Rechnung/Test001.xsd">
<kunde>
...
Report
ERROR at line 2:
ORA-19007: Schema and element do not match
Answer: xsi:schemaLocation takes two parameters: "NS SchemaURL"
try:
xsi:schemaLocation="http://cczarski.de.oracle.com/Rechnung/Test001.xsd
http://cczarski.de.oracle.com/Rechnung/Test001.xsd">
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
5-82 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
How Do I Pull a Stylesheet From RESOURCE_VIEW [S/MIME]?
I am having trouble pulling out the saved stylesheet fromRESOURCE_VIEW with
the following statement:
SELECT EXTRACT
(rtab.res,
'r:Resource/r:Contents/node()/xsl:stylesheet',
'xmlns:r="http://xmlns.oracle.com/xdb/XDBResource.xsd" '||
'xmlns:xdb="http://xmlns.oracle.com/xdb" ' ||
'xmlns:xsl="http://www.w3.org/1999/XSL/Transform"'
).getclobval()
FROM resource_view rtab
WHERE rtab.any_path =
'/public/spec_proto/XDB_Stylesheet_Render_XML.xsl'
/
Did I err in terms of the namespace?
Answer: Do you have the XSL schema registered? At this time, extracting from
resource contents will not work unless the contents are from a registered XML
schema.
Why for Our XML Parser Does selectSingleNode return NULL When the xmlns
Attribute is Added?
Our code parses an XML le that is an instance of our own XML schema
ApplicationStructure. It works ne, until we add
xmlns="http://www.oracle.com/JHeadstart/ApplicationStructure"
in the top-level tag. Then the call to selectSingleNode suddenly returns NULL.
If we remove the xmlns attribute, selectSingleNode again returns the node we
want. Our code:
import oracle.xml.parser.v2.*;
...
private XMLDocument mXmldoc;
mXmldoc = XMLLoader.getXMLDocument(mSource);
// Select Service node
XMLNode serviceNode = (XMLNode)mXmldoc.selectSingleNode("Service");
What are we doing wrong?
It seems that there is another constructor of selectSingleNode, which accepts a
second parameter NSResolver. How must we use this and can we make it work
with XML les with the xmlns attribute and without it?
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
Structured Mapping of XMLType 5-83
We would like to be able to use the xmlns attribute, so that we can benet from the
JDeveloper9i Code Insight for our own registered XML Schema.
Answer: XPath has no syntax for searching on elements that are qualied with the
default namespace. The XPath pattern "foo" always searches for the element <foo>
with a null namespace. So that even though the default namespace
*SYNTACTICALLY* allows you the convenience of writing:
<foo xmlns="urn:mynamespace"/>
To the XML Parser internally, this is an Element named: <{urn:mynamespace}:foo>
and not just:
<foo>
So, moral of the story, is that to search for anything with a namespace URI,
including default namespace, use the following:
I A namespace prex in the <foo xmlns="urn:mynamespace"/>
I An XPath pattern like "someprex:foo" where you have mapped the
"someprex" prex to the "urn:mynamespace" namespace URI.
Here's an example:
package test;
import oracle.xml.parser.v2.*;
import org.w3c.dom.*;
import java.io.*;
public class Demo {
private static final String URI =
"http://www.oracle.com/JHeadstart/ApplicationStructure";
private static final String TESTDOC =
"<foo xmlns='"+URI+"'/>";
private static final NSResolver nsr = new MyNSResolver();
public static void main(String[] args) throws Throwable {
System.out.println("Document to parse is");
System.out.println(TESTDOC);
DOMParser dp = new DOMParser();
dp.parse( new StringReader(TESTDOC));
XMLDocument doc = dp.getDocument();
Node n = doc.selectSingleNode("xxx:foo", nsr); // Provide NSResolver!
System.out.println( "Found " + ((n!=null) ? " it! " : " nothing"));
}
static class MyNSResolver implements NSResolver {
public String resolveNamespacePrefix(String pref) {
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
5-84 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
if (pref.equals("xxx")) return URI;
else return null;
}
}
}
Why Do I Get Error ORA-19007: Schema and Element Do Not Match?
This script runs successfully until I insert sample data into the table. It then fails
with ORA-19007: Schema and element do not match. It should work:
---- testPo.sql
set serverout on
drop table po_tab1;
declare
urlvar varchar2(100);
xsdfile varchar2(2000);
begin
urlvar := 'http://www.oracle.com/PO.xsd';
-- xmlns:po="http://www.oracle.com/PO.xsd">
xsdfile :=
'<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/PO.xsd"
xmlns:po="http://www.oracle.com/PO.xsd">
<complexType name="PurchaseOrderType">
<sequence>
<element name="PONum" type="decimal"/>
<element name="Company" type="string"/>
<element name="Item" maxOccurs="1000">
<complexType>
<sequence>
<element name="Part" type="string"/>
<element name="Price" type="decimal"/>
</sequence>
</complexType>
</element>
</sequence>
<attribute name = "PurchaseDate" type = "date"/>
</complexType>
<element name="PurchaseOrder" type = "po:PurchaseOrderType"/>
</schema>';
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
Structured Mapping of XMLType 5-85
begin
dbms_xmlschema.deleteschema(urlvar,dbms_xmlschema.delete_cascade_force);
exception
when others then null;
end;
dbms_xmlschema.registerschema(urlvar,xsdfile);
end;
/
set heading off
set pagesize 0
set long 10000
set maxdata 12000
set arraysize 1
select a.schema.getstringval() from user_xml_schemas a
where a.schema_url = 'http://www.oracle.com/PO.xsd';
CREATE TABLE po_tab1 OF XMLTYPE ELEMENT
"http://www.oracle.com/PO.xsd#PurchaseOrder";
insert into po_tab1 values (xmltype('
<PurchaseOrder xmlns="http://www.oracle.com/PO.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/PO.xsd"
PurchaseDate="1967-08-13">
<PONum>1</PONum>
<Company>The Business</Company>
<Item>
<Part>Part 1</Part>
<Price>1000</Price>
</Item>
</PurchaseOrder>'));
select * from po_tab1;
Answer: The schemaLocation attribute should be a pair of <namespace> and
<schemaloc> values as follows:
xsi:schemaLocation="http://www.oracle.com/PO.xsd
http://www.oracle.com/PO.xsd"
Frequently Asked Questions (FAQs): XML DB, XML Schema-Based Issues
5-86 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Is it Possible to Register XML Schema for Schemas?
I am trying to register the XML schema for schemas with something like. I have
downloaded XMLSchema.xsd, XMLSchema.dtd, datatypes.dtd and made
them available at my local webserver after checking that XMLSchema.xsd can be
validated:
begin
dbms_xmlschema.registeruri( schemaURL =>
'http://www.denmark.dk/MD/XMLSchema'
, schemaDocUri => 'http://144.21.226.78/XMLSchema.xsd'
, local => false
);
end;
/
declare
*
ERROR at line 1:
ORA-31011: XML parsing failed
ORA-19202: Error occurred in XML processing
LPX-00233: namespace prefixes starting with "xml" are reserved
Error at line 70
ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 0
ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 160
ORA-06512: at line 34
I need a table for storing all the XML schemas. The content of this table I want to be
validated against schema for schemas as well as the built-in capability of searching
through the object-relational structures afterwards in order to do analyses that are
more complex. Is it possible to Register XML schema for schemas?
In the original XMLSchema.xsd no XML namespace is declared; hence I could not
validate it in XMLSpy. The I added the xmlns:xml namespace declaration to
validate success in XMLSpy, but I get an error.
Answer: It's illegal to have namespaces that start with xml. Pick another
namespace prex such as, foo or "xsd" or xs or x.
Transforming and Validating XMLType Data 6-1
6
Transforming and Validating XMLType Data
This chapter describes the SQL functions and XMLType APIs for transforming
XMLType data using XSLT stylesheets. It also explains the various functions and
APIs available for validating the XMLType instance against an XML schema. It
contains the following sections:
I Transforming XMLType Instances
I XMLTransform() Examples
I Validating XMLType Instances
I Validating XML Data Stored as XMLType: Examples
Transforming XMLType Instances
6-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Transforming XMLType Instances
XML documents have structure but no format. To add format to the XML
documents you can use Extensible Stylesheet Language (XSL). XSL provides a way
of displaying XML semantics. It can map XML elements into other formatting or
mark-up languages such as HTML.
In Oracle XML DB, XMLType instances or XML data stored in XMLType tables,
columns, or views in Oracle9i database, can be (formatted) transformed into HTML,
XML, and other mark-up languages, using XSL stylesheets and XMLTypes
function, transform(). This process conforms to W3Cs XSLT 1.0 recommendation.
XMLType instance can be transformed in the following ways:
I Using the XMLTransform() SQL function (or the transform() member
function of XMLType) in the database
I Using XDK transformation options in the middle tier, such as XSLT Processor
for Java.
XMLTransform() and XMLType.transform()
Figure 61 shows the XMLTransform() syntax. The XMLTransform() function
takes as arguments an XMLType instance and an XSL stylesheet (which is itself an
XMLType instance). It applies the stylesheet to the instance and returns an XMLType
instance.
Figure 62 shows howXMLTransform() transforms the XML document by using
the XSL stylesheet passed in. It returns the processed output as XML, HTML, and so
on, as specied by the XSL stylesheet. You typically need to use XMLTransform()
See Also:
I Chapter 26, "Oracle XML DB Basic Demo", the section, "8.3
Transforming PurchaseOrder Using XSLT"
I Appendix D, "XSLT Primer"
I Oracle9i XML Developers Kits Guide - XDK, the chapter on XSQL
Pages Publishing Framework
Note: You can also use the syntax, XMLTYPE.transform(). This
is the same as XMLtransform().
XMLTransform() Examples
Transforming and Validating XMLType Data 6-3
when retrieving or generating XML documents stored as XMLType in Oracle9i
database.
Figure 61 XMLTransform() Syntax
Figure 62 Using XMLTransform()
XMLTransform() Examples
Use the following code to set up the XML schema and tables needed to run the
examples in this chapter:
--register schema
begin
dbms_xmlschema.deleteSchema(http://www.example.com/schemas/ipo.xsd,4);
end;
/
begin
dbms_xmlschema.registerSchema(http://www.example.com/schemas/ipo.xsd,
<schema targetNamespace="http://www.example.com/IPO"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:ipo="http://www.example.com/IPO">
<!-- annotation>
<documentation xml:lang="en">
International Purchase order schema for Example.com
Copyright 2000 Example.com. All rights reserved.
</documentation>
</annotation -->
<element name="purchaseOrder" type="ipo:PurchaseOrderType"/>
See Also: Figure 11, "Oracle XML DB Architecture: XMLType
Storage and Repository" in Chapter 1, "Introducing Oracle XML
DB"
XMLTRANSFORM ( XMLType_instance , XMLType_instance )
XMLtransform()
XSL stylesheet
XMLType function
XMLType instance
(table, cloumn, view)
transformed XMLType
(HTML, XML, ...)
XMLTransform() Examples
6-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<element name="comment" type="string"/>
<complexType name="PurchaseOrderType">
<sequence>
<element name="shipTo" type="ipo:Address"/>
<element name="billTo" type="ipo:Address"/>
<element ref="ipo:comment" minOccurs="0"/>
<element name="items" type="ipo:Items"/>
</sequence>
<attribute name="orderDate" type="date"/>
</complexType>
<complexType name="Items">
<sequence>
<element name="item" minOccurs="0" maxOccurs="unbounded">
<complexType>
<sequence>
<element name="productName" type="string"/>
<element name="quantity">
<simpleType>
<restriction base="positiveInteger">
<maxExclusive value="100"/>
</restriction>
</simpleType>
</element>
<element name="USPrice" type="decimal"/>
<element ref="ipo:comment" minOccurs="0"/>
<element name="shipDate" type="date" minOccurs="0"/>
</sequence>
<attribute name="partNum" type="ipo:SKU" use="required"/>
</complexType>
</element>
</sequence>
</complexType>
<complexType name="Address">
<sequence>
<element name="name" type="string"/>
<element name="street" type="string"/>
<element name="city" type="string"/>
<element name="state" type="string"/>
<element name="country" type="string"/>
<element name="zip" type="string"/>
</sequence>
</complexType>
<simpleType name="SKU">
<restriction base="string">
<pattern value="{3}-[A-Z]{2}"/>
XMLTransform() Examples
Transforming and Validating XMLType Data 6-5
</restriction>
</simpleType>
</schema>,
TRUE, TRUE, FALSE);
end;
/
-- create table to hold XML instance documents
DROP TABLE po_tab;
CREATE TABLE po_tab (id number, xmlcol xmltype)
XMLTYPE COLUMN xmlcol
XMLSCHEMA "http://www.example.com/schemas/ipo.xsd"
ELEMENT "purchaseOrder";
INSERT INTO po_tab VALUES(1, xmltype(
<?xml version="1.0"?>
<ipo:purchaseOrder
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ipo="http://www.example.com/IPO"
xsi:schemaLocation="http://www.example.com/IPO
http://www.example.com/schemas/ipo.xsd"
orderDate="1999-12-01">
<shipTo xsi:type="ipo:Address">
<name>Helen Zoe</name>
<street>121 Broadway</street>
<city>Cardiff</city>
<state>Wales</state>
<country>UK</country>
<zip>CF2 1QJ</zip>
</shipTo>
<billTo xsi:type="ipo:Address">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>CA</state>
<country>US</country>
<zip>95819</zip>
</billTo>
<items>
<item partNum="833-AA">
<productName>Lapis necklace</productName>
<quantity>1</quantity>
<USPrice>99.95</USPrice>
<ipo:comment>Want this for the holidays!</ipo:comment>
<shipDate>1999-12-05</shipDate>
XMLTransform() Examples
6-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</item>
</items>
</ipo:purchaseOrder>));
The following examples illustrate how to use XMLTransform() to transform XML
data stored as XMLType to HTML, XML, or other languages.
Example 61 Transforming an XMLType Instance Using XMLTransform() and
DBUriType to Get the XSL Stylesheet
DROP TABLE stylesheet_tab;
CREATE TABLE stylesheet_tab(id NUMBER, stylesheet xmltype);
INSERT INTO stylesheet_tab VALUES (1, xmltype(
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*">
<td>
<xsl:choose>
<xsl:when test="count(child::*) > 1">
<xsl:call-template name="nested"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="name(.)"/>:<xsl:value-of select="text()"/>
</xsl:otherwise>
</xsl:choose>
</td>
</xsl:template>
<xsl:template match="*" name="nested" priority="-1" mode="nested2">
<b>
<!-- xsl:value-of select="count(child::*)"/ -->
<xsl:choose>
<xsl:when test="count(child::*) > 1">
<xsl:value-of select="name(.)"/>:<xsl:apply-templates mode="nested2"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="name(.)"/>:<xsl:value-of select="text()"/>
</xsl:otherwise>
</xsl:choose>
</b>
</xsl:template>
</xsl:stylesheet>
));
SELECT XMLTransform(x.xmlcol,
dburiType(/SCOTT/STYLESHEET_TAB/ROW[ID =
XMLTransform() Examples
Transforming and Validating XMLType Data 6-7
1]/STYLESHEET/text()).getXML()).getStringVal()
AS result
FROM po_tab x;
-- The preceding statement produces the following output:
-- RESULT
-- ---------------------------------------------------------
-- <td>
-- <b>ipo:purchaseOrder:
-- <b>shipTo:
-- <b>name:Helen Zoe</b>
-- <b>street:100 Broadway</b>
-- <b>city:Cardiff</b>
-- <b>state:Wales</b>
-- <b>country:UK</b>
-- <b>zip:CF2 1QJ</b>
-- </b>
-- <b>billTo:
-- <b>name:Robert Smith</b>
-- <b>street:8 Oak Avenue</b>
-- <b>city:Old Town</b>
-- <b>state:CA</b>
-- <b>country:US</b>
-- <b>zip:95819</b>
-- </b>
-- <b>items:</b>
-- </b>
-- </td>
Example 62 Transforming an XMLType Instance Using XMLTransform() and a
Subquery SELECT to Retrieve the XSL Stylesheet
This example illustrates the use of a stored stylesheet to transform XMLType instances.
Unlike the previous example, this example uses a scalar subquery to retrieve the stored
stylesheet:
SELECT XMLTransform(x.xmlcol,
(select stylesheet from stylesheet_tab where id = 1)).getStringVal()
AS result
FROM po_tab x;
Example 63 Transforming XMLType Instances Using Transient Stylesheets and
XMLTransform()
This example describes how you can transform XMLType instances using a transient
Validating XMLType Instances
6-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
stylesheet:
SELECT x.xmlcol.transform(xmltype(
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*">
<td>
<xsl:choose>
<xsl:when test="count(child::*) > 1">
<xsl:call-template name="nested"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="name(.)"/>:<xsl:value-of select="text()"/>
</xsl:otherwise>
</xsl:choose>
</td>
</xsl:template>
<xsl:template match="*" name="nested" priority="-1" mode="nested2">
<b>
<!-- xsl:value-of select="count(child::*)"/ -->
<xsl:choose>
<xsl:when test="count(child::*) > 1">
<xsl:value-of select="name(.)"/>:<xsl:apply-templates mode="nested2"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="name(.)"/>:<xsl:value-of select="text()"/>
</xsl:otherwise>
</xsl:choose>
</b>
</xsl:template>
</xsl:stylesheet>
)).getStringVal()
FROM po_tab x;
Validating XMLType Instances
Often, besides knowing that a particular XML document is well-formed, it is
necessary to knowif a particular document conforms to a specic XML schema, that
is, is VALID with respect to a specic XML schema.
By default, Oracle9i does check to make sure that XMLType instances are
well-formed. In addition, for schema-based XMLType instances, Oracle9i performs
few basic validation checks. Since full XML schema validation (as specied by the
Validating XMLType Instances
Transforming and Validating XMLType Data 6-9
W3C) is an expensive operation, when XMLType instances are constructed, stored,
or retrieved, they are not also fully validated.
To validate and manipulate the validated status of XML documents, the
following functions and SQL operator are provided:
XMLIsValid()
XMLIsValid() is an SQL Operator. It checks if the input instance conforms to a
specied XML schema. It does not change the validation status of the XML instance.
If an XML schema URL is not specied and the XML document is schema-based,
the conformance is checked against the XMLType instances own schema. If any of
the arguments are specied to be NULL, then the result is NULL. If validation fails,
0 is returned and no errors are reported explaining why the validation has failed.
Syntax
XMLIsValid ( XMLType_inst [, schemaurl [, elem]])
Parameters:
I XMLType_inst - The XMLType instance to be validated against the specied
XML Schema.
I schurl - The URL of the XML Schema against which to check conformance.
I elem - Element of a specied schema, against which to validate. This is useful
when we have a XML Schema which denes more than one top level element,
and we want to check conformance against a specic one of these elements.
schemaValidate
schemaValidate is a member procedure. It validates the XML instance against its
XML schema if it has not already been done. For non-schema-based documents an
error is raised. If validation fails an error is raised otherwise, the documents status
is changed to VALIDATED.
Syntax
MEMBER PROCEDURE schemaValidate
isSchemaValidated()
isSchemaValidated() is a member function. It returns the validation status of
the XMLType instance and tells if a schema-based instance has been actually
validated against its schema.It returns 1 if the instance has been validated against
the schema, 0 otherwise.
Validating XML Data Stored as XMLType: Examples
6-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Syntax
MEMBER FUNCTION isSchemaValidated return NUMBER deterministic
setSchemaValidated()
setSchemaValidated() is a member function. It sets the VALIDATION state of the
input XML instance.
Syntax
MEMBER PROCEDURE setSchemaValidated(flag IN BINARY_INTEGER := 1)
Parameters:
flag, 0 - NOT VALIDATED; 1 - VALIDATED; The default value for this parameter
is 1.
isSchemaValid()
isSchemaValid() is a member function. It checks if the input instance conforms
to a specied XML schema. It does not change the validation status of the XML
instance. If an XML Schema URL is not specied and the XML document is
schema-based, the conformance is checked against the XMLType instances own
schema. If the validation fails, exceptions are thrown with the reason why the
validation has failed.
Syntax
member function isSchemaValid(schurl IN VARCHAR2 := NULL, elem IN VARCHAR2 :=
NULL) return NUMBER deterministic
Parameters:
schurl - The URL of the XML Schema against which to check conformance.
elem - Element of a specied schema, against which to validate. This is useful when
we have a XML Schema which denes more than one top level element, and we
want to check conformance against a specic one of these elements.
Validating XML Data Stored as XMLType: Examples
The following examples illustrate how to use isSchemaValid(),
setSchemaValidated(), and isSchemaValidated() to validate XML data
being stored as XMLType in Oracle XML DB.
Validating XML Data Stored as XMLType: Examples
Transforming and Validating XMLType Data 6-11
Example 64 Using isSchemaValid()
SELECT x.xmlcol.isSchemaValid(http://www.example.com/schemas/ipo.xsd,
purchaseOrder)
FROM po_tab x;
Example 65 Validating XML Using isSchemaValid()
The following PL/SQL example validates an XML instance against XML schema
PO.xsd:
declare
xmldoc xmltype;
begin
-- populate xmldoc (for example, by fetching from table)
-- validate against XML schema
xmldoc.isSchemaValid('http://www.oracle.com/PO.xsd');
if xmldoc.isSchemaValid = 1 then --
else --
end if;
end;
Example 66 Using schemaValidate() Within Triggers
The schemaValidate() method of XMLType can be used within INSERT and
UPDATE TRIGGERS to ensure that all instances stored in the table are validated
against the XML schema:
DROP TABLE po_tab;
CREATE TABLE po_tab OF xmltype
XMLSchema "http://www.example.com/schemas/ipo.xsd" element "purchaseOrder";
CREATE TRIGGER emp_trig BEFORE INSERT OR UPDATE ON po_tab FOR EACH ROW
DECLARE
newxml xmltype;
BEGIn
newxml := :new.sys_nc_rowinfo$;
xmltype.schemavalidate(newxml);
END;
/
Example 67 Using XMLIsSchemaValid() Within CHECK Constraints
This example uses XMLIsValid() to:
I Verify that the XMLType instance conforms to the specied XML schema
Validating XML Data Stored as XMLType: Examples
6-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Ensure that the incoming XML documents are valid by using CHECK
constraints
DROP TABLE po_tab;
CREATE TABLE po_tab OF XMLTYPe
(CHECK (XMLIsValid(sys_nc_rowinfo$) = 1))
XMLSchema "http://www.example.com/schemas/ipo.xsd" element "purchaseOrder";
Note: The validation functions and operators described in the
preceding section, facilitate validation checking. Of these,
isSchemaValid() is the only one that throws errors that include
why the validation has failed.
Searching XML Data with Oracle Text 7-1
7
Searching XML Data with Oracle Text
This chapter explains the use of Oracle Text functionality in indexing and querying
XML data. It contains the following sections:
I Searching XML Data with Oracle Text
I Introducing Oracle Text
I Assumptions Made in This Chapters Examples
I Oracle Text Users and Roles
I Querying with the CONTAINS Operator
I Using the WITHIN Operator to Narrow Query Down to Document Sections
I Introducing SECTION_GROUPS
I INPATH or HASPATH Operators Search Using XPath-Like Expressions
I Building a Query Application with Oracle Text
I Step 1. Create a Section Group Preference
I Step 2. Set the Preferences Attributes
I Step 3. Create an Index Using the Section Preference Created in Step 2
I Step 4. Create Your Query Syntax
I Presenting the Results of Your Query
I XMLType Indexing
I Using Oracle Text with Oracle XML DB
I Full-Text Search Functions in XPath Using ora:contains
I Oracle XML DB: Creating a Policy for ora:contains()
7-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Oracle XML DB: Using CTXXPATH Indexes for existsNode()
I Using Oracle Text: Advanced Techniques
I Case Study: Searching XML-Based Conference Proceedings
I Frequently Asked Questions About Oracle Text
Note: In Oracle9i, you can use the WITHIN or INPATH operators.
INPATH was introduced in Oracle9i Release 1 (9.0.1) to handle
XPath searching in XML documents. Everything you can do with
the WITHIN operator, you can also do using INPATH. INPATH is the
recommended syntax in Oracle9i Release 1 (9.0.1) and higher when
searching XML data.
Introducing Oracle Text
Searching XML Data with Oracle Text 7-3
Searching XML Data with Oracle Text
This chapter describes the following aspects of Oracle Text:
I How to create a section group and index your XML document(s)
I Howto build an XML query application with Oracle Text, to search and retrieve
data from your XML document(s)
I Using Oracle Text to search XMLType data
Introducing Oracle Text
Oracle Text (aka interMedia Text) can be used to search XML documents. It extends
Oracle9i by indexing any text or document stored in Oracle. It can also search
documents in the le system and URLs.
Oracle Text enables the following:
I Content-based queries, such as, nding text and documents which contain
particular words, using familiar, standard SQL.
I File-based text applications to use Oracle9i to manage text and documents in an
integrated fashion with traditional relational information.
I Concept searching of English language documents.
I Theme analysis of English language documents using the theme/gist package.
I Highlighting hit words. With Oracle Text, you can render a document in different
ways. For example, you can present documents with query terms highlighted,
either the words of a word query or the themes of an ABOUT query in
English. Use the CTX_DOC.MARKUP or HIGHLIGHT procedures for this.
I Highlighting hit words. With Oracle Text, you can render a document in
different ways. For example, you can present documents with query terms
highlighted, either the "words" of a word query or the "themes" of an ABOUT
query in English. Also, you can present XML documents with the
INPATH/HASPATH query element(s) highlighted. Use CTX_DOC.MARKUP or
HIGHLIGHT procedures for this.
Note: Oracle Text is a strictly server-based implementation.
See Also: http://otn.oracle.com/products/text
Assumptions Made in This Chapters Examples
7-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I With Oracle Text you can use PL/SQL packages for document presentation and
thesaurus maintenance.
You can query XML data stored in the database directly, without using Oracle Text.
However, Oracle Text is useful for boosting query performance.
Accessing Oracle Text
Oracle Text is a standard feature that comes with every Oracle9i Standard,
Enterprise, and Personal edition license. It needs to be selected during installation.
No special installation instructions are required.
Oracle Text is essentially a set of schema objects owned by CTXSYS. These objects
are linked to the Oracle kernel. The schema objects are present when you perform
an Oracle9i installation.
Oracle Text Now Supports XMLType
You can now perform Oracle Text searches on tables containing XMLType columns.
Further Oracle Text Examples
You can nd more examples for Oracle Text and for creating section group indexes
at the following site: http://otn.oracle.com/products/text
Assumptions Made in This Chapters Examples
XML text is aVARCHAR2 or CLOB type in an Oracle9i database table with
character semantics. Oracle Text can also deal with documents in a le system or in
URLs, but we are not considering these document types in this chapter.
To simplify the examples included in this chapter they use a subset of the Oracle
Text options and make the following assumptions:
I All XML data here is represented using US-ASCII, a 7 bit character set.
I Issues about whether a character such as "*" is treated as white space or as part
of a word are not included.
See Also :
I Oracle Text Reference
I Oracle Text Application Developers Guide
I http://otn.oracle.com/products/text
Oracle Text Users and Roles
Searching XML Data with Oracle Text 7-5
I Storage characteristics of the Oracle schema object that implement the Oracle
Text index are not considered.
I They focus on the SECTION GROUP parameter in the CREATE INDEX or
ALTER INDEX statement. Other parameter types available for CREATE INDEX
and ALTER INDEX, are DATASTORE, FILTER, LEXER, STOPLIST, and
WORDLIST.
Here is an example of using SECTION GROUP in CREATE INDEX:
CREATE INDEX my_index
ON my_table ( my_column )
INDEXTYPE IS ctxsys.context
PARAMETERS ( 'SECTION GROUP my_section_group' ) ;
I Specically, the examples focus on using AUTO_SECTION_GROUP and
XML_SECTION_GROUP, and PATH_SECTION_GROUP.
I Tagged or marked up data. In this chapter, the examples focus on how to
handle XML data. Oracle Text handles many other kinds of data besides XML
data.
Oracle Text Users and Roles
With Oracle Text you can use the following users/roles:
I user CTXSYS to administer users
I role CTXAPP to create and delete Oracle Text preferences and use Oracle Text
PL/SQL packages
User CTXSYS
User CTXSYS is created at install time. Administer Oracle Text users as this user.
User CTXSYS has the following privileges:
I Modify system-dened preferences
I Drop and modify other user preferences
See Also:
I Oracle Text Application Developers Guide
I Oracle Text Reference, for more information on these parameter
types.
Querying with the CONTAINS Operator
7-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Call procedures in the CTX_ADM PL/SQL package to start servers and set
system-parameters
I Start a ctxsrv server
I Query all system-dened views
I Perform all the tasks of a user with the CTXAPP role
Role CTXAPP
Any user can create an Oracle Text index and issue a Text query. For additional
tasks, use the CTXAPP role. This is a system-dened role that enables you to
perform the following tasks:
I Create and delete Oracle Text preferences
I Use Oracle Text PL/SQL packages, such as the CTX_DDL package
Querying with the CONTAINS Operator
Oracle Texts main purpose is to provide an implementation for the CONTAINS
operator. The CONTAINS operator can be used in the WHERE clause of a SELECT
statement to specify the query expression for a Text query.
CONTAINS Syntax
Here is the CONTAINS syntax:
...WHERE CONTAINS([schema.]column,text_query VARCHAR2,[label NUMBER])
where:
Table 71 CONTAINS Operator: Syntax Description
Syntax Description
[schema.] column Species the text column to be searched on. This column must
have a Text index associated with it.
text_query Species the query expression that denes your search in
column.
label Optionally species the label that identies the score generated
by the CONTAINS operator.
Querying with the CONTAINS Operator
Searching XML Data with Oracle Text 7-7
For each row selected, CONTAINS returns a number between 0 and 100 that
indicates how relevant the document row is to the query. The number 0 means that
Oracle found no matches in the row. You can obtain this score with the SCORE
operator.
Example 71 Using a Simple SELECT Statement with CONTAINS
The following example illustrates how the CONTAINS operator is used in a SELECT
statement:
SELECT id FROM my_table
WHERE
CONTAINS (my_column, receipts) > 0
Thereceipts parameter of the CONTAINS operator is called the Text Query
Expression.
Example 72 Using the Score Operator with a Label to Obtain the Relevance
The following example searches for all documents in the text column that contain
the word Oracle. The score for each rowis selected with the SCORE operator using a
label of 1:
SELECT SCORE(1), title from newsindex
WHERE CONTAINS(text, 'oracle', 1) > 0 ORDER BY SCORE(1) DESC;
The CONTAINS operator must always be followed by the > 0 syntax. This species
that the score value calculated by the CONTAINS operator must be greater than zero
for the row selected.
When the SCORE operator is called, such as in a SELECT clause, the operator must
reference the label value as shown in the example.
Note: You must use the SCORE operator with a label to obtain
this number.
Note: The SQL statement with the CONTAINS operator requires an
Oracle Text index in order to run.
Using the WITHIN Operator to Narrow Query Down to Document Sections
7-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Using the WITHIN Operator to Narrow Query Down to Document
Sections
When documents have internal structure such as in HTML and XML, you can
dene document sections using embedded tags before you index. This enables you
to query within the sections using the WITHIN operator.
Introducing SECTION_GROUPS
You can query within attribute sections when you index with either
XML_SECTION_GROUP, AUTO_SECTION_GROUP, or PATH_SECTION_GROUP your
section group type. Consider the following XML document:
<book title="Tale of Two Cities">It was the best of times.</book>
XML_SECTION_GROUP
If you use XML_SECTION_GROUP, you can specify any of the following sections:
I Zone sections
I Field sections
I Attribute section
I Special sections
This chapter only focuses on Zone, Field, and Attribute sections. For more
information on Special sections see Oracle Text Reference and Oracle Text Application
Developers Guide.
Zone Sections: CTX_DLL.ADD_ZONE_SECTION Procedure
The syntax for this is:
CTX_DDL.ADD_ZONE_SECTION(
group_name in varchar2,
section_name in varchar2,
tag in varchar2);
Note: This is only true for XML_SECTION_GROUP, but not true for
AUTO_ or PATH_SECTION_GROUP.
Introducing SECTION_GROUPS
Searching XML Data with Oracle Text 7-9
To dene a chapter as a Zone section, create an XML_SECTION_GROUP and dene
the Zone section as follows:
EXEC ctx_ddl_create_section_group('myxmlgroup', 'XML_SECTION_GROUP');
EXEC ctx_ddl.add_zone_section('myxmlgroup', 'chapter', 'chapter');
When you dene Zone section as such and index the document set, you can query
the XML chapter Zone section as follows:
'Cities within chapter'
Field Sections: CTX_DLL.ADD_FIELD_SECTION Procedure
The syntax for this is:
CTX_DDL.ADD_FIELD_SECTION(
group_name in varchar2,
section_name in varchar2,
tag in varchar2);
To dene a abstract as a Field section, create an XML_SECTION_GROUP and
dene the Field section as follows:
EXEC ctx_ddl_create_section_group('myxmlgroup', 'XML_SECTION_GROUP');
EXEC ctx_ddl.add_eld_section('myxmlgroup', 'abstract', 'abstract');
When you dene Field section as such and index the document set, you can query
the XML abstract Field section as follows:
'Cities within abstract'
Attribute Section: CTX_DLL.ADD_ATTR_SECTION Procedure
The syntax for this is:
CTX_DDL.ADD_ATTR_SECTION(
group_name in varchar2,
section_name in varchar2,
tag in varchar2);
To dene the booktitle attribute as an Attribute section, create an
XML_SECTION_GROUP and dene the Attribute section as follows:
EXEC ctx_ddl_create_section_group('myxmlgroup', 'XML_SECTION_GROUP');
EXEC ctx_ddl.add_attr_section('myxmlgroup', 'booktitle', 'book@title');
Introducing SECTION_GROUPS
7-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
When you dene the Attribute section as such and index the document set, you can
query the XML booktitle attribute text as follows:
'Cities within booktitle'
Constraints for Querying Attribute or Field Sections
The following constraints apply to querying within Attribute or Field sections:
I Regular queries on attribute text will not work unless qualied in a WITHIN
clause. Using the following XML document:
<book title="Tale of Two Cities">It was the best of times.</book>
querying on Tale will not work unless qualied with WITHIN title@book.
I You cannot use Attribute or Field sections in a nested WITHIN query.
I Phrases ignore attribute text. For example, if the original document looked like:
....Now is the time for all good <word type="noun"> men </word> to come to
the aid......
The search would result in a regular querys, good men, and ignore the
intervening attribute text.
AUTO_ SECTION_GROUP/ PATH_SECTION_GROUP for INPATH and HASPATH
When you use the AUTO_SECTION_GROUP or PATH_SECTION_GROUP to index
XML documents, Oracle9i automatically creates sections.
To search on Tale within the Attribute section booktitle, include the following
WITHIN clause in your SELECT statement:
I If you are using XML_SECTION_GROUP:
... WHERE CONTAINS ('Tale INPATH booktitle')>0;
I If you are using PATH_SECTION_GROUP
... WHERE CONTAINS (Tale INPATH title@book)>0;
Dynamically Adding Sections or Stop Section Using ALTER INDEX
The syntax for ALTER INDEX is:
See Also: "Distinguishing Tags Across DocTypes" on page 7-51.
Introducing SECTION_GROUPS
Searching XML Data with Oracle Text 7-11
ALTER INDEX [schema.]index REBUILD [ONLINE] [PARAMETERS (paramstring)];
where
paramstring = 'replace [datastore datastore_pref]
[filter filter_pref]
[lexer lexer_pref]
[wordlist wordlist_pref]
[storage storage_pref]
[stoplist stoplist]
[section group section_group]
[memory memsize]
| ...
| add zone section section_name tag tag
| add field section section_name tag tag [(VISIBLE | INVISIBLE)]
| add attr section section_name tag tag@attr
| add stop section tag
The added section applies only to documents indexed after this operation. Thus
for the change to take effect, you must manually re-index any existing
documents that contain the tag. The index is not rebuilt by this statement.
WITHIN Syntax for Section Querying
Here is the WITHIN syntax for querying sections:
...WHERE CONTAINS(text,XML WITHIN title) >0;...
This searches for expression text within a section. If you are using
XML_SECTION_GROUP the following restrictions apply to the pre-dened zone,
eld, or attribute section:
I If section is a zone, expression can contain one or more WITHIN operators
(nested WITHIN) whose section is a zone or special section.
I If section is a eld or attribute section, expression cannot contain another
WITHIN operator.
You can combine and nest WITHIN clauses. For ner grained searches of XML
sections, you can use WITHIN clauses inside CONTAINS select statements.
WITHIN Operator Limitations
The WITHIN operator has the following limitations:
INPATH or HASPATH Operators Search Using XPath-Like Expressions
7-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I You cannot embed the WITHIN clause in a phrase. For example, you cannot
write: term1 WITHIN section term2
I You cannot combine WITHIN with expansion operators, such as $ ! and *.
I Since WITHIN is a reserved word, you must escape the word with braces to
search on it.
INPATH or HASPATH Operators Search Using XPath-Like Expressions
Path Indexing and Path Querying with Oracle Text
In Oracle9i Oracle Text introduced a new section type and new query operators
which support an XPath-like query language. Indexes of type context with XML
path searching are able to perform very complex section searches on XML
documents. Here are the basic concepts of path indexing and path querying.
Path Indexing
Section searching is enabled by dening section groups. To use XML path searching,
the Oracle Text index must be created with the new section group,
PATH_SECTION_GROUP as follows:
begin
ctx_ddl.create_section_group('mypathgroup','PATH_SECTION_GROUP');
end;
To create the Oracle Text index use this command:
create index order_idx on library_catalog(text)
indextype is ctxsys.context
parameters ('SECTION GROUP mypathgroup');
Path Querying
The Oracle Text path query language is based on W3C XPath. For Oracle9i Release 1
(9.0.1) and higher, you can use the INPATH and HASPATH operators to express path
queries.
See Also: Oracle Text Reference
INPATH or HASPATH Operators Search Using XPath-Like Expressions
Searching XML Data with Oracle Text 7-13
Using INPATH Operator for Path Searching in XML Documents
You can use INPATH operator to perform path searching in XML documents.
Table 72 summarizes the ways you can use the INPATH operator for path
searching.
Table 72 Path Searching XML Documents Using the INPATH Operator
Path Search Feature Syntax Description
Simple Tag Searching virginia INPATH (//STATE) Finds all documents where the word virginia
appears between <STATE> and </STATE>. The
STATE element can appear at any level of the
document structure.
Case-sensitivity virginia INPATH (STATE)
virginia INPATH (State)
Tags and attribute names in path searching are
case-sensitive. virginia INPATH STATE -- nds
<STATE>virginia</STATE> but NOT
<State>virginia</State>. To nd the latter
you must do virginia INPATH State.
Top-Level Tag
Searching
virginia INPATH (Legal)
virginia INPATH (/Legal)
For example, the following
query nds Quijote where it
occurs between <order> and
</order>:
select id from library_catalog where
contains(text,'Quijote INPATH(order)') >
0;
Here <order> must be the top
level tag.
Finds all documents where virginia appears in a
Legal element which is the top-level tag.'Legal'
MUST be the top-level tag of the document.virginia'
may appear anywhere in this tag regardless of other
intervening tags. For example:
<?xml version=1.0 standalone=yes?>
<!-- <?xml-stylesheet type=text/xsl"
href="./xsl/vacourtling(html).xsl"?> -->
<Legal>
<CourtFiling>
<Filing ID="f001" FilingType="Civil">
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState>VIRGINIA</AddressState>
</Address> ... </Legal>
INPATH or HASPATH Operators Search Using XPath-Like Expressions
7-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Any Level Tag
Searching
virginia INPATH (//Address)
For example, a double slash
indicates "any number of levels"
down. The following query nds
Quijote inside a <title> tag that
occurs at the top level or any
lower level:
select id from library_catalog
where contains(text,'Quijote
INPATH(//title)') > 0;
'Virginia' can appear anywhere within an 'Address'
tag, which may appear within any other tags. for
example:
<?xml version="1.0" standalone="yes"?>
<!-- <?xml-stylesheet type="text/xsl"
href="./xsl/vacourtling(html).xsl"?> -->
<Legal>
<CourtFiling>
<Filing ID="f001" FilingType="Civil">
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState> VIRGINIA </AddressState>...
</Legal>
Direct Parentage Path
Searching
virginia INPATH
(//CourtInformation/Location)
for example:
select id from library_catalog where
contains(text,'virginia
INPATH(order/item)') > 0;
Finds all documents where virginia appears in a
Location element which is a direct child of a
CourtInformation element. For example:
<?xml version="1.0" standalone="yes"?>
<!-- <?xml-stylesheet type="text/xsl"
href="./xsl/vacourtling(html).xsl"?> -->
<Legal>
<CourtFiling>
<Filing ID="f001" FilingType="Civil">
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState> VIRGINIA </AddressState>
</Address>... </CourtInformation>
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
INPATH or HASPATH Operators Search Using XPath-Like Expressions
Searching XML Data with Oracle Text 7-15
Single-Level Wildcard
Searching
virginia INPATH(A/*/B)
'virginia INPATH
(//CaseCaption/*/Location)'
Finds all documents where virginia appears in a B
element which is a grandchild of an A element. For
instance, <A><D><B>virginia</B></D></A>.
The intermediate element does not need to be an
indexed XML tag. For example:
<?xml version="1.0" standalone="yes"?>
<!-- <?xml-stylesheet type="text/xsl"
href="./xsl/vacourtling(html).xsl"?> -->
<Legal>
<CourtFiling>
<Filing ID="f001" FilingType="Civil">
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState>VIRGINIA</AddressState>...
</Legal>
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
INPATH or HASPATH Operators Search Using XPath-Like Expressions
7-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Multi-level Wildcard
Searching
'virginia INPATH
(Legal/*/Filing/*/*/CourtInformation)'
'Legal' must be a top-level tag, and there must be
exactly one tag-level between 'Legal' and 'Filing',
and two between 'Filing' and 'CourtInformation'.
'Virginia' may then appear anywhere within
'CourtInformation'. For example:
<?xml version="1.0" standalone="yes"?>
<!-- <?xml-stylesheet type="text/xsl"
href="./xsl/vacourtling(html).xsl"?> -->
<Legal>
<CourtFiling>
<Filing ID="f001" FilingType="Civil">
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState>VIRGINIA</AddressState>
</Address>
</Location>
<CourtName>
IN THE CIRCUIT COURT OF LOUDOUN COUNTY
</CourtName>
</CourtInformation>....
Descendant Searching virginia INPATH(A//B) Finds all documents where virginia appears in a B
element which is some descendant (any level) of an
A element.
Attribute Searching virginia INPATH(A/@B) Finds all documents where virginia appears in the
B attribute of an A element. You can search within
an attribute value using the syntax
<tag>/@<attribute>:
select id from library_catalog where contains(text,'dvd
INPATH(//item/@type)') > 0; AND and OR
You can use boolean AND and OR to combine
existence or equality predicates in a test.
select id from library_catalog where contains(text,'Levy or
Cervantes INPATH(//title)') >0;
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
INPATH or HASPATH Operators Search Using XPath-Like Expressions
Searching XML Data with Oracle Text 7-17
Descendant/Attribute
Existence Testing
virginia INPATH (A[B])
You can search for documents
using the any-level tag
searching:
select id from library_catalog where
contains (text,'Quijote
INPATH(/order/title)') > 0;
You can also use the "*" as a
single level wildcard. The *
matches exactly one level.:
select id from library_catalog where
contains (text,'Cervantes
INPATH(/order/*/author)') > 0;
Finds all documents where virginia appears in an
A element which has a B element as a direct child.
I virginia INPATH A[.//B] -- Finds all
documents where virginia appears in an A
element which has a B element as a descendant
(any level).
I virginia INPATH A[@B] -- Finds all documents
where virginia appears in an A element
which has a B attribute
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
INPATH or HASPATH Operators Search Using XPath-Like Expressions
7-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Attribute Value
Testing
Within Equality
virginia INPATH A[@B = foo]
That means that:
virginia INPATH(A[@B = "pot of
gold]), would, with the default
lexer and stoplist, match any of
the following:
<A B="POT OF GOLD">virginia</A>
By default, lexing is
case-independent, so pot
matches POT, <A B="POT
BLACK GOLD>virginia</A>
By default, of is a stopword,
and, in a query, would match
any word in that position, <A
B=" Pot OF Gold
>virginia</A>
Finds all documents where virginia appears in an
A element which has a B attribute whose value is
foo.
I Only equality is supported as a test. Range
operators and functions are not supported.
I The left-hand-side of the equality MUST be an
attribute or tag. Literals here are not allowed.
I The right-hand-side must be a literal. Tags and
attributes here are not allowed.
Within equality (See "Using INPATH Operator for
Path Searching in XML Documents" on page 7-13) is
used to evaluate the test.
Whitespace is mainly ignored in text indexing.
Again, lexing is case-independent:
<A B=pot_of_gold>virginia</A>
Underscore is a non-alphabetic character, and is not
a join character by default. As a result, it is treated
more or less as whitespace and breaks up that string
into three words.
Example:
select id from library_catalog where contains(text,'(Bob the
Builder) INPATH(//item[@type="dvd"])') > 0;
The following will not return rows:
select id from library_catalog where contains(text,'(Bob the
Builder) INPATH(//item[@type="book"])') > 0;
Numeric Equality virginia INPATH (A[@B = 5]) Numeric literals are allowed. But they are treated as
text. The within equality is used to evaluate. This
means that the query does NOT match. That is, <A
B=5.0>virginia</A> does not match A[@B=5]
where "5.0", a decimal is not considered the same as
5, an integer.
Conjunctive Testing virginia INPATH (A[B AND C])
virginia INPATH (A[B AND @C =
foo])...
Predicates can be conjunctively combined.
Combining Path and
Node Tests
virginia INPATH (A[@B = foo]/C/D)
virginia INPATH(A//B[@C]/D[E])...
Node tests can be applied to any node in the path.
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
INPATH or HASPATH Operators Search Using XPath-Like Expressions
Searching XML Data with Oracle Text 7-19
Using HASPATH Operator for Path Searching in XML Documents
Use the HASPATH operator to nd all XML documents that contain a specied
section path. HASPATH is used when you want to test for path existence. It is also
very useful for section equality testing. To nd all XML documents where an order
has an item within it:
select id from library_catalog
where contains(text,'HASPATH(order/item)') > 0;
will return all documents where the top-level tag is a order element which has a
item element as a direct child.
In Oracle9i, Oracle Text introduces a new section type and new query operators
which support an XPath-like query language. Indexes of type context with XML
path searching are able to perform very complex section searches on XML
documents. Here are more examples of path querying using INPATH and HASPATH.
Assuming the following XML document:
<?xml version="1.0"?>
<order>
<item type="book">
<title>Crypto</title>
<author>Levi</author>
</item>
<item type="dvd">
<title> Bob the Builder</title>
<author>Auerbach</author>
</item>
<item type="book">
<title>Don Quijote</title>
<author>Cervantes</author>
</item>
</order>
In general, use INPATH and HASPATH operators only when your index has been
created with PATH_SECTION_GROUP. Use of PATH_SECTION_GROUP enables path
searching. Path searching extends the syntax of the WITHIN operator so that the
section name operand (right-hand-side) is a path instead of a section name.
INPATH or HASPATH Operators Search Using XPath-Like Expressions
7-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Using HASPATH Operator for Path Existence Searching
Only use the HASPATH operator when your index has been created with the
PATH_SECTION_GROUP. The syntax for the HASPATH operator is:
I WHERE CONTAI NS(column, HASPATH(path)...): Here HASPATH searches an
XML document set and returns a score of 100 for all documents where path
exists. Parent and child paths are separated with the / character, for example,
A/B/C. For example, the query:
...WHERE CONTAINS (col,HASPATH(A/B/C))>0;
nds and returns a score of 100 for the document:
<A><B><C>Virginia</C></B></A>
without having to reference Virginia at all.
I WHERE CONTAI NS(column, HASPATH(A=value)...): Here the HASPATH
clause searches an XML document set and returns a score of 100 for all
documents that have element A with content value and only that value.
HASPATH is used to test equality. This is the "Section Equality Testing" feature of
the HASPATH operator. The query:
...WHERE CONTAINS virginia INPATH A
nds <A>virginia</A>, but it also nds <A>virginia state</A>. To limit the
query to the term virginia and nothing else, you can use a section equality test
with the HASPATH operator. For example:
... WHERE CONTAINS (col,HASPATH(A="virginia")
nds and returns a score of 100 only for the rst document, and not the second.
Tag Value Equality Testing
You can do tag value equality test with HASPATH:
select id from library_catalog
where CONTAINS(text,'HASPATH (//author="Auerbach")') >0;
Note: The HASPATH operator functions in a similar fashion to the
existsNode() in XMLType.
Step 1. Create a Section Group Preference
Searching XML Data with Oracle Text 7-21
Building a Query Application with Oracle Text
To build a Oracle Text query application carry out the following steps:
1. Create a section preference group. Before you create a section group and
Oracle text index you must rst determine the role you will need and grant the
appropriate privilege. See "Oracle Text Users and Roles" on page 7-5, and grant
the appropriate privilege.
After creating and preparing your data, you are ready to perform the next step.
See "Step 1. Create a Section Group Preference" on page 7-21.
2. Add sections or stop_sections
3. Create an Oracle Text index based on the section group you created. Using the
section preference created, you then create an Oracle Text index. See Building a
Query Application with Oracle Text.
4. Build your query application using the CONTAINS operator. Now you can
nish building your query application. See "Building a Query Application with
Oracle Text".
What Role Do You Need?
First determine the role you need. See Oracle Text Reference and "Oracle Text Users
and Roles" on page 7-5, and grant the appropriate privilege as follows:
CONNECT system/manager
GRANT ctxapp to scott;
CONNECT scott/tiger
Step 1. Create a Section Group Preference
The rst thing you must do is create a preference. This section describes how to
create section preferences using PATH_SECTION_GROUP, XML_SECTION_GROUP,
and AUTO_SECTION_GROUP. Table 73 describes the groups and summarizes their
features.
Step 1. Create a Section Group Preference
7-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Table 73 Comparing Oracle Text Section Groups
Section Group Description
XML_SECTION_GROUP Use this group type for indexing XML documents and for dening sections in
XML documents.
AUTO_SECTION_GROUP Use this group type to automatically create a zone section for each
start-tag/end-tag pair in an XML document. The section names derived fromXML
tags are case-sensitive as in XML. Attribute sections are created automatically for
XML tags that have attributes. Attribute sections are named in the form
attribute@tag. Stop sections, empty tags, processing instructions, and comments
are not indexed. The following limitations apply to automatic section groups:
I You cannot add zone, eld or special sections to an automatic section group.
I Automatic sectioning does not index XML document types (root elements.)
However, you can dene stop-sections with document type.
I The length of the indexed tags including prex and namespace cannot exceed
64 characters. Tags longer than this are not indexed.
PATH_SECTION_GROUP Use this group type to index XML documents. Behaves like the
AUTO_SECTION_GROUP. With this section group you can do path searching with
the INPATH and HASPATH operators. Queries are case-sensitive for tag and
attribute names.
How is PATH_SECTION_GROUP Similar to AUTO_SECTION_GROUP?
Documents are assumed to be XML, Every tag and every attribute is indexed by
default, Stop sections can be added to prevent certain tags from being indexed,
Only stop sections can be added -- ZONE, FIELD, and SPECIAL sections cannot
be added, When indexing XML document collections, you do not need to
explicitly dene sections as Oracle automatically does this for you.
How Does PATH_SECTION_GROUP Differ From AUTO_SECTION_GROUP?
Path Searching is allowed at query time (see "Case Study: Searching XML-Based
Conference Proceedings" and "You can use INPATH operator to perform path
searching in XML documents. Table 72 summarizes the ways you can use the
INPATH operator for path searching." on page 7-13) with the newINPATH and
HASPATH operators, Tag and attribute names are case-sensitive in queries.
Note: If you are using the AUTO_SECTION_GROUP or
PATH_SECTION_GROUP to index an XML document collection, you
need not explicitly dene sections since the system does this for
you during indexing.
Step 1. Create a Section Group Preference
Searching XML Data with Oracle Text 7-23
Deciding Which Section Group to Use
How do you determine which section groups is best for your application? This
depends on your application. Table 74 lists some general guidelines to help you
decide which of the XML_, AUTO_, or PATH_ section groups to use when indexing
your XML documents, and why.
Creating a Section Preference with XML_SECTION_GROUP
The following command creates a section group called, xmlgroup, with the
XML_SECTION_GROUP group type:
EXEC ctx_ddl.create_section_group('myxmlgroup', 'XML_SECTION_GROUP');
Creating a Section Preference with AUTO_SECTION_GROUP
You can set up your indexing operation to automatically create sections from XML
documents using the section group AUTO_SECTION_GROUP. Here, Oracle creates
Table 74 Guidelines for Choosing XML_, AUTO_, or PATH_ Section Groups
Application Criteria XML_section_... AUTO_section_... PATH_section_...
You are using XPATH search features -- -- Yes
You knowthe layout and structure of
your XML documents, and you can
predene the sections on which users
are most likely to search.
Yes -- --
You do not know which tags users
are most likely to search.
-- Yes --
Query performance, in general Fastest Little slower than
XML_section_...
Little slower than
AUTO_section_...
Indexing performance, in general Fastest Little slower than
XML_section_...
Little slower than
AUTO_section_...
Index size Smallest Little larger than
XML_section_...
Little larger than
AUTO_section_...
Other features Mappings can be
dened so that tags in
one or different DTDs
can be mapped to one
section. Good for DTD
evolution and data
aggregation.
Simplest. No need to
dene mapping,
add_stop_section can
be used to ignore
some sections.
Designed for more
sophisticated XPATH-
like queries
Step 2. Set the Preferences Attributes
7-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
zone sections for XML tags. Attribute sections are created for those tags that have
attributes, and these attribute sections are named in the form tag@attribute.
The following command creates a section group called autogroup with the
AUTO_SECTION_GROUP group type. This section group automatically creates
sections from tags in XML documents.
EXEC ctx_ddl.create_section_group('autogroup', 'AUTO_SECTION_GROUP');
Creating a Section Preference with PATH_SECTION_GROUP
To enable path section searching, index your XML document with
PATH_SECTION_GROUP. For example:
EXEC ctx_ddl.create_section_group('xmlpathgroup', 'PATH_SECTION_GROUP');
Step 2. Set the Preferences Attributes
To set the preferences attributes for XML_SECTION_GROUP, use the following
procedures:
I Add_Zone_Section
I Add_Attr_Section
I Add_Field_Section
I Add_Special_Section
To set the preferences attributes for AUTO_SECTION_GROUP and
PATH_SECTION_GROUP, use the following procedures:
I Add_Stop_Section
There are corresponding CTX_DDL.DROP sections and CTX_DDL.REMOVE section
commands.
Note: You can add attribute sections only to XML section groups.
When you use AUTO_SECTION_GROUP, attribute sections are
created automatically. Attribute sections created automatically are
named in the form tag@attribute.
Step 2. Set the Preferences Attributes
Searching XML Data with Oracle Text 7-25
2.1 XML_SECTION_GROUP: Using CTX_DDL.add_zone_section
The syntax for CTX_DDL.add_zone_section follows:
CTX_DDL.Add_Zone_Section (
group_name => 'my_section_group' /* whatever you called it in the
preceding section */
section_name => 'author' /* what you want to call this section */
tag => 'my_tag' /* what represents it in XML */ );
where my_tag implies opening with <my_tag> and closing with </my_tag>.
add_zone_section Guidelines
add_zone_section guidelines are listed here:
I Call CTX_DDL.Add_Zone_Section for each tag in your XML document that
you need to search on.
2.2 XML_SECTION_GROUP: Using CTX_DDL.Add_Attr_Section
The syntax for CTX_DDL.ADD_ATTR_SECTION follows:
CTX_DDL.Add_Attr_Section ( /* call this as many times as you need to describe
the attribute sections */
group_name => 'my_section_group' /* whatever you called it in the
preceding section */
section_name => 'author' /* what you want to call this section */
tag => 'my_tag' /* what represents it in XML */ );
where my_tag implies opening with <my_tag> and closing with </my_tag>.
Add_Attr_Section Guidelines
Add_Attr_Section guidelines are listed here:
I Consider meta_data attribute author:
<meta_data author = John Smith title=How to get to Mars>
ADD_ATTR_SECTION adds an attribute section to an XML section group. This
procedure is useful for dening attributes in XML documents as sections. This
enables searching XML attribute text with the WITHIN operator.
The section_name:
I Is the name used for WITHIN queries on the attribute text.
Step 2. Set the Preferences Attributes
7-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Cannot contain the colon (:) or dot (.) characters.
I Must be unique within group_name.
I Is case-insensitive.
I Can be no more than 64 bytes.
The tag species the name of the attribute in tag@attr format. This is case-sensitive.
2.3 XML_SECTION_GROUP: Using CTX_DDL.Add_Field_Section
The syntax for CTX_DDL.Add_Field_Section follows:
CTX_DDL.Add_Field_Section (
group_name => 'my_section_group' /* whatever you called it in the preceding
section */
section_name => 'qq' /* what you want to call this section */
tag => 'my_tag' /* what represents it in XML */ );
visible => TRUE or FALSE );
Add_Field_Section Guidelines
Add_Field_Section guidelines are listed here:
I Searches using Field_Sections are faster than those using Zone_Section.
I Visible attribute: This is available in Add_Field_Section but not available in the
Add_Zone_section. If VISIBLE is set to TRUE then the text within the Field
section will be indexed as part of the enclosing document. For example:
<state> Virginia </state>
CTX_DDL.Add_Field_Section (
group_name => 'my_section_group'
section_name => 'state'
tag => 'state'
visible => TRUE or FALSE );
Note: In the ADD_ATTR_SECTION procedure, you can have many
tags all represented by the same section name at query time.
Explained in another way, the names used as the arguments of the
keyword WITHIN can be different from the actual XML tag names.
That is many tags can be mapped to the same name at query time.
This feature enhances query usability.
Step 2. Set the Preferences Attributes
Searching XML Data with Oracle Text 7-27
If visible is set to TRUE, then searching on Virginia without specifying the
state Field section produces a hit.
If visible is set to FALSE, then searching on Virginia without specifying the
state Field section does not produce a hit.
How Attr_Section Differs from Field_Section
Attribute section differs from Field section in the following ways:
I Attribute text is considered invisible, hence the following clause:
WHERE CONTAINS (..., ... jeeves,...)...
does NOT nd the document. This is similar to when Field sections have
visible set to FALSE. Unlike Field sections, however, Attribute section within
searches can distinguish between occurrences. Consider the document:
<comment author="jeeves">
I really like Oracle Text
</comment>
<comment author="bertram">
Me too
</comment>
the query:
WHERE CONTAINS (...,(cryil and bertram) WITHIN author, ...)...
will NOT nd the document, because "jeeves" and "bertram" do not occur
within the SAME attribute text.
I Attribute section names cannot overlap with zone or eld section names
although you can map more than one tag@attr to a single section name.
Attribute sections do not support default values. Given the document:
<!DOCTYPE foo [
<!ELEMENT foo (bar)>
<!ELEMENT bar (#PCDATA)>
<!ATTLIST bar
rev CDATA "8i">
]>
<foo>
<bar>whatever</bar>
</foo>
and attribute section:
Step 3. Create an Index Using the Section Preference Created in Step 2
7-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
ctx_ddl.add_attr_section('mysg','barrev','bar@rev');
the query:
8i within barrev does not hit the document, although in XML semantics, the
bar element has a default value for its rev attribute.
2.5 AUTO_SECTION_GROUP: Using CtX_DDL.Add_Stop_Section
CtX_DDL.Add_Stop_Section (
group_name => 'my_section_group' /* whatever you called it in the preceding
section */
section_name => 'qq' /* what you want to call this section */ );
Step 3. Create an Index Using the Section Preference Created in Step 2
Create an index depending on which section group you used to create a preference:
Creating an Index Using XML_SECTION_GROUP
To index your XML document when you have used XML_SECTION_GROUP, you can
use the following statement:
CREATE INDEX myindex ON docs(htmlfile) INDEXTYPE IS ctxsys.context
parameters('section group xmlgroup');
Creating an Index Using AUTO_SECTION_GROUP
The following statement creates the index, myindex, on a column containing XML
les using the AUTO_SECTION_GROUP:
CREATE INDEX myindex ON xmldocs(xmlfile) INDEXTYPE IS ctxsys.context PARAMETERS
('section group autogroup');
Creating an Index Using PATH_SECTION_GROUP
To index your XML document when you have used PATH_SECTION_GROUP, you
can use the following statement:
CREATE INDEX myindex ON xmldocs(xmlfile) INDEXTYPE IS ctxsys.context PARAMETERS
('section group xmlpathgroup');
See Also: "Creating an Index Using XML_SECTION_GROUP" on
page 7-29.
Step 3. Create an Index Using the Section Preference Created in Step 2
Searching XML Data with Oracle Text 7-29
Example 73 Creating an Index Using XML_SECTION_GROUP
EXEC ctx_ddl_create_section_group('myxmlgroup', 'XML_SECTION_GROUP');
/* ADDING A FIELD SECTION */
EXEC ctx_ddl.Add_Field_Section /* THIS IS KEY */
( group_name =>'my_section_group',
section_name =>'author',/* do this for EVERY tag used after "WITHIN" */
tag =>'author'
);
EXEC ctx_ddl.Add_Field_Section /* THIS IS KEY */
( group_name =>'my_section_group',
section_name =>'document',/*do this for EVERY tag after "WITHIN" */
tag =>'document'
);
...
/
/* ADDING AN ATTRIBUTE SECTION */
EXEC ctx_ddl.add_attr_section('myxmlgroup', 'booktitle', 'book@title');
/* The more sections you add to your index, the longer your search will take.*/
/* Useful for defining attributes in XML documents as sections. This allows*/
/* you to search XML attribute text using the WITHIN operator.*/
/* The section name:
/* ** Is used for WITHIN queries on the attribute text.
** Cannot contain the colon (:) or dot (.) characters.
** Must be unique within group_name.
** Is case-insensitive.
** Can be no more than 64 bytes.
** The tag specifies the name of the attribute in tag@attr format. This is
case-sensitive. */
/* Names used as arguments of the keyword WITHIN can be different from the
actual XML tag names. Many tags can be mapped to the same name at query
time.*/
/* Call CTX_DDL.Add_Zone_Section for each tag in your XML document that you need
to search on. */
EXEC ctx_ddl.add_zone_section('myxmlgroup', 'mybooksec', 'mydocname(book)');
CREATE INDEX my_index ON my_table ( my_column )
INDEXTYPE IS ctxsys.context
See Also: Oracle Text Reference for detailed notes on CTX_DDL.
Step 4. Create Your Query Syntax
7-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
PARAMETERS ( 'SECTION GROUP my_section_group' );
SELECT my_column FROM my_table
WHERE CONTAINS(my_column, 'smith WITHIN author') > 0;
Step 4. Create Your Query Syntax
See the section, "Querying with the CONTAINS Operator" for information about
how to use the CONTAINS operator in query statements.
Querying Within Attribute Sections
You can query within attribute sections when you index with either
XML_SECTION_GROUP or AUTO_SECTION_GROUP as your section group type.
Assume you have an XML document as follows:
<book title="Tale of Two Cities">It was the best of times.</book>
You can dene the section title@book as the attribute section title. You can do so
with the CTX_DLL.Add_Attr_Section procedure or dynamically after indexing
with ALTER INDEX.
If you use the XML_SECTION_GROUP, you can name attribute sections anything
with CTX_DDL.ADD_ATTR_SECTION.
To search on Tale within the attribute section title, issue the following query:
WHERE CONTAINS (...,'Tale WITHIN title', ...)
When you dene the TITLE attribute section as such and index the document set,
you can query the XML attribute text as follows:
... WHERE CONTAINS (...,'Cities WITHIN booktitle', ....)...
When you dene the AUTHOR attribute section as such and index the document
set, you can query the XML attribute text as follows:
... WHERE 'England WITHIN authors'
Note: When you use the AUTO_SECTION_GROUP to index XML
documents, the system automatically creates attribute sections and
names them in the formattribute@tag.
Step 4. Create Your Query Syntax
Searching XML Data with Oracle Text 7-31
Example 74 Querying an XML Document
This example does the following:
1. Creates and populates table res_xml
2. Creates an index, section_group, and preferences
3. Paramaterizes the preferences
4. Runs a test query against res_xml
drop table res_xml;
CREATE TABLE res_xml (
pk NUMBER PRIMARY KEY ,
text CLOB
) ;
insert into res_xml values(111,
'ENTITY chap8 "Chapter 8, <q>Keeping it Tidy: the XML Rule Book </q>"> this is
the document section');
commit;
---
--- script to create index on res_xml
---
--- cleanup, in case we have run this before
DROP INDEX res_index ;
EXEC CTX_DDL.DROP_SECTION_GROUP ( 'res_sections' ) ;
--- create a section group
BEGIN
CTX_DDL.CREATE_SECTION_GROUP ( 'res_sections', 'XML_SECTION_GROUP' ) ;
CTX_DDL.ADD_FIELD_SECTION ( 'res_sections', 'chap8', '<q>') ;
END ;
/
begin
ctx_ddl.create_preference
(
preference_name => 'my_basic_lexer',
object_name => 'basic_lexer'
);
ctx_ddl.set_attribute
(
Step 4. Create Your Query Syntax
7-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
preference_name => 'my_basic_lexer',
attribute_name => 'index_text',
attribute_value => 'true'
);
ctx_ddl.set_attribute
(
preference_name => 'my_basic_lexer',
attribute_name => 'index_themes',
attribute_value => 'false');
end;
/
CREATE INDEX res_index
ON res_xml(text)
INDEXTYPE IS ctxsys.context
PARAMETERS ( 'lexer my_basic_lexer SECTION GROUP res_sections' ) ;
Test the preceding index with a test query, such as:
SELECT pk FROM res_xml WHERE CONTAINS( text, 'keeping WITHIN chap8' )>0 ;
Example 75 Creating an Index and Performing a Text Query
drop table explain_ex;
create table explain_ex
(
id number primary key,
text varchar(2000)
);
insert into explain_ex ( id, text )
values ( 1, 'thinks thinking thought go going goes gone went' || chr(10) ||
'oracle orackle oricle dog cat bird' || chr(10) ||
'President Clinton' );
insert into explain_ex ( id, text )
values ( 2, 'Last summer I went to New England' || chr(10) ||
'I hiked a lot.' || chr(10) ||
'I camped a bit.' );
commit;
Example 76 Text Query Using "ABOUT" in the Text Query Expression
Set Define Off
select text
from explain_ex
Step 4. Create Your Query Syntax
Searching XML Data with Oracle Text 7-33
WHERE CONTAINS ( text,
'( $( think & go ) , ?oracle ) & ( dog , ( cat & bird ) ) & about(mammal
during Bill Clinton)' ) > 0;
select text
from explain_ex
WHERE CONTAINS ( text, 'about ( camping and hiking in new england )' ) > 0;
Example 77 Creating an Index Using AUTO_SECTION_GROUP
ctx_ddl_create_section_group('auto', 'AUTO_SECTION_GROUP');
CREATE INDEX myindex ON docs(xmlfile_column)
INDEXTYPE IS ctxsys.context
PARAMETERS ('filter ctxsys.null_filter SECTION GROUP auto');
SELECT xmlfile_column FROM docs
WHERE CONTAINS (xmlfile_column, virginia WITHIN title)>0;
Example 78 Creating an Index Using PATH_SECTION_GROUP
EXEC ctx_ddl.create_section_group('xmlpathgroup', 'PATH_SECTION_GROUP');
CREATE INDEX myindex ON xmldocs(xmlfile_column)
INDEXTYPE IS ctxsys.context
PARAMETERS ('section group xmlpathgroup');
SELECT xmlfile_column FROM xmldocs
... WHERE CONTAINS (column, Tale WITHIN title@book)>0;
Example 79 Using XML_SECTION_GROUP and add_attr_section to Aid Querying
Consider an XML le that denes the BOOK tag with a TITLE attribute as follows:
<BOOK TITLE="Tale of Two Cities">
It was the best of times. </BOOK>
<Author="Charles Dickens">
Born in England in the town, Stratford_Upon_Avon </Author>
Recall the CTX_DDL.ADD_ATTR_SECTION syntax is:
CTX_DDL.Add_Attr_Section ( group_name, section_name, tag );
To dene the title attribute as an attribute section, create an XML_SECTION_GROUP
and dene the attribute section as follows:
ctx_ddl_create_section_group('myxmlgroup', 'XML_SECTION_GROUP');
Presenting the Results of Your Query
7-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
ctx_ddl.add_attr_section('myxmlgroup', 'booktitle', 'book@title');
ctx_ddl.add_attr_section('myxmlgroup', 'authors', 'author');
end;
Presenting the Results of Your Query
An Oracle Text query application enables viewing documents returned by a query.
You typically select a document from the hit list and then your application presents
the document in some form.
With Oracle Text, you can render a document in different ways. For example, with
the query terms highlighted. Highlighted query terms can be either the words of a
word query or the themes of an ABOUT query in English. This rendering uses the
CTX_DOC.HIGHLIGHT or CTX_DOC.MARKUP procedures.
You can also obtain theme information from documents with the CTX_DOC.THEMES
PL/SQL package. Besides these there are several other CTX_DOC procedures for
presenting your query results.
INPATH does not support working with highlighting or themes.
Note:
I Oracle knows what the end tags look like from the group_type
parameter you specify when you create the section group. The
start tag you specify must be unique within a section group.
I Section names need not be unique across tags. You can assign
the same section name to more than one tag, making details
transparent to searches.
See Also: Oracle Text Reference for more information on the
CTX_DOC package.
XMLType Indexing
Searching XML Data with Oracle Text 7-35
XMLType Indexing
The Oracle9i datatype for storing XML, XMLType, is a core database feature.
You Need Query Rewrite Privileges
You can create an Oracle Text index on this type, but you need a few database
privileges rst:
1. The user creating the index must have Query Rewrite privileges:
GRANT QUERY REWRITE TO <user>
Without this privilege, the create index will fail with:
ORA-01031: insufficient privileges
<user> should be the user creating the index. The database schema that owns
the index, if different, does not need the grant.
2. query_rewrite_enabled should be true, and query_rewrite_integrity should be
trusted. You can add them to the init.ora le:
query_rewrite_enabled=true
query_rewrite_integrity=trusted
or turn it on for the session as follows:
ALTER SESSION SET query_rewrite_enabled=true;
ALTER SESSION SET query_rewrite_integrity=trusted;
Without these, queries will fail with:
DRG-10599: column is not indexed
These privileges are needed because XMLType is really an object, and you access it
through a function, hence an Oracle Text index on an XMLType column is actually a
function-based index on the getclobval() method of the type. These are the
standard grants you need to use function-based indexes, however, unlike
function-based B-Tree indexes, you do not need to calculate statistics.
Note: These privileges are only required for Oracle9i Release 1
(9.0.1).
XMLType Indexing
7-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
System Parameter is Set to the Default, CTXSYS.PATH_SECTION_GROUP
When an XMLType column is detected, and no section group is specied in the
parameters string, the default system examines the new system parameter
DEFAULT_XML_SECTION, and uses the section group specied there. At install time
this system parameter is set to CTXSYS.PATH_SECTION_GROUP, which is the
default path sectioner.
The default lter system parameter for XMLType is DEFAULT_FILTER_TEXT,
which means that the INSO lter is not engaged by default.
XMLType Indexes Work Like Other Oracle Text Indexes
Other than the database privileges and the special default section group system
parameter, indexes on XMLType columns work like any other Oracle Text index.
Example 710 Creating a Text Index on XMLType Columns
Here is a simple example:
connect ctxsys/ctxsys
GRANT QUERY REWRITE TO xtest;
connect xtest/xtest
CREATE TABLE xtest(doc sys.xmltype);
INSERT INTO xtest VALUES (sys.xmltype.createxml('<A>simple</A>'));
CREATE INDEX xtestx ON xtest(doc)
Note: Oracle9i SQL Reference under CREATE INDEX, states:
To create a function-based index in your own schema on your own
table, in addition to the prerequisites for creating a conventional
index, you must have the QUERY REWRITE system privilege.
To create the index in another schema or on another schema's table,
you must have the GLOBAL QUERY REWRITE privilege. In both
cases, the table owner must also have the EXECUTE object
privilege on the function(s) used in the function-based index.
In addition, in order for Oracle to use function-based indexes in
queries, the QUERY_REWRITE_ENABLED parameter must be set
to TRUE, and the QUERY_REWRITE_INTEGRITY parameter must
be set to TRUSTED.
Using Oracle Text with Oracle XML DB
Searching XML Data with Oracle Text 7-37
INDEXTYPE IS ctxsys.context;
ALTER SESSION SET query_rewrite_enabled = true;
ALTER SESSION SET query_rewrite_integrity = trusted;
SELECT a.doc.getclobval() FROM xtest a
WHERE CONTAINS (doc, 'simple INPATH(A)')>0;
Using Oracle Text with Oracle XML DB
Creating an Oracle Text Index on an UriType Column
UriType columns can be indexed natively in Oracle9i database using Oracle Text.
No special datastore is needed.
Example 711 Creating an Oracle Text Index on a UriType Column
For example:
CREATE TABLE table uri_tab ( url sys.httpuritype);
INSERT INTO uri_tab VALUES
(sys.httpuritype.createUri('http://www.oracle.com'));
CREATE INDEX urlx ON uri_tab(url) INDEXTYPE IS ctxsys.context;
SELECT url FROM uri_tab WHERE CONTAINS(url, Oracle)>0;
Table 75 lists system parameters used for default preference names for Oracle Text
indexing, when the column type is UriType:
Table 75 rUriType Column Default Preference Names for Oracle Text Indexing
URIType Column Default Preference Names
DATASTORE DEFAULT_DATASTORE
FILTER DEFAULT_FILTER_TEXT
SECTION GROUP DEFAULT_SECTION_HTML
LEXER DEFAULT_LEXER
STOPLIST DEFAULT_STOPLIST
WORDLIST DEFAULT_WORDLIST
STORAGE DEFAULT_STORAGE
Using Oracle Text with Oracle XML DB
7-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Querying XML Data: Use CONTAINS or existsNode()?
Oracle9i Release 1(9.0.1) introduced the Oracle Text PATH_SECTION_GROUP,
INPATH(), and HASPATH() query operators. These allow you to do XPath-like text
query searches on XML documents using the CONTAINS operator. CONTAINS,
however, supports only a subset of XPath functionality. Also, there are important
semantic differences between the CONTAINS operator and the existsNode()
function.
The existsNode, extract() and extractValue() SQL functions (and the
corresponding member functions of XMLType) provide full XPath support. This
release of Oracle9i also introduces new extension functions to XPath to support full
text searches.
Table 76 lists and compares CONTAINS() and existsNode() features for
searching XMLType data.
Note: This release does not support theme querying for Oracle
Text CONTAINS() and existsNode() searching.
Table 76 Using CONTAINS() and existsNode() to Search XMLType Data
Feature CONTAINS() existsNode()
XPath Conformance -- --
Predicate Support -- --
I String equality Y Y
I Numerical equality N Y
I Range Predicates N Y
I XPath functions N Y
I Spaces N Y
I Namespaces N Y
I Value case sensitivity N Y
I Entity handling N Y
I Parent-ancestor and
sibling axes
N Y
Using Oracle Text with Oracle XML DB
Searching XML Data with Oracle Text 7-39
I Attribute searching
under wild cards. For
example, */@A or ../
Y Y
I Uses XML schema or
DTD information
N Y
I Empty elements may
lead to false matches
Y N
Synchronous -- --
I DML N CTXXPath = N
Other indexes = Y
I Query N Y
Linguistic search capability In INPATH() -> Y Using ora:contains() -> Y
Index type ctxsys.context ctxsys.ctxxpath
Query rewrites N Y, if XML schema-based
and stored
object-relationally
Functional indexes N Y. Can create Functional
Index on existsNode() and
extractValue() expressions.
Features supported if context
index is already built
-- --
I About Y N
I Highlighting Y N
Text searching in general Supports full text
searching.
Supports limited text
searching with
ora:contains.
XPath searching in general Limited XPath
searching.
Non-synchronous.
Full XPath searching.
Synchronous.
Table 76 Using CONTAINS() and existsNode() to Search XMLType Data (Cont.)
Feature CONTAINS() existsNode()
Full-Text Search Functions in XPath Using ora:contains
7-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Full-Text Search Functions in XPath Using ora:contains
Though XPath species a set of builtin text functions such as substring() and
CONTAINS(), these are considerably less powerful than Oracle's full text search
capabilities. NewXPath extension functions are dened by Oracle to enable a richer
set of text search capabilities. These extension functions are dened within the
Oracle XML DB namespace : http://xmlns.oracle.com/xdb.
They can be used within XPath queries appearing in the context of existsNode(),
extract() and extractValue() functions operating on XMLType instances.
ora:contains Features
The following lists the ora:contains features:
I The text search extension functions support most of text query operators such
as stemming, fuzzy matching, and proximity search.
I These functions do not require a ConText index for their evaluation.
I The score values computed by these functions may differ from the regular
index based query processing (through Contains SQL operator). Due to absence
of document statistics, the weight for each term is xed to 10. This means that a
score for a word search is the number of occurrence multiplied by 10. If it
exceeds 100, it is truncated to 100. This is also true for fuzzy matched terms.
ora:contains Syntax
The following is the syntax for the ora:contains function:
number contains(string, string, string?, string?)
where:
I string, the rst argument is input text value
I string, the second argument is the text query string
I string?, the optional third argument is the policy name
I string?, the optional fourth argument is the policy owner
Note: Like other procedures in CTX_DDL package, you must have
CTXAPP privilege in order to execute the
CTX_DDL.CREATE_POLICY() procedure.
Full-Text Search Functions in XPath Using ora:contains
Searching XML Data with Oracle Text 7-41
The contains extension function in the Oracle XML DB namespace, takes the
input text value as the rst argument and the text query string as the second
argument. It returns the score value - a number between 0 and 100.
The optional third and fourth arguments can be used to specify the name and
owner of the CTX policy which is to be used for processing the text query. If the
third argument is not specied, it defaults to the CTX policy named
DEFAULT_POLICY_ORACONTAINS owned by CTXSYS. If the fourth argument is not
specied, the policy owner is assumed to be the current user.
ora:contains Examples
Assume the table xmltab contains XML documents corresponding to books with
embedded chapters, each chapter containing a title and a body.
<book>
<chapter>
<title>...</title>
<body>...</body>
</chapter>
<chapter>
<title>...</title>
<body>...</body>
</chapter>
...
</book>
Example 712 Using ora:contains to Find a Text Query String
Find books containing a chapter whose body contains the specied text query
string:
select * from xmltab x where
existsNode(value(x), '/book/chapter[ora:contains(body,"dog OR cat")>0]',
'xmlns:ora="http://xmlns.oracle.com/xdb"') = 1;
Example 713 Using ora:contains and extract() to Find a Text Query String
Extract chapters whose body contains the specied text query string.
select extract(value(x),
'/book/chapter[ora:contains(body,"dog OR cat")>0]',
'xmlns:ora="http://xmlns.oracle.com/xdb"')
from xmltab x;
Oracle XML DB: Creating a Policy for ora:contains()
7-42 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB: Creating a Policy for ora:contains()
This section includes syntax and examples for creating, updating, and dropping a
policy for ora:contains():
The following CTX_DDL procedures creates/updates/drops a policy used by
ora:contains():
A policy is a set of preferences used for processing ora:contains().
Table 77 describes the CTX_DDL functions for creating, updating, and dropping
policies for use in your XPath searches.
See Also: Oracle XML DB: Creating a Policy for ora:contains() on
page 7-42.
See Also:
I Oracle Text Application Developers Guide
I Oracle Text Reference
for a description of the Oracle Text preferences.
Oracle XML DB: Creating a Policy for ora:contains()
Searching XML Data with Oracle Text 7-43
Example 714 Creating a Policy for ora:contains
Create lexer preference named mylex:
begin
ctx_ddl.create_preference(mylex, BASIC_LEXER);
ctx_ddl.set_attribute(mylex, printjoins, _-);
ctx_ddl.set_attribute ( mylex, index_themes, NO);
ctx_ddl.set_attribute ( mylex, index_text, YES);
end;
Table 77 CTX_DDL Syntax for Creating, Updating, and Dropping Policies
CTX_DDL Function Description
CREATE_POLICY
CTX_DDL.create_policy(policy_name in varchar2, lter
in varchar2 default NULL, section_group in varchar2 default
NULL, lexer n varchar2 default NULL, stoplist in varchar2
default NULL, wordlist in varchar2 default NULL);
Denes a policy.
Arguments:
policy_name - the name for the new policy
lter - the lter preference to use (reserved for future use)
section_group - the section group to use (currently only
NULL_SECTION_GROUP is supported)
lexer - the lexer preference to use. This should not have
theme indexing turned on.
stoplist - the stoplist preference to use
wordlist - the wordlist preference to use
UPDATE_POLICY
CTX_DDL.update_policy( policy_name in varchar2, lter
in varchar2 default NULL, section_group in varchar2 default
NULL, lexer in varchar2 default NULL, stoplist in varchar2
default NULL, wordlist in varchar2 default NULL);
Updates a policy by replacing specied preferences.
Arguments:
policy_name - the name for the policy
lter - the new lter preference to use (reserved for future
use)
section_group - the newsection group to use (currently only
NULL_SECTION_GROUP is supported)
lexer - the newlexer preference. This should not have theme
indexing turned on.
stoplist - the new stoplist preference to use
wordlist - the new wordlist preference to use
DROP_POLICY
CTX_DDL.drop_policy(policy_name in varchar2);
Deletes a policy.
Arguments:
policy_name - the name of the policy
Oracle XML DB: Creating a Policy for ora:contains()
7-44 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Create a stoplist preference named mystop.
begin
ctx_ddl.create_stoplist(mystop, BASIC_STOPLIST);
ctx_ddl.add_stopword(mystop, because);
ctx_ddl.add_stopword(mystop, nonetheless);
ctx_ddl.add_stopword(mystop, therefore);
end;
Create a wordlist preference named mywordlist.
begin
ctx_ddl.create_preference(mywordlist, BASIC_WORDLIST);
ctx_ddl.set_attribute(mywordlist,FUZZY_MATCH,ENGLISH);
ctx_ddl.set_attribute(mywordlist,FUZZY_SCORE,0);
ctx_ddl.set_attribute(mywordlist,FUZZY_NUMRESULTS,5000);
ctx_ddl.set_attribute(mywordlist,SUBSTRING_INDEX,TRUE);
ctx_ddl.set
_attribute(mywordlist,STEMMER,ENGLISH);
end;
exec ctx_ddl.create_policy(my_policy, NULL, NULL, mylex, mystop,
mywordlist);
or
exec ctx_ddl.create_policy(policy_name => my_policy,
lexer => mylex,
stoplist => mystop,
wordlist => mywordlist);
Then you can issue the following existsNode() query with your own dened
policy:
select * from xmltab x where
existsNode(value(x),
/book/chapter[ora:contains(body,"dog OR cat", "my_policy")>0],
xmlns:ora="http://xmlns.oracle.com/xdb") = 1;
You can also update your policy by using the following:
exec ctx_ddl.update_policy(policy_name => my_policy,
lexer => my_new_lex);
You can drop your policy by using:
Oracle XML DB: Using CTXXPATH Indexes for existsNode()
Searching XML Data with Oracle Text 7-45
exec ctx_ddl.drop_policy(policy_name => my_policy);
Querying Using Other Users Policy
You can also issue the existsNode() query using another users policy, in this
case, using Scotts policy:
Example 715 Querying Another Users Policy
select * from xmltab x where
existsNode(value(x),
/book/chapter[ora:contains(body,"dog OR cat", "Scotts_policy","Scott")>0],
xmlns:ora="http://xmlns.oracle.com/xdb") = 1;
Oracle XML DB: Using CTXXPATH Indexes for existsNode()
The existsNode() SQL function, unlike the CONTAINS operator, cannot use
ConText indexes to speed up its evaluation. To improve the performance of XPath
searches in existsNode(), this release introduces a new index type, CTXXPATH.
The CTXXPATH index is a new indextype provided by Oracle Text. It is designed to
serve as a primary lter for existsNode() processing, that is, it produces a
superset of the results that would be produced by the existNode() function.
Why do We Need CTXXPATH When ConText Indexes Can Perform XPath Searches?
The existing ConText index type already has some XPath searching capabilities,
but the ConText index type has some limitations:
I For the ConText index to be usable as a primary lter for existsNode(),
I You must create the index using PATH_SECTION_GROUP.
I You cannot create the index with USER_LEXER or MULTI_LEXER
preference.
I You must create the index with DIRECT DATASTORE.
I You must create the index with NULL FILTER.
This limits the linguistic searching capabilities that ConText index type
provides.
I The ConText index is asynchronous and does not follow the same
transactional semantics as existsNode().
Oracle XML DB: Using CTXXPATH Indexes for existsNode()
7-46 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I The ConText index does not handle namespaces nor user-dened entities.
With all these limitations in mind, CTXXPATH index type was designed specically
to serve the purpose of existsNode() primary lter processing. You can still
create ConText indexes with whichever preferences you need on XMLType
columns, and this will be used to speed up CONTAINS operators. At the same time,
you can create a CTXXPATH index to speedup the processing of existsNode().
CTXXPATH Index Type
CTXXPATH index type has the following characteristics:
I This index can only be used to speed up existsNode() processing. It acts as
a primary lter for the existsNode() function. In other words, it provides a
superset of the results that existsNode() would provide
I The index can only handle a limited set of XPath expressions. See the Section ,
"Choosing the Right Plan: Using CTXXPATH Index in existsNode() Processing"
for the list of XPath expressions not supported by the index.
I The only supported parameter is the TABLESPACE parameter. See "Creating
CTXXPATH Storage Preferences with CTX_DDL. Statements" on page 7-47.
I DMLs are asynchronous. Users are required to issue a special DDL command to
synchronize the DMLs, similar to that of ConText index.
I Despite the asynchronous nature of DML, it still follows transactional semantics
of existsNode() by also returning unindexed rows as part of its result set in
order to guarantee its requirement of returning a superset of the valid results.
Creating CTXXPATH Indexes
You create CTXXPATH indexes the same way you create ConText indexes. The
syntax is the same as that of ConText index:
CREATE INDEX [schema.]index ON [schema.]table(XMLType column)
INDEXTYPE IS ctxsys.CTXXPATH [PARAMETERS(paramstring)];
where
paramstring = [storage storage_pref] [memory memsize] [populate | nopopulate]
Example 716 Creating CTXXPATH Indexes
For example:
CREATE INDEX xml_idx ON xml_tab(col_xml) indextype is ctxsys.CTXXPATH;
Oracle XML DB: Using CTXXPATH Indexes for existsNode()
Searching XML Data with Oracle Text 7-47
or
CREATE INDEX xml_idx ON xml_tab(col_xml) indextype is ctxsys.CTXXPATH
PARAMETERS(storage my_storage memory 40M);
The index can only be used to speed up queries using existsNode():
SELECT xml_id FROM xml_tab x WHERE
x.col_xml.existsnode(/book/chapter[@title="XML"])>1;
Creating CTXXPATH Storage Preferences with CTX_DDL. Statements
The only preference allowed for CTXXPATH index type is the STORAGE preference.
You create the STORAGE preference the same way you would for a ConText index
type.
Example 717 Creating Storage Preferences for CTXXPATH Indexes
For example:
begin
ctx_ddl.create_preference(mystore, BASIC_STORAGE);
ctx_ddl.set_attribute(mystore, I_TABLE_CLAUSE,
tablespace foo storage (initial 1K));
ctx_ddl.set_attribute(mystore, K_TABLE_CLAUSE,
tablespace foo storage (initial 1K));
ctx_ddl.set_attribute(mystore, R_TABLE_CLAUSE,
tablespace foo storage (initial 1K));
ctx_ddl.set_attribute(mystore, N_TABLE_CLAUSE,
tablespace foo storage (initial 1K));
ctx_ddl.set_attribute(mystore, I_INDEX_CLAUSE,
tablespace foo storage (initial 1K));
end;
Performance Tuning CTXXPATH Index: Synchronizing and Optimizing the Index
To synchronize DMLs, you can use the SYNC_INDEX procedure provided in the
CTX_DDL package.
See Also: Chapter 4, "Using XMLType" for more information on
using existsNode().
Oracle XML DB: Using CTXXPATH Indexes for existsNode()
7-48 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 718 Optimizing the CTXXPATH Index
For example:
exec ctx_ddl.sync_index(xml_idx);
To optimize the CTXXPATH index, you can use the OPTIMIZE_INDEX() procedure
provided in the CTX_DDL package. For example:
exec ctx_ddl.optimize_index(xml_idx, FAST);
or
exec ctx_ddl.optmize_index(xml_idx, FULL);
Choosing the Right Plan: Using CTXXPATH Index in existsNode() Processing
It is not guaranteed that a CTXXPATH index will always be used to speed up
existsNode() processing. The following is a list of reasons why Oracle Text
index may not be used under existsNode():
I The Cost Based Optimizer decides it is too expensive to use CTXXPATH index as
primary lter.
I The XPath expression cannot be handled by CTXXPATH index. Here are a list of
XPath constructs CTXXPATH index cannot handle:
I XPATH functions.
I Numerical Range operators.
I Numerical equality.
I Arithmetic operators.
I Union operator |
I Existence of attribute
I Positional/Index predicate, that is, /A/B[5].
I Parent and sibling axes
I attribute following a *, //,.., in other words,/A/*/@attr, /A//@attr,
/A//../@attr
See Also:
I Oracle Text Application Developers Guide
I Oracle Text Reference
Using Oracle Text: Advanced Techniques
Searching XML Data with Oracle Text 7-49
I . or * at the end of the path expression.
I predicate following . or *.
I String literal equality is supported with the following restrictions:
* The left hand side must be a path (. self by itself is not
allowed,.="dog).
* The right hand side must be a literal.
For the Optimizer to better estimate the costs and selectivities for the
existsNode() function, you must gather statistics on CTXXPATH index by using
ANALYZE command or DBMS_STATS package. You can analyze the index and
compute the statistics using the ANALYZE command as follows:
ANALYZE INDEX myPathIndex COMPUTE STATISTICS;
or you can simply analyze the whole table:
ANALYZE TABLE XMLTAB COMPUTE STATISTICS;
Using Oracle Text: Advanced Techniques
The following sections describe several Oracle Text advanced techniques for
ne-tuning your XML data search.
Highlight Support for INPATH/HASPATH Text Operators
Oracle Text provides the CTX_DOC.HIGHLIGHT() procedure to generate highlight
offsets and lengths for a Text query on a document. These offsets and lengths are
generated for the terms in the document that satisfy a word query, phrase query, or
about query. In Oracle9i Release 2 (9.2.0.2), Oracle Text extends highlight support
for INPATH and HASPATH operators.
Highlighting XML Documents with INPATH
For INPATH, CTX_DOC.HIGHTLIGHT() calculates the offset and length for the left
hand child of the INPATH operator just as with the WITHIN operator. This only
applies to cases where the path child points to an element. For example, if the Text
query expression is:
'txt INPATH(/A/B)' or
'txt INPATH(/A/B[@attr="atxt" and .="Btxt"])'
Using Oracle Text: Advanced Techniques
7-50 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
then CTX_DOC.HIGHTLIGHT() generates offsets and lengths for all occurrences of
'txt' in the document satisfying the INPATH query.
If the path child points to an attribute, then nothing is highlighted. For example, if
the Text query expression is:
'atxt INPATH(/A/B/@attr)'
then no highlight information is generated.
Highlighting XML Documents with HASPATH
For HASPATH, if its path operand points to an element, CTX_DOC.HIGHTLIGHT()
calculates the offset and length for the bodies of the element pointed to by the
XPath expression. For example, if the Text query expression is:
'HASPATH(/A/B)' or
'HASPATH(/A/B[@att="atxt"])'
then offsets and lengths are calculated for the bodies of elements pointed to by
/A/B.
If the path operand points to an attribute, such as, 'HASPATH(/A/B/@Battr)',
then no highlight information is generated.
If the operand does WITHIN-EQUAL/SECTION-EQUAL testing, then
CTX_DOC.HIGHTLIGHT() outputs offsets and lengths of the elements pointed to
by the path child of '='. If the path child of '=' points to an attribute, then no
highlight information is generated. For example, if the Text query expression is:
HASPATH(/A/B = "ABtxt")' or
'HASPATH(/A/B[@att="atxt"]= "ABtxt")'
then offsets and lengths are generated for the bodies of elements pointed to by
/A/B. On the other hand, if the Text query expression is:
'HASPATH(/A/B/@att = "atxt")'
then no highlight information is generated because the path child '/A/B/@att'
points to an attribute, not an element.
Using Oracle Text: Advanced Techniques
Searching XML Data with Oracle Text 7-51
Distinguishing Tags Across DocTypes
In previous releases, XML_SECTION_GROUP was unable to distinguish between
tags in different DTDs. For example, suppose you use the following DTD for storing
contact information:
<!DOCTYPE contact>
<contact>
<address>506 Blue Pool Road</address>
<email>[email protected]</email>
</contact>
Appropriate sections might look like:
ctx_ddl.add_field_section('mysg','email', 'email');
ctx_ddl.add_field_section('mysg','address','address');
This is ne until you have a different kind of document in the same table:
<!DOCTYPE mail>
<mail>
<address>[email protected]</address>
</mail>
Now your address section, originally intended for street addresses, starts picking
up email addresses, because of tag collision.
Specifying Doctype Limiters to Distinguish Between Tags
Oracle8i release 8.1.5 and higher allow you to specify doctype limiters to distinguish
between these tags across doctypes. Simply specify the doctype in parentheses
before the tag as follows:
ctx_ddl.add_field_section('mysg','email','email');
ctx_ddl.add_field_section('mysg','address','(contact)address');
ctx_ddl.add_field_section('mysg','email','(mail)address');
Note: While CTX_DOC.HIGHTLIGHT() calculates and outputs
the offsets and lengths, CTX_DOC.MARKUP() goes one step further
by returning a version of the document with query terms or
element bodies marked up using specied tags.
Note that mark-ups can make the target XML document invalid.
Using Oracle Text: Advanced Techniques
7-52 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Nowwhen the XML section group sees an address tag, it will index it as the address
section when the document type is contact, or as the email section when the
document type is mail.
Doctype-Limited and Unlimited Tags in a Section Group
If you have both doctype-limited and unlimited tags in a section group:
ctx_ddl.add_field_section('mysg','sec1','(type1)tag1');
ctx_ddl.add_field_section('mysg','sec2','tag1');
Then the limited tag applies when in the doctype, and the unlimited tag applies in
all other doctypes.
Querying is unaffected by this. The query is done on the section name, not the tag,
so querying for an email address would be done like:
radical WITHIN email
which, since we have mapped two different kinds of tags to the same section name,
nds documents independent of which tags are used to express the email address.
XML_SECTION_GROUP Attribute Sections
In Oracle8i Release 1(8.1.5) and higher, XML_SECTION_GROUP offers the ability to
index and search within attribute values. Consider a document with the following
lines:
<comment author="jeeves">
I really like Oracle Text
</comment>
NowXML_SECTION_GROUP offers an attribute section. This allows the inclusion of
attribute values to index. For example:
ctx_ddl.add_attr_section('mysg','author','comment@author');
The syntax is similar to other add_section calls. The rst argument is the name of
the section group, the second is the name of the section, and the third is the tag, in
the form <tag_name>@<attribute_name>. This tells Oracle Text to index the
contents of the author attribute of the comment tag as the section author.
Query syntax is just like for any other section:
WHERE CONTAINS ( ... ,jeeves WITHIN author...,...)...
Using Oracle Text: Advanced Techniques
Searching XML Data with Oracle Text 7-53
and nds the document.
Attribute Value Sensitive Section Search
Attribute sections allow you to search the contents of attributes. They do not allow
you to use attribute values to specify sections to search. For instance, given the
document:
<comment author="jeeves">
I really like Oracle Text
</comment>
You can nd this document by asking:
jeeves within comment@author
which is equivalent to nd me all documents which have a comment element
whose author attribute's value includes the word jeeves.
However, there you cannot currently request the following:
interMedia within comment where (@author = "jeeves")
in other words, nd me all documents where interMedia appears in a comment
element whose author is jeeves. This feature -- attribute value sensitive section
searching -- is planned for future versions of the product.
Dynamic Add Section
Because the section group is dened before creating the index, Oracle8i Release 1
(8.1.5) is limited in its ability to cope with changing structured document sets; if
your documents start coming with newtags, or you start getting newdoctypes, you
have to re-create the index to start making use of those tags.
With Oracle8i Release 2 (8.1.6) and higher you can add new sections to an existing
index without rebuilding the index, using alter index and the new add section
parameters string syntax:
add zone section <section_name> tag <tag>
add field section <section_name> tag <tag> [ visible | invisible ]
For instance, to add a new zone section named tsec using the tag title:
alter index <indexname> rebuild
parameters ('add zone section tsec tag title')
To add a new eld section named asec using the tag author:
Using Oracle Text: Advanced Techniques
7-54 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
alter index <indexname> rebuild
parameters ('add field section asec tag author')
This eld section would be invisible by default, just like when using
ADD_FIELD_SECTION. To add it as visible eld section:
alter index <indexname> rebuild
parameters ('add field section asec tag author visible')
Dynamic add section only modies the index metadata, and does not rebuild the
index in any way. This means that these sections take effect for any document
indexed after the operation, and do not affect any existing documents -- if the index
already has documents with these sections, they must be manually marked for
re-indexing (usually with an update of the indexed column to itself).
This operation does not support addition of special sections. Those would require
all documents to be re-indexed, anyway. This operation cannot be done using
rebuild online, but it should be a fairly quick operation.
Constraints for Querying Attribute Sections
The following constraints apply to querying within attribute sections:
I Regular queries on attribute text do not hit the document unless qualied in a
within clause. Assume you have an XML document as follows:
<book title="Tale of Two Cities">It was the best of times.</book>
A query on Tale by itself does not produce a hit on the document unless
qualied with WITHIN title@book. This behavior is like eld sections when you
set the visible ag set to false.
I You cannot use attribute sections in a nested WITHIN query.
I Phrases ignore attribute text. For example, if the original document looked like:
Now is the time for all good <word type="noun"> men </word> to come to the
aid.
Then this document would hit on the regular query good men, ignoring the
intervening attribute text.
WITHIN queries can distinguish repeated attribute sections. This behavior is like
zone sections but unlike eld sections. For example, for the following document:
<book title="Tale of Two Cities">It was the best of times.</book>
<book title="Of Human Bondage">The sky broke dull and gray.</book>
Using Oracle Text: Advanced Techniques
Searching XML Data with Oracle Text 7-55
Assume the book is a zone section and book@author is an attribute section.
Consider the query:
'(Tale and Bondage) WITHIN book@author'
This query does not hit the document, because tale and bondage are in different
occurrences of the attribute section book@author.
Repeated Zone Sections
Zone sections can repeat. Each occurrence is treated as a separate section. For
example, if <H1> denotes a heading section, they can repeat in the same documents
as follows:
<H1> The Brown Fox </H1>
<H1> The Gray Wolf </H1>
Assuming that these zone sections are named Heading.
The query:
WHERE CONTAINS (..., Brown WITHIN Heading, ...)...
returns this document.
But the query:
WHERE CONTAINS (..., (Brown and Gray) WITHIN Heading,...)...
does not.
Overlapping Zone Sections
Zone sections can overlap each other. For example, if <B> and <I> denote two
different zone sections, they can overlap in document as follows:
plain <B> bold <I> bold and italic </B> only italic </I> plain
Nested Sections
Zone sections can nest, including themselves as follows:
<TD>
<TABLE>
<TD>nested cell</TD>
</TABLE>
Using Oracle Text: Advanced Techniques
7-56 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</TD>
Using the WITHIN operator, you can write queries to search for text in sections
within sections.
Nested Section Query Example
For example, assume the BOOK1, BOOK2, and AUTHOR zone sections occur as
follows in documents doc1 and doc2:
doc1:
<book1><author>Scott Tiger</author> This is a cool book to read.</book1>
doc2:
<book2> <author>Scott Tiger</author> This is a great book to read.</book2>
Consider the nested query:
'Scott WITHIN author WITHIN book1'
This query returns only doc1.
Using Table CTX_OBJECTS and CTX_OBJECT_ATTRIBUTES View
The CTX_OBJECT_ATTRIBUTES view displays attributes that can be assigned to
preferences of each object. It can be queried by all users.
Check out the structure of CTX_OBJECTS and CTX_OBJECT_ATTRIBUTE view,
with the following DESCRIBE commands. Because we are only interested in
querying XML documents in this chapter, we focus on XML_SECTION_GROUP and
AUTO_SECTION_GROUP.
Describe ctx_objects
SELECT obj_class, obj_name FROM ctx_objects
ORDRR BY obj_class, obj_name;
The result is:
...
SECTION_GROUP AUTO_SECTION_GROUP <<==
SECTION_GROUP BASIC_SECTION_GROUP
SECTION_GROUP HTML_SECTION_GROUP
SECTION_GROUP NEWS_SECTION_GROUP
SECTION_GROUP NULL_SECTION_GROUP
SECTION_GROUP XML_SECTION_GROUP <<==
Case Study: Searching XML-Based Conference Proceedings
Searching XML Data with Oracle Text 7-57
...
Describe ctx_object_attributes
SELECT oat_attribute FROM ctx_object_attributes
WHERE oat_object = 'XML_SECTION_GROUP';
The result is:
OAT_ATTRIBUTE
-------------
ATTR
FIELD
SPECIAL
ZONE
SELECT oat_attribute FROM ctx_object_attributes
WHERE oat_object = 'AUTO_SECTION_GROUP';
The result is:
OAT_ATTRIBUTE
-------------
STOP
Example 719 Case Study: See the following section.
Case Study: Searching XML-Based Conference Proceedings
This case study uses INPATH, HASPATH, and extract() to search a XML-based
conference proceedings.
Searching for Content and Structure in XML Documents
Documents are structured presentations of information. You can dene a document
as an asset that contains structure, content, and presentation. This case study
describes how to search for content and structure at the same time. All features
described here are available in Oracle9i Release 1 (9.0.1) and higher.
Note: You can download this sample application from
http://otn.oracle.com/products/text
Case Study: Searching XML-Based Conference Proceedings
7-58 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Consider an online conference proceedings search where the conference attendees
can perform full text searches on the structure of the papers, for example search on
title, author, abstract, and so on.
Searching XML-Based Conference Proceedings Using Oracle Text
Follow these tasks to build this conference proceedings search case study:
Task 1. Grant System Privileges. Set Initialization Parameters
You must be granted with QUERY REWRITE system privileges to create a
Functional Index. You must also have the following initialization parameters
dened to create a Functional Index:
I QUERY_REWRITE_INTEGRITY set to TRUSTED
I QUERY_REWRITE_ENABLED set to TRUE
I COMPATIBLE set to 8.1.0.0.0 or a greater value
Task 2. Create Table Proceedings
For example, create a table, Proceedings with two columns: tk, the papers id, and
papers, the content. Store the papers content as an XMLType.
CREATE TABLE Proceedings (tk number, papers XMLTYPE);
Task 3. Populate Table with Data
Now populate table Proceedings with some conference papers:
INSERT INTO Proceedings(tk,papers) VALUES (1, XMLType.createXML(
'<?xml version="1.0"?>
<paper>
<title>Accelerating Dynamic Web Sites using Edge Side Includes</title>
<authors>Soo Yun and Scott Davies</authors>
<company> Oracle Corporation </company>
<abstract> The main focus of this presentation is on Edge Side Includes
(ESI). ESI is a simple markup language which is used to mark cacheable and
non-cacheable fragments of a web page. An "ESI aware server", such as Oracle Web
Cache and Akamai EdgeSuite, can take in ESI marked content and cache and
assemble pages closer to the users, at the edge of the network, rather than at
the application server level. This session will discuss the challenge many
dynamic websites face today, discuss what ESI is, explain how ESI can be used to
alleviate these issues. The session will also describe how to build pages with
ESI, and detail the ESI and JESI (Edge Side Includes for Java) libraries.
</abstract>
Case Study: Searching XML-Based Conference Proceedings
Searching XML Data with Oracle Text 7-59
<track> Fast Track to Oracle9i </track>
</paper>'));
Task 4. Create an Oracle Text Index on the XMLType Column
Create an Oracle Text index on the XMLType column, papers, using the usual
CREATE INDEX statement:
CREATE INDEX proc_idx ON Proceedings(papers)
INDEXTYPE IS ctxsys.context
parameters(FILTER ctxsys.null_filter SECTION GROUP ctxsys.path_section_group);
Task 5. Querying the Conference Proceedings with XPath and Contains()
Oracle9i Release 1 (9.0.1) introduced two new SQL functions existsNode() and
extract() that operate on XMLType values as follows:
I existsNode(): given an XPath expression, checks if the XPath applied over
the XML document can return any valid nodes.
I extract(): given an XPath expression, applies the XPath to the XML
document and returns the fragment as an XMLType.
For example, select the authors only from the XML document:
SELECT p.papers.extract('/paper/authors/text()').getStringVal()
FROM Proceedings p;
You can use the Oracle Text CONTAINS() operator to search for content in a text or
XML document. For example, to search for papers that contain Dynamic in the
title you can use:
SELECT tk FROM Proceedings
WHERE CONTAINS(papers,'Dynamic INPATH(paper/title)')>0
Using the CONTAINS() operator Oracle9i returns the columns selected. For an XML
document it returns the entire document. To extract fragments of XML, you can
combine the extract() function to manipulate the XML. For example, select the
authors of papers that contain Dynamic in the title:
SELECT p.papers.extract('/paper/authors/text()').getStringVal()
FROM Proceedings p
WHERE CONTAINS(papers,'Dynamic INPATH(paper/title)')>0
You can use all the functionality of an Oracle Text query for the content search. The
following example selects the authors of papers containing Dynamic or Edge or
Libraries in the title:
Case Study: Searching XML-Based Conference Proceedings
7-60 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
SELECT p.papers.extract('/paper/authors/text()').getStringVal()
FROM Proceedings p
WHERE CONTAINS(papers,'Dynamic or Edge or Libraries INPATH(paper/title)')>0
Traditional databases allow searching of XML content or structure, but not both at
the same time. Oracle provides unique features that enable querying of both XML
content and structure at the same time.
Figure 71 illustrates entering the search for Libraries in the structure of the
Conference Proceedings documents. You can search for Libraries within Authors,
abstract, title, company, or track. In this example, you are searching for the term
Libraries in the abstracts only. Since it is an XML document your are searching,
you can even select which fragment of the XML document you want to display. This
example only displays the title of the paper.
Figure 72 shows the search results.
For the .jsp code to build this look-up application, see "Searching Conference
Proceedings Example: jsp" on page 7-62.
See Also:
I Oracle Text Reference
I Oracle Text Application Developers Guide
I http://otn.oracle.com/products/text
Case Study: Searching XML-Based Conference Proceedings
Searching XML Data with Oracle Text 7-61
Figure 71 Using Oracle Text to Search for Libraries in the Conference Proceedings Abstracts
Figure 72 Oracle Text Search Results
Case Study: Searching XML-Based Conference Proceedings
7-62 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Searching Conference Proceedings Example: jsp
Here is the full jsp example illustrating how you can use Oracle Text to create an
online XML-based Conference Proceedings look-up application.
<%@ page import="java.sql.* , oracle.jsp.dbutil.*" %>
<jsp:useBean id="name" class="oracle.jsp.jml.JmlString" scope="request" >
<jsp:setProperty name="name" property="value" param="query" />
</jsp:useBean>
<%
String connStr="jdbc:oracle:thin:@oalonso-sun:1521:betadev";
java.util.Properties info = new java.util.Properties();
Connection conn = null;
ResultSet rset = null;
Statement stmt = null;
if (name.isEmpty()) { %>
<html>
<title>OOW Paper Search</title>
<body>
<center>
<h3>OOW Proceedings Search </h3>
<form method=post>
Search for
<input type=text size=15 maxlength=25 name=query>
in
<select name="tagvalue">
<option value="authors">Author(s)
<option value="abstract">Abstract
<option value="title">Title
<option value="company">Company
<option value="track">Track
</select>
<input type=submit value="Search">
<p><b>Display</b><br>
<table>
<tr>
<td>
Author(s)<input type="radio" name="section" value="authors">
</td>
<td>
Abstract <input type="radio" name="section" value="abstract">
</td>
<td>
Title <input type="radio" name="section" value="title" checked>
Case Study: Searching XML-Based Conference Proceedings
Searching XML Data with Oracle Text 7-63
</td>
<td>
Company <input type="radio" name="section" value="company">
</td>
<td>
Track <input type="radio" name="section" value="track">
</td>
</tr>
</table>
</form>
</center>
<hr>
</body>
</html>
<%
}
else {
%>
<html>
<title>OOW Paper Search</title>
<body>
<center>
<h3>OOW Proceedings Search </h3>
<form method=post action="oowpapersearch.jsp">
Search for
<input type=text size=15 maxlength=25 name="query" value=<%=
name.getValue() %>>
in
<select name="tagvalue">
<option value="authors">Author(s)
<option value="abstract">Abstract
<option value="title">Title
<option value="company">Company
<option value="track">Track
</select>
<input type=submit value="Search">
<p><b>Display</b><br>
Author(s)<input type="radio" name="section" value="authors">
Abstract <input type="radio" name="section" value="abstract">
Title <input type="radio" name="section" value="title" checked>
Company <input type="radio" name="section" value="company">
Track <input type="radio" name="section" value="track">
</form>
Case Study: Searching XML-Based Conference Proceedings
7-64 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</center>
<%
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver() );
info.put ("user", "ctxdemo");
info.put ("password","ctxdemo");
conn = DriverManager.getConnection(connStr,info);
stmt = conn.createStatement();
String theQuery = request.getParameter("query")+"
INPATH(paper/"+request.getParameter("tagvalue")+")";
String tagValue = request.getParameter("tagvalue");
String sectionValue = request.getParameter("section");
// select p.papers.extract('/paper/authors').getStringVal()
// from oowpapers p
// where contains(papers,'language inpath(paper/abstract)')>0
String myQuery = "select
p.papers.extract('/paper/"+request.getParameter("section")+"/text()').getStringV
al() from oowpapers p where contains(papers,'"+theQuery+"')>0";
rset = stmt.executeQuery(myQuery);
String color = "ffffff";
String myDesc = null;
int items = 0;
while (rset.next()) {
myDesc = (String)rset.getString(1);
items++;
if (items == 1) {
%>
<center>
<table border="0">
<tr bgcolor="#6699CC">
<th><%= sectionValue %></th>
</tr>
<% } %>
<tr bgcolor="#<%= color %>">
<td> <%= myDesc %></td>
Frequently Asked Questions About Oracle Text
Searching XML Data with Oracle Text 7-65
</tr>
<%
if (color.compareTo("ffffff") == 0)
color = "eeeeee";
else
color = "ffffff";
}
} catch (SQLException e) {
%>
<b>Error: </b> <%= e %><p>
<%
} finally {
if (conn != null) conn.close();
if (stmt != null) stmt.close();
if (rset != null) rset.close();
}
%>
</table>
</center>
</body></html>
<%
}
%>
Frequently Asked Questions About Oracle Text
This Frequently Asked Questions (FAQs) section is divided into the following
categories:
I FAQs: General Questions About Oracle Text
I FAQs: Searching Attribute Values with Oracle Text
I FAQs: Searching XML Documents in CLOBs Using Oracle Text
FAQs: General Questions About Oracle Text
Can I Use a CONTAINS() Query with an XML Function to Extract an XML
Fragment?
Answer: Yes you can. See "Querying XML Data: Use CONTAINS or existsNode()?"
on page 7-38.
Frequently Asked Questions About Oracle Text
7-66 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Can XML Documents Be Queried Like Table Data?
I know that an intact XML document can be stored in a CLOB in Oracles XML
solution.
Can XML documents stored in a CLOB or a BLOB be queried like table schema? For
example:
[XML document stored in BLOB]...<name id="1111"><first>lee</first>
<sencond>jumee</second></name>...
Can value (lee, jumee) be queried by elements, attributes, and the structure of
XML document?
Answer: Using Oracle Text, you can nd this document with a queries such as:
lee within first
jumee within second
1111 within name@id
You can combine these like this:
lee within first and jumee within second, or
(lee within first) within name.
For more information, please read the Oracle Text Technical Overview available on
OTN at http://otn.oracle.com/products/text
Can I Edit Individual XML Elements?
If some element or attribute is inserted, updated, or deleted, must the whole
document be updated? Or can insert, update, and delete function as in table
schema?
Answer: Oracle Text indexes CLOB and BLOB, and this has no knowledge about
XML specically, so you cannot really change individual elements. You have to edit
the document as a whole.
How Are XML Files Locked in CLOBs and BLOBs?
About locking, if we manage an XML document stored in a CLOB or a BLOB, can
anyone access the same XML document?
Answer: Just like any other CLOB, if someone is writing to the CLOB, they have it
locked and nobody else can write to the CLOB. Other users can read it, but not write
to it. This is basic LOB behavior.
Frequently Asked Questions About Oracle Text
Searching XML Data with Oracle Text 7-67
An alternative is to decompose the XML document and store the information in
relational elds. Then you can modify individual elements, have element-level
simultaneous access, and so on. In this case, using something called the
USER_DATASTORE and PL/SQL, you can reconstitute the document to XML for text
indexing. Then, you can search the text as if it were XML, but manage the data as if
it were relational data. Again, see the Oracle Text Technical Overview for more
information at: http://otn.oracle.com/products/text.
How Can I Search XML Documents and Return a Zone?
I need to store a large XML le, search it, and return a specic tagged area. Using
Oracle Text some of this is possible:
I I can store an XML le in a CLOB eld
I I can index it with ctxsys.context
I I can create <Zones> and <Fields> to represent the tags in my XML le Ex.
ctx_ddl.add_zone_section(xmlgroup,dublincore, dc);
I I can search for text within a zone or fieldEx. Select title frommytable where
CONTAINS(textField,some words WITHIN doubleness)
How do I return a zone or a eld based on a text search?
Answer: Oracle Text will only return the hits. You can use Oracle Text doc service
to highlight or mark up the section, or you can store the CLOB in an XMLType
column and use the extract() function.
How Do I Load XML Documents into the Database?
How do I insert XML documents into a database? I need to insert the XML
document as-is in column of datatype CLOB into a table.
Answer: Oracle's XML SQL Utility for Java offers a command-line utility that can be
used for loading XML data. More information can be found on the XML SQL Utility
at the following Web site:
http://otn.oracle.com/tech/xml
as well as in Chapter 7, "XML SQL Utility (XSU)".
You can insert the XML documents as you would any text le. There is nothing
special about an XML-formatted le from a CLOB perspective.
Frequently Asked Questions About Oracle Text
7-68 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
How Do I Search XML Documents with Oracle Text?
Can Oracle Text be used to index and search XML stored in CLOBs? Howcan we get
started?
Answer: Versions of Oracle Text before Oracle8i Release 2 (8.1.6) only allowed
tag-based searching. The current version allows for XML structure and attribute
based searching. There is documentation on how to have the index built and the
SQL usage in the Oracle Text documentation.
How Do I Search XML Using the WITHIN Operator?
I have this XML code:
<person>
<name>efrat</name>
<childrens>
<child>
<id>1</id>
<name>keren</name>
</child>
</childrens>
</person>
How do I nd the person who has a child name keren but not the person's name
keren? This assumes I dened every tag with the add_zone_section that can be
nested and can include themselves.
Answer: Use (keren within name) within child.
Where Can I Find Examples of Using Oracle Text to Search XML?
Answer: See the following manuals:
I Oracle Text Application Developers Guide
I Oracle Text Reference
Does Oracle Text Automatically Recognize XML Tags?
Can Oracle Text recognize the tags in my XML document or do I have to use the
add_field_section command for each tag in the XML document? My XML
documents have hundreds of tags. Is there an easy way to do this?
See Also: Oracle Text Reference.
Frequently Asked Questions About Oracle Text
Searching XML Data with Oracle Text 7-69
Answer: Which version of the database are you using? I believe you need to use
that command for Oracle8 release 8.1.5 but not in Oracle8i release 2 (8.1.6). You can
use AUTO_SECTION_GROUP in Oracle8i release 2 (8.1.6).
XSQL Servlet ships with a complete (albeit simple from the Oracle Text standpoint)
example of a SQL script that creates a complex XML datagram out of object types,
and then creates an Oracle Text index on the XML document fragment stored in the
Insurance Claim type.
If you download the XSQL Servlet, and look at the le
./xsql/demo/insclaim.sql you'll be able to see the Oracle Text stuff at the
bottom of the le. One of the key new features in Oracle Text in Oracle8i release 2
(8.1.6) was the AUTO Section for XML.
Can I Do Range Searching with Oracle Text?
I have an XML document that I have stored in CLOB. I have also created the indexes
on the tags using section_group, and so on. One of the tags is <SALARY>
</SALARY>. I want to write a SQL statement to select all the records that have
salary of greater than 5000. How do I do this? I cannot use the WITHIN operator.
I want to interpret the value present in this tag as a number. This could be a oating
point number also since this is salary.
Answer: You cannot do this in Oracle Text. Range search is not really a text
operation. The best solution is to use the other Oracle XML parsing utilities to
extract the salary into a NUMBER eld. Then, you can use Oracle Text for text
searching, and normal SQL operators for the more structured elds, and achieve the
same results.
Can Oracle Text Do Section Extraction?
We are storing all our documents in XML format in a CLOB. Are there utilities
available in Oracle, perhaps Oracle Text, to retrieve the contents a eld at a time?
That is, given a eld name, can I get the text between tags, as opposed to retrieving
the whole document and traversing the structure?
Answer: Oracle Text does not do section extraction. See the XML SQL Utility for
this.
Can I Create a Text Index on Three Columns?
I have created a view based on seven to eight tables and it has columns like
custordnumber, product_dsc, qty, prdid, shipdate, ship_status, and so
on. I need to create an Oracle Text index on the three columns:
Frequently Asked Questions About Oracle Text
7-70 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I custordnumber
I product_dsc
I ship_status
Is there a way to create a Text index on these columns?
Answer: The short answer is yes. You have two options:
1. Use the USER_DATASTORE object to create a concatenated eld on the y
during indexing; or
2. Concatenate your elds and store them in an extra CLOB eld in one of your
tables. Then, create the index on the CLOB eld. If you're using Oracle8i release
2 (8.1.6) or higher, then you also have the option of placing XML tags around
each eld prior to concatenation. This gives you the capability of searching
within each eld.
How Fast Is Oracle9i at Indexing Text? Can I Just Enable Boolean Searches?
We are using mySQL to do partial indexing of 9 million Web pages a day. We are
running on a 4-processor Sparc 420 and are unable to do full text indexing. Can
Oracle8i or Oracle9i do this?
We are not interested in transactional integrity, applying any special lters to the
text pages, or in doing any other searching other than straight boolean word
searches (no scoring, no stemming, no fuzzy searches, no proximity searches, and so
on).
I have are the following questions:
I Will Oracle8i or Oracle9i be any faster at indexing text than mySQL?
I If so, is there a way to disable all the features of text indexing except for boolean
word searches?
Answer: Yes. Oracle Text can create a full-text index on 9 million Web pages - and
pretty quickly. In a benchmark on a large Sun box, we indexed 100 GB of Web pages
(about 15 million) in 7 hours. We can also do partial indexing through regular DML
or (in Oracle9i) through partitioning.
You can do indexing lite to some extent by disabling theme indexing. You do not
need to lter documents if they are already in ASCII, HTML, or XML, and most
common expansions, like fuzzy, stemming, and proximity, are done at query time.
Frequently Asked Questions About Oracle Text
Searching XML Data with Oracle Text 7-71
FAQs: Searching Attribute Values with Oracle Text
Can I Build Text Indexes on Attribute Values?
Currently Oracle Text has the option to create indexes based on the content of a
section group. But most XML elements are of the type Element. So, the only option
for searching would be attribute values. Can I build indexes on attribute values?
Answer: Oracle8 release 8.1.6 and higher allowattribute indexing. See the following
site:
http://otn.oracle.com/products/intermedia/htdocs/text_trainin
g_816/Samples/imt_816_techover.html#SCN
FAQs: Searching XML Documents in CLOBs Using Oracle Text
How Can I Search Different XML Documents Stored in CLOBs?
I store XML in CLOBs and use the DOM or SAX parsers to reparse the XML later as
needed. How can I search this document repository? Oracle Text seems ideal. Do
you have an example of setting this up using interMedia in Oracle8i, demonstrating
how to dene the XML_SECTION_GROUP and where to use a ZONE as opposed to a
FIELD, and so on? For example:
How would I dene interMedia parameters so that I would be able to search my
CLOB column for records that had the values aorta and damage using the
following XML (the DTD of which is implied)
WellKnownFileName.gif <keyword>echo</keyword>
<keyword>cardiogram aorta</keyword>
This is an image of the vessel damage.
Answer: Oracle8i release 2 (8.1.6) and higher allow searching within attribute text.
That's something like: state within book@author. Oracle now offers attribute
value sensitive search, more like the following:
state within book[@author = Eric]:
begin ctx_ddl.create_section_group('mygrp','basic_section_group');
ctx_ddl.add_field_section('mygrp','keyword','keyword');
ctx_ddl.add_field_section('mygrp','caption','caption');
end;
create index myidx on mytab(mytxtcolumn)indextype is ctxsys.contextparameters
Frequently Asked Questions About Oracle Text
7-72 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
('section group mygrp');
select * from mytab where contains(mytxtcolumn, 'aorta within keyword')>0;
options:
I Use XML section group instead of basic section group if your tags have
attributes or you need case-sensitive tag detection.
I Use zone sections instead of eld sections if your sections overlap, or if you
need to distinguish between instances. For instance, if keywords is a eld
section, then (aorta and echo cardiogram) within keywords nds
the document. If it is a zone section, then it does not, because they are not in the
SAME instance of keywords.
How Do I Store an XML Document in a CLOB Using Oracle Text?
I need to store XML les, which are currently on the le system, in the database. I
want to store them as whole documents; that is, I do not want to break the
document down by tags and then store the info in separate tables or elds. Rather, I
want to have a universal table, that I can use to store different XML documents. I
think internally it will be stored in a CLOB type of eld. My XML les will always
contain ASCII data.
Can this be done using Oracle Text? Should we be using Oracle Text or Oracle Text
Annotator for this? I downloaded Annotator from OTN, but I could not store XML
documents in the database.
I am trying to store XML documents in a CLOB column. Basically I have one table
with the following denition:
CREATE TABLE xml_store_testing
(
xml_doc_id NUMBER,
xml_doc CLOB )
I want to store my XML document in an xml_doc eld.
I have written the following PL/SQL procedure, to read the contents of the XML
document. The XML document is available on the le system and contains just
ASCII data, no binary data.
CREATE OR REPLACE PROCEDURE FileExec
(
p_Directory IN VARCHAR2,
p_FileName IN VARCHAR2)
AS v_CLOBLocator CLOB;
v_FileLocator BFILE;
Frequently Asked Questions About Oracle Text
Searching XML Data with Oracle Text 7-73
BEGIN
SELECT xml_doc
INTO v_CLOBLocator
FROM xml_store_testing
WHERE xml_doc_id = 1
FOR UPDATE;
v_FileLocator := BFILENAME(p_Directory, p_FileName);
DBMS_LOB.FILEOPEN(v_FileLocator, DBMS_LOB.FILE_READONLY);
dbms_output.put_line(to_char(DBMS_LOB.GETLENGTH(v_FileLocator)));
DBMS_LOB.LOADFROMFILE(v_CLOBLocator, v_FileLocator,
DBMS_LOB.GETLENGTH(v_FileLocator));
DBMS_LOB.FILECLOSE(v_FileLocator);
END FileExec;
Answer: Put the XML documents into your CLOB column, then add an Oracle Text
index on it using the XML_SECTION_GROUP. See the documentation and overview
material at this Web site: http://otn.oracle.com/products/intermedia.
Is Storing XML in CLOBs Affected by Character Set?
When I put my XML documents in a CLOB column, then add an Oracle Text index
using the XML section-group, it executes successfully. But when I select from the
table I see unknown characters in the table in CLOB eld. Could this be because of
the character set difference between operating system, where XML le resides, and
database, where CLOB data resides?
Answer: Yes. If the character sets are different then you probably have to pass the
data through UTL_RAW.CONVERT to do a character set conversion before writing to
the CLOB.
Can I Only Insert Structured Data When the Table is Created?
I need to insert data in the database from an XML le. Currently I can only insert
structured data with the table already created. Is this correct?
I am working in a law project where we need to store laws containing structured
data and unstructured data, and then search the data using Oracle Text. Can I insert
unstructured data too? Or do I need to develop a custom application to do it? Then,
if I have the data stored with some structured parts and some unstructured parts,
can I use Oracle Text to search it? If I stored the unstructured part in a CLOB, and the
CLOB has tags, how can I search only data in a specic tag?
Answer: Consider usingOracle9iFS, which enables you to break up a document and
store it across tables and in a LOB. Oracle Text can perform data searches with tags
and is knowledgeable about the hierarchical XML structure. FromOracle8i release 2
Frequently Asked Questions About Oracle Text
7-74 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
(8.1.6), Oracle Text has had this capability, along with name/value pair attribute
searches.
Can I Break an XML Document Without Creating a Custom Development?
Is document breaking possible if I don't create a custom development? Although
Oracle Text does not understand hierarchical XML structure, can I do something
like this?
<report>
<day>yesterday</day> there was a disaster <cause>hurricane</cause>
</report>
Indexing with Oracle Text, I would like to search LOBs where cause was hurricane.
Is this possible?
Answer: You can perform that level of searching with the current release of Oracle
Text. Currently, to break a document up you have to use the XML Parser with XSLT
to create a style sheet that transforms the XML into DDL. Oracle9iFS gives you a
higher level interface.
Another technique is to use a JDBC program to insert the text of the document or
document fragment into a CLOB or LONG column, then do the searching using the
CONTAINS() operator after setting up the indexes.
What Is the Syntax for Creating a Substring Index with XML_SECTION_GROUP?
I have a CLOB column that has an existing XML_SECTION_GROUP index on certain
tags within the XML content of the CLOB, as follows:
begin
ctx_ddl.create_section_group('XMLDOC','XML_SECTION_GROUP');
end;
/
begin
ctx_ddl.add_zone_section ('XMLDOC','title','title');
ctx_ddl.add_zone_section('XMLDOC','keywords','keywords');
ctx_ddl.add_zone_section('XMLDOC','author','author');
end;
/
create index xmldoc_idx on xml_documents(xmldoc)
indextype is ctxsys.context
parameters ('section group xmldoc') ;
I need to search on the 'author' zone section by the rst letter only. I believe I should
use a substring index but I am unsure of the syntax to create a substring index.
Frequently Asked Questions About Oracle Text
Searching XML Data with Oracle Text 7-75
Especially when I have already declared a SECTION_GROUP preference on this
column and I would also need to create a WORDLIST preference.
Answer. The main problem here is that you cannot apply that fancy substring
processing just to the author section. It will apply to everything, which will
probably blow up the index size. Anything you do will require reindexing the
documents, so you cannot really get around having to rebuild the index entirely.
Here are various ways to solve your problem:
1. Do nothing. Query just like: Z%WITHIN AUTHOR
Pro: You do not have to rebuild the index.
Con: The query is slow. Some queries cannot be executed due to wildcard
maxterms limits.
2. Create a wordlist preference with PREFIX_INDEX set to TRUE,
PREFIX_MIN_LENGTH set to 1, and PREFIX_MAX_LENGTH set to 1. The
query looks like: Z%WITHIN AUTHOR
Pro: This is a moderately fast query.
Con: You must use Oracle8i Release 3 (8.1.7) or higher or you will get junk
from words from other sections.
3. As in the preceding, plus make AUTHOR, KEYWORDS, TITLE eld sections.
Pro: This faster query than 2.
Con: The eld sections are less exible with regards to. nesting and repeating
occurrences.
4. Use a user_datastore or procedure_lter to transform the data so that:
<AUTHOR>Steven King</AUTHOR>
becomes
<AUTHORINIT>AIK</AUTHORINIT><AUTHOR>Steven King<AUTHOR>
Use eld section for AUTHORINIT and query becomes:
AIK within AUTHORINIT
I used AIK instead of just K so that you do not have to make I and A
non-stopwords.
Pro: This is the fastest query and the smallest index.
Frequently Asked Questions About Oracle Text
7-76 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Con: It involves the most work as you have to massage the data so it slows
down indexing.
Why Does the XML Search for Topic X with Relevance Y Give Wrong Results?
We are using Sun SPARC Solaris 5.8, Oracle8i Enterprise Edition Release 3
(8.1.7.2.0), Oracle Text. We are indexing XML documents that contain attributes
within the XML tags. One of the sections in the XML is a list of subjects associated
with the document. Each subject has a relevance associated with it. We want to
search for topic x with relevance y but we get the wrong results. For example: The
data in some of the rows look like this, considering subject PA:
DOC 1 --> Story_seq_num = 561106
<ne-metadata.subjectlist>
<ne-subject code="PA" source="NEWZ" relevance="50" confidence="100"/>
<ne-subject code="CONW" source="NEWZ" relevance="100" confidence="100"/>
<ne-subject code="LENF" source="NEWZ" relevance="100" confidence="100"/>
<ne-subject code="TRAN" source="NEWZ" relevance="100" confidence="100"/>
</ne-metadata.subjectlist>
DOC 2 --> Story_seq_num =561107
<ne-metadata.subjectlist>
<ne-subject code="CONW" source="NEWZ" relevance="100" confidence="100"/>
...
If users wants subject PA with relevance = 100, only DOC 2 should be returned.
Here is a test case showing the results:
Are these the expected results?
TABLE
drop table t_stories1 ;
create table t_stories1 as select * from t_Stories_bck
where story_Seq_num in (561114,562571,562572,561106,561107);
INDEX SECTIONS
BEGIN
-- Drop the preference if it already exists
CTX_DDL.DROP_SECTION_GROUP('sg_nitf_story_body2');
END;
/
BEGIN
--Define a section group
ctx_ddl.create_section_group ('sg_nitf_story_body2','xml_section_group');
-- Create field sections for headline and body
ctx_ddl.add_field_section('sg_nitf_story_body2','HL','hedline',true);
Frequently Asked Questions About Oracle Text
Searching XML Data with Oracle Text 7-77
ctx_ddl.add_field_section('sg_nitf_story_body2','ST','body.content', true);
--Define attribute sections for the source fields
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'P', 'ne-provider@id');
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'C', 'ne-publication@id');
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'S', 'ne-publication@section');
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'D', 'date.issue@norm');
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'SJ', 'ne-subject@code');
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'SJR', 'ne-subject@relevance');
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'CO', 'ne-company@code');
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'TO', 'ne-topic@code');
ctx_ddl.add_attr_section( 'sg_nitf_story_body2', 'TK', 'ne-orgid@value');
ENd;
/
creating the index
drop index ix_stories ;
CREATE INDEX ix_stories on T_STORIES1(STORY_BODY)
INDEXTYPE IS CTXSYS.CONTEXT
PARAMETERS ('SECTION GROUP sg_nitf_story_body2 STORAGE ixst_story_body ');
-- testing the index
--We are looking for the subject PA with relevance = 100
--query that gives us the correct results
SELECT STORY_SEQ_NUM, STORY_BODY FROM T_STORIES1 WHERE CONTAINS(STORY_BODY, 'PA
WITHIN SJ')>0;
--Query that gives us the wrong results
SELECT STORY_SEQ_NUM, STORY_BODY FROM T_STORIES1 WHERE CONTAINS(STORY_BODY, 'PA
WITHIN SJ AND 100 within SJR')>0;
The data in some of the rows look like this:
Story_seq_num = 561106
<ne-metadata.subjectlist>
<ne-subject code="PA" source="NEWZ" relevance="50" confidence="100"/>
<ne-subject code="CONW" source="NEWZ" relevance="100" confidence="100"/>
<ne-subject code="LENF" source="NEWZ" relevance="100" confidence="100"/>
<ne-subject code="TRAN source=NEWZ relevance=100
condence=100/>
</ne-metadata.subjectlist>
Frequently Asked Questions About Oracle Text
7-78 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Story_seq_num =561107
<ne-metadata.subjectlist>
<ne-subject code="CONW" source="NEWZ" relevance="100" confidence="100"/>
...
We are looking for the subject PA with relevance = 100
Only Story_seq_num = 561107 should be returned
The results are wrong because we wanted the subjects PA that have relevance =100.
We get back story_seq_num=561106 that has relevance = 50 <ne-subject code="PA
source=NEWZ relevance=50 condence=100/>
SQL> connect sosa/sosa
Connected.
SQL> select object_name, object_type from user_objects;
OBJECT_NAME
--------------------------------------------------------------------------------
OBJECT_TYPE
------------------
IX_STORIES
INDEX
SYS_LOB0000025364C00005$$
LOB
SYS_LOB0000025364C00009$$
LOB
OBJECT_NAME
--------------------------------------------------------------------------------
OBJECT_TYPE
------------------
SYS_LOB0000025364C00014$$
LOB
SYS_LOB0000025364C00016$$
LOB
T_STORIES1
TABLE
6 rows selected.
SQL> drop index ix_stories force;
Index dropped....
Frequently Asked Questions About Oracle Text
Searching XML Data with Oracle Text 7-79
Answer. Oracle8i Release 3(8.1.7) is not able to this kind of search. You need the
PATH section group in Oracle9i Release 1 (9.0.1), which has a much more
sophisticated understanding of such relationships. To do this in 8.1.7 you would
have to re-format the documents (possibly through a procedure lter or user
datastore), use zone sections, and nested withins, so that:
<A B="C" D="E">...
became
<A><B>C</B><D>E</D>...
and queries are like:
(C within B and E within D) within A in 9.0.1, you should be able to use
PATH_SECTION_GROUP on the unmodied data, with a query like:
haspath(//ne-subject[@code = "PA" and @relevance = "100"])
Frequently Asked Questions About Oracle Text
7-80 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Part III
Using XMLType APIs to Manipulate XML
Data
Part III of this manual introduces you to ways you can use Oracle XML DB
XMLType Pl/SQL and Java APIs to access and manipulate XML data. Part III
contains the following chapters:
I Chapter 8, "PL/SQL API for XMLType"
I Chapter 9, "Java API for XMLType"
PL/SQL API for XMLType 8-1
8
PL/SQL API for XMLType
This chapter describes the use of the APIs for XMLType in PL/SQL. It contains the
following sections:
I Introducing PL/SQL APIs for XMLType
I PL/SQL DOM API for XMLType (DBMS_XMLDOM)
I PL/SQL Parser API for XMLType (DBMS_XMLPARSER)
I PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
Introducing PL/SQL APIs for XMLType
8-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing PL/SQL APIs for XMLType
This chapter describes the PL/SQL Application Program Interfaces (APIs) for
XMLType. These include the following:
I PL/SQL DOM API for XMLType (package DBMS_XMLDOM): For accessing
XMLType objects. You can access both XML schema-based and
non-schema-based documents. Before database startup, you must specify the
read-from and write-to directories in the initialization.ORA le for example:
UTL_FILE_DIR=/mypath/insidemypath
The read-from and write-to les must be on the server le system.
I PL/SQL XML Parser API for XMLType (package DBMS_XMLPARSER): For
accessing the contents and structure of XML documents.
I PL/SQL XSLT Processor for XMLType (package DBMS_XSLPROCESSOR): For
transforming XML documents to other formats using XSLT.
Backward Compatibility with XDK for PL/SQL, Oracle9i Release 1 (9.0.1)
This release maintains support for the XDK for PL/SQL:
I XML Parser for PL/SQL
I XSLT Processor for PL/SQL
to ensure backward compatibility. Therefore, most applications written for Oracle9i
Release 1 (9.0.1) XML Parser for PL/SQL and XSLT Processor for PL/SQL instances
will need no changes. In this release, new applications built with the updated
PL/SQL DOM and the extensions to XMLType API do not need the XDKs XML
Parser for PL/SQL and XSLT Processor for PL/SQL.
If Your Application Uses Character-Set Conversions and File Systems
Applications that extensively use character-set conversions and le system
interaction require some changes. The changes needed are due to the UTL_FILE
package limitations, such as read/write to les in the UTL_FILE_DIR specied at
database start-up.
See Also: Oracle9i XML Developers Kits Guide - XDK
Introducing PL/SQL APIs for XMLType
PL/SQL API for XMLType 8-3
Differences Between PL/SQL API for XMLType and XDK for PL/SQL
This section explains differences between PL/SQL APIs native to Oracle XML DB
and PL/SQL APIs available in XML Developers Kits (XDK).
I PL/SQL API s for XMLType. Use PL/SQL APIs for XMLType for developing
applications that run on the server. PL/SQL APIs for XMLTYpe in Oracle XML
DB provide native XML support within the database.
I OracleXML XDK for PL/SQL. Use Oracle XDK for PL/SQL for middle-tier and
client-side XML support.
PL/SQL APIs For XMLType Features
The PL/SQL APIs for XMLType allow you to perform the following tasks:
I Create XMLType tables, columns, and views
I Access XMLType data
I Manipulate XMLType data
Note: In this release, the PL/SQL packages DBMS_XMLDOM,
DBMS_XMLPARSER, and DBMS_XSLPROCESSOR, replace the
previous XDK packages XMLDOM, XMLPARSER, and
XSLPROCESSOR.
Note: Oracle XML DB APIs are natively integrated in Oracle9i
Release 2 (9.2) and not available separately. Oracle XML DB APIs
cannot be downloaded from Oracle Technology Network (OTN).
However, Oracle XDKs are available separately for download from
OTN: http://otn.oracle.com/tech/xml/content.html.
See Also: "PL/SQL DOM API for XMLType (DBMS_XMLDOM)"
on page 8-5
Introducing PL/SQL APIs for XMLType
8-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Lazy XML Loading (Lazy Manifestation)
Because XMLType provides an in-memory or virtual Document Object Model
(DOM), it can use a memory conserving process called lazy XML loading, also
sometimes referred to as lazy manifestation. This process optimizes memory usage by
only loading rows of data as they are requested. It throws away
previously-referenced sections of the document if memory usage grows too large.
Lazy XML loading supports highly scalable applications that have many concurrent
users needing to access large XML documents.
XMLType Datatype Now Supports XML Schema
The XMLType datatype has been enhanced in this release to include support for
XML schemas. You can create an XML schema and annotate it with XML to object-
relational mappings. To take advantage of the PL/SQL DOM API, rst create an
XML schema and register it. Then when you create XMLType tables and columns,
you can specify that these conform to the XML schema you dened and registered
with Oracle XML DB.
With PL/SQL APIs for XMLType You Can Modify and Store XML Elements
While typical XML parsers give read access to XML data in a standard way, they do
not provide a way to modify and store individual XML elements.
What are Elements? An element is the basic logical unit of an XML document and
acts as a container for other elements such as children, data, attributes, and their
values. Elements are identied by start-tags, as in <name>, and end-tags, as in
</name>, or in the case of empty elements, <name/>.
What is a DOM Parser? An embedded DOM parser accepts an XML-formatted
document and constructs an in-memory DOM tree based on the documents
structure. It then checks whether or not the document is well-formed and optionally
whether it complies with a specic Document Type Denition (DTD). A DOM
parser also provides methods for traversing the DOM tree and return data from it.
See Also:
I "Key Features of Oracle XML DB" on page 8-2 in Chapter 1,
"Introducing Oracle XML DB", for an overview of the Oracle
XML DB architecture and new features.
I Chapter 4, "Using XMLType"
I Oracle9i XML API Reference - XDK and Oracle XML DB
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-5
If you use the PL/SQL DOM API, you can use the NamedNodeMap methods to
retrieve elements from an XML le.
Server-Side Support PL/SQL APIs for XMLType support processing on the server
side only. Support for client-side processing is not provided in this release.
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Introducing W3C Document Object Model (DOM) Recommendation
Skip this section if you are already familiar with the generic DOM specications
recommended by the World Wide Web Consortium (W3C).
The Document Object Model (DOM) recommended by the W3C is a universal API
to the structure of XML documents. It was originally developed to formalize
Dynamic HTML, which allows animation, interaction and dynamic updating of
Web pages. DOM provides a language and platform-neutral object model for Web
pages and XML document structures in general. The DOM describes language and
platform-independent interfaces to access and to operate on XML components and
elements. It expresses the structure of an XML document in a universal,
content-neutral way. Applications can be written to dynamically delete, add, and
edit the content, attributes, and style of XML documents. Additionally, the DOM
makes it possible to write applications that work properly on all browsers and
servers and on all platforms.
A brief summary of the state of the DOM Recommendations is provided in this
section for your convenience.
W3C DOM Extensions Not Supported in This Release
The only extensions to the W3C DOM API not supported in this release are those
relating to client-side le system input and output, and character set conversions.
This type of procedural processing is available through the SAX interface.
Supported W3C DOM Recommendations
All Oracle XML DB APIs for accessing and manipulating XML comply with
standard XML processing requirements as approved by the W3C. PL/SQL DOM
supports Levels 1 and 2 from the W3C DOM specications.
I In Oracle9i Release 1 (9.0.1), the XDK for PL/SQL implemented DOM Level 1.0
and parts of DOM Level 2.0.
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I In Oracle9i Release 2 (9.2), the PL/SQL API for XMLType implements DOM
Levels 1.0 and Level 2.0 Core, and is fully integrated in Oracle9i database
through extensions to the XMLType API.
The following briey describe each level:
I DOM Level 1.0. The rst formal Level of the DOM specications, completed in
October 1998. Level 1.0 denes support for XML 1.0 and HTML.
I DOMLevel 2.0. Completed in November 2000, Level 2.0 extends Level 1.0 with
support for XML 1.0 with namespaces and adds support for Cascading Style
Sheets (CSS) and events (user-interface events and tree manipulation events),
and enhances tree manipulations (tree ranges and traversal mechanisms).
I DOM Level 3.0. Currently under development, Level 3.0 will extend Level 2.0
by nishing support for XML 1.0 with namespaces (alignment with the XML
Infoset and support for XML Base) and will extend the user interface events
(keyboard). It will also add support for abstract schemas (for DTDs and XML
schema), and the ability to load and save a document or an abstract schema. It
is exploring further mixed markup vocabularies and the implications on the
DOM API (Embedded DOM), and it will support XPath.
Difference Between DOM and SAX
The generic APIs for XML can be classied in two main categories:
I Tree-based. The DOM is the primary generic tree-based API for XML.
I Event-based. SAX (Simple API for XML) is the primary generic event-based
programming interface between an XML parser and an XML application.
The DOM works by creating objects. These objects have child objects and
properties, and the child objects have child objects and properties, and so on.
Objects are referenced either by moving down the object hierarchy or by explicitly
giving an HTML element an ID attribute. For example:
<img src="employee_jdoe.gif" ID="0123jdoe">
Examples of structural manipulations are:
I Reordering elements
I Adding or deleting elements
I Adding or deleting attributes
I Renaming elements
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-7
PL/SQL DOM API for XMLType (DBMS_XMLDOM): Features
The default behavior for the PL/SQL DOMAPI for XMLType (DBMS_XMLDOM) is
as follows:
I Produces a parse tree that can be accessed by DOM APIs.
I The parser is validating if a DTD is found; otherwise, it is non-validating.
I An application error is raised if parsing fails.
I The types and methods described in this document are made available by the
PL/SQL package DBMS_XMLPARSER.
DTD validation follows the same rules that are exposed for the XML Parser
available through the XDK in Oracle9i Release 1(9.0.1) with the only difference
being that the validation occurs when the object document is manifested. For
example, if lazy manifestation is used, the document will be validated when it is
used.
Oracle XML DB extends the Oracle XML development platform beyond SQL
support for XML text and storage and retrieval of XML data. In this release, you can
operate on XMLType instances using the DOM in PL/SQL and Java. Thus, you can
directly manipulate individual XML elements and data using the language best
suited for your application or plug-in.
This release has updated the PL/SQL DOM API to exploit a C-based representation
of XML in the server and to operate on XML schema-based XML instances. Oracle
XML DB PL/SQL DOMAPI for XMLType and Java DOMAPI for XMLType comply
with the W3C DOM Recommendations to dene and implement structured storage
of XML in relational or object-relational columns and as in-memory instances of
XMLType. See "Using PL/SQL DOM API for XMLType: Preparing XML Data" on
page 8-9, for a description of W3C DOM Recommendations.
XML Schema Support
PL/SQL DOM API for XMLType introduces XML schema support. Oracle XML DB
uses annotations within an XML schema as metadata to determine both an XML
documents structure and its mapping to a database schema.
Note: For backward compatibility and for exibility, the PL/SQL
DOM supports both XML schema-based documents and non-
schema-based documents.
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
When an XML schema is registered with Oracle XML DB, the PL/SQL DOM API
for XMLType builds an in-memory tree representation of the XML document as a
hierarchy of node objects, each with its own specialized interfaces. Most node object
types can have child node types, which in turn implement additional, more
specialized interfaces. Some node types can have child nodes of various types,
while some node types can only be leaf nodes and cannot have children nodes
under them in the document structure.
Enhanced Performance
Additionally, Oracle XML DB uses the DOM to provide a standard way to translate
data from multiple back-end data sources into XML and vice versa. This eliminates
the need to use separate XML translation techniques for the different data sources in
your environment. Applications needing to exchange XML data can use one native
XML database to cache XML documents. Thus, Oracle XML DB can speed up
application performance by acting as an intermediate cache between your Web
applications and your back-end data sources, whether in relational databases or in
disparate le systems.
Designing End-to-End Applications Using XDK and Oracle XML DB
When you build applications based on Oracle XML DB, you do not need the
additional components in the XDKs. However, you can mix and match XDK
components with Oracle XML DB to deploy a full suite of XML-enabled
applications that run end-to-end. For example, you can use features in XDK for:
I Simple API for XML (SAX) interface processing. SAX is an XML standard
interface provided by XML parsers and used by procedural and event-based
applications.
I DOM interface processing for structural and recursive object-based processing.
Oracle XDKs contain the basic building blocks for creating applications that run on
the client, in a browser or plug-in, for example, for reading, manipulating,
transforming and viewing XML documents. To provide a broad variety of
deployment options, Oracle XDKs are also available for Java, Java beans, C, C++,
and PL/SQL. Unlike many shareware and trial XML components, Oracle XDKs are
fully supported and come with a commercial redistribution license.
Oracle XDK for Java consists of these components:
I XML Parsers: Supports Java, C, C++ and PL/SQL, the components create and
parse XML using industry standard DOM and SAX interfaces.
See Also: Chapter 9, "Java API for XMLType"
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-9
I XSLT Processor: Transforms or renders XML into other text-based formats such
as HTML.
I XML Schema Processor: Supports Java, C, and C++, allows use of XML simple
and complex datatypes.
I XML Class Generator: Automatically generates Java and C++ classes from
DTDs and Schemas to send XML data from Web forms or applications.
I XML Transviewer Java Beans: Displays and transforms XML documents and
data using Java components.
I XML SQL Utility: Supports Java, generates XML documents, DTDs and
Schemas from SQL queries.
I TransXUtility. Loads data encapsulated in XML into the database with
additional functionality useful for installations.
I XSQL Servlet: Combines XML, SQL, and XSLT in the server to deliver dynamic
web content.
Using PL/SQL DOM API for XMLType: Preparing XML Data
To take advantage of the Oracle XML DB DOM APIs, you must follow a few
processes to allow Oracle XML DB to develop a data model from your XML data.
This is true for any language, although PL/SQL is the focus of this chapter. The
process you use depends on the state of your data and your application
requirements.
To prepare data for using PL/SQL DOM APIs in Oracle XML DB, you must:
1. Create a standard XML schema if you do not already use one. Annotate the
XML schema with denitions for the SQL objects dened in your relational or
object-relational database.
2. Register your XML schema to generate the necessary database mappings.
You can then:
I Use XMLType views to wrap existing relational or object-relational data in XML
formats. This enables an XML structure to be created that can be accessed by
your application. See also "Wrapping Existing Data into XML with XMLType
Views" on page 8-11.
I Insert XML documents (and fragments) into XMLType columns.
See Also: Oracle9i XML Developers Kits Guide - XDK
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Use Oracle XML DB DOM PL/SQL and Java APIs to access and manipulate
XML data stored in XMLType columns and tables.
Creating and registering a standard XML schema allows your compliant XML
documents to be inserted into the database where they can be decomposed, parsed,
and stored in object-relational columns that can be accessed by your application.
Generating an XML Schema Mapping to SQL Object Types
An XML schema must be registered before it can be used or referenced in any
context. When you register an XML schema, elements and attributes declared
within it get mapped to separate attributes within the corresponding SQL object
types within the database schema.
After the registration process is completed, XML documents conforming to this
XML schema, and referencing it with its URL within the document, can be handled
by Oracle XML DB. Tables and columns for storing the conforming documents can
be created for root XML elements dened by this schema.
An XML schema is registered by using the DBMS_XMLSCHEMA package and by
specifying the schema document and its URL (also known as schema location). The
URL used here is a name that uniquely identies the registered schema within the
database and need not be the physical URL where the schema document is located.
Additionally, the target namespace of the schema is another URL (different fromthe
schema location URL) that species an abstract namespace within which the
elements and types get declared. An instance of an XML document should specify
both the namespace of the root element and the location (URL) of the schema that
denes this element.
When instances of documents are inserted into Oracle XML DB using path-based
protocols like HTTP or FTP, the XML schema to which the document conforms is
registered implicitly, if its name and location are specied and if it has not been
previously registered.
See Also: Chapter 5, "Structured Mapping of XMLType" for more
information and examples.
See Also:
I Oracle9i Supplied PL/SQL Packages and Types Reference
I Oracle9i XML API Reference - XDK and Oracle XML DB
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-11
DOM Fidelity for XML Schema Mapping
While elements and attributes declared within the XML schema get mapped to
separate attributes within the corresponding SQL object type, some encoded
information in an XML document is not represented directly. In order to guarantee
that the returned XML document is identical to the original document for purposes
of DOM traversals (referred to as DOM delity), a binary attribute called
SYS_XDBPD$ is added to all generated SQL object types. This attribute stores all
pieces of information that cannot be stored in any of the other attributes, thereby
ensuring DOM delity for XML documents stored in Oracle XML DB.
Data handled by SYS_XDBPD$ that is not represented in the XML schema mapping
include:
I Comments
I Namespace declaration
I Prex information
Wrapping Existing Data into XML with XMLType Views
To make existing relational and object-relational data available to your XML
applications, you create XMLType views, which provide a mechanism for wrapping
the existing data into XML formats. This exposes elements and entities, that can
then be accessed using the PL/SQL DOM APIs.
You register an XML schema containing annotations that represent the
bi-directional mapping from XML to SQL object types. Oracle XML DB can then
create an XMLType view conforming to this XML schema.
PL/SQL DOM API for XMLType (DBMS_XMLDOM) Methods
Table 81 lists the PL/SQL DOM API for XMLType (DBMS_XMLDOM) methods
supported in Release 2 (9.2.0.1).
Note: In this document, the SYS_XDBPD$ attribute has been
omitted in many examples for simplicity. However, the attribute is
always present in all SQL object types generated by the
schema-registration process.
See Also: Chapter 11, "XMLType Views"
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Non-Supported DBMS_XMLDOM Methods in Release 2 (9.2.0.2)
The following DBMS_XMLDOM methods are not supported in Release 2 (9.2.0.2):
I hasFeature
I getVersion
I setVersion
I getCharset
I setCharset
I getStandalone
I setStandalone
I writeExternalDTDToFile
I writeExternalDTDToBuffer
I writeExternalDTDToClob
Table 82 lists additional methods supported in Release 2 (9.2.0.2).
Table 81 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods
Group/Method Description
Node methods --
isNull() Tests if the node is NULL.
makeAttr() Casts the node to an Attribute.
makeCDataSection() Casts the node to a CDataSection.
makeCharacterData() Casts the node to CharacterData.
makeComment() Casts the node to a Comment.
makeDocumentFragment() Casts the node to a DocumentFragment.
makeDocumentType() Casts the node to a Document Type.
makeElement() Casts the node to an Element.
makeEntity() Casts the node to an Entity.
makeEntityReference() Casts the node to an EntityReference.
makeNotation() Casts the node to a Notation.
makeProcessingInstruction() Casts the node to a DOMProcessingInstruction.
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-13
makeText() Casts the node to a DOMText.
makeDocument() Casts the node to a DOMDocument.
writeToFile() Writes the contents of the node to a le.
writeToBuffer() Writes the contents of the node to a buffer.
writeToClob() Writes the contents of the node to a clob.
getNodeName() Retrieves the Name of the Node.
getNodeValue() Retrieves the Value of the Node.
setNodeValue() Sets the Value of the Node.
getNodeType() Retrieves the Type of the node.
getParentNode() Retrieves the parent of the node.
getChildNodes() Retrieves the children of the node.
getFirstChild() Retrieves the rst child of the node.
getLastChild() Retrieves the last child of the node.
getPreviousSibling() Retrieves the previous sibling of the node.
getNextSibling() Retrieves the next sibling of the node.
getAttributes() Retrieves the attributes of the node.
getOwnerDocument() Retrieves the owner document of the node.
insertBefore() Inserts a child before the reference child.
replaceChild() Replaces the old child with a new child.
removeChild() Removes a specied child from a node.
appendChild() Appends a new child to the node.
hasChildNodes() Tests if the node has child nodes.
cloneNode() Clones the node.
Named node map methods --
isNull() Tests if the NodeMap is NULL.
getNamedItem() Retrieves the item specied by the name.
setNamedItem() Sets the item in the map specied by the name.
Table 81 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
removeNamedItem() Removes the item specied by name.
item() Retrieves the item given the index in the map.
getLength() Retrieves the number of items in the map.
Node list methods --
isNull() Tests if the Nodelist is NULL.
item() Retrieves the item given the index in the nodelist.
getLength() Retrieves the number of items in the list.
Attr methods --
isNull() Tests if the Attribute Node is NULL.
makeNode() Casts the Attribute to a node.
getQualiedName() Retrieves the Qualied Name of the attribute.
getNamespace() Retrieves the NS URI of the attribute.
getLocalName() Retrieves the local name of the attribute.
getExpandedName() Retrieves the expanded name of the attribute.
getName() Retrieves the name of the attribute.
getSpeciied() Tests if attribute was specied in the owning
element.
getValue() Retrieves the value of the attribute.
setValue() Sets the value of the attribute.
C data section methods --
isNull()isNull() Tests if the CDataSection is NULL.
makeNode()makeNode() Casts the CDatasection to a node.
Character data methods --
isNull() Tests if the CharacterData is NULL.
makeNode() Casts the CharacterData to a node.
getData() Retrieves the data of the node.
setData() Sets the data to the node.
getLength() Retrieves the length of the data.
Table 81 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-15
substringData() Retrieves the substring of the data.
appendData() Appends the given data to the node data.
insertData() Inserts the data in the node at the given offSets.
deleteData() Deletes the data from the given offSets.
replaceData() Replaces the data from the given offSets.
Comment methods --
isNull() Tests if the comment is NULL.
makeNode() Casts the Comment to a node.
DOM implementation methods --
isNull() Tests if the DOMImplementation node is NULL.
hasFeature() Tests if the DOM implements a given feature. [Not
supported in this release]
Document fragment methods --
isNull() Tests if the DocumentFragment is NULL.
makeNode() Casts the Document Fragment to a node.
Document type methods --
isNull() Tests if the Document Type is NULL.
makeNode() Casts the document type to a node.
ndEntity() Finds the specied entity in the document type.
ndNotation() Finds the specied notation in the document type.
getPublicId() Retrieves the public ID of the document type.
getSystemId() Retrieves the system ID of the document type.
writeExternalDTDToFile() Writes the document type denition to a le.
writeExternalDTDToBuffer() Writes the document type denition to a buffer.
writeExternalDTDToClob() Writes the document type denition to a clob.
getName() Retrieves the name of the Document type.
getEntities() Retrieves the nodemap of entities in the Document
type.
Table 81 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
getNotations() Retrieves the nodemap of the notations in the
Document type.
Element methods --
isNull() Tests if the Element is NULL.
makeNode() Casts the Element to a node.
getQualiedName() Retrieves the qualied name of the element.
getNamespace() Retrieves the NS URI of the element.
getLocalName() Retrieves the local name of the element.
getExpandedName() Retrieves the expanded name of the element.
getChildrenByTagName() Retrieves the children of the element by tag name.
getElementsByTagName() Retrieves the elements in the subtree by element.
resolveNamespacePrex() Resolve the prex to a namespace uri.
getTagName() Retrieves the Tag name of the element.
getAttribute() Retrieves the attribute node specied by the name.
setAttribute() Sets the attribute specied by the name.
removeAttribute() Removes the attribute specied by the name.
getAttributeNode() Retrieves the attribute node specied by the name.
setAttributeNode() Sets the attribute node in the element.
removeAttributeNode() Removes the attribute node in the element.
normalize() Normalizes the text children of the element. [Not
supported in this release]
Entity methods --
isNull() Tests if the Entity is NULL.
makeNode() Casts the Entity to a node.
getPublicId() Retrieves the public Id of the entity.
getSystemId() Retrieves the system Id of the entity.
getNotationName() Retrieves the notation name of the entity.
Entity reference methods --
Table 81 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-17
isNull() Tests if the entity reference is NULL.
makeNode() Casts the Entity reference to NULL.
Notation methods --
isNull() Tests if the notation is NULL.
makeNode() Casts the notation to a node.
getPublicId() Retrieves the public Id of the notation.
getSystemId() Retrieves the system Id of the notation.
Processing instruction methods --
isNull() Tests if the processing instruction is NULL.
makeNode() Casts the Processing instruction to a node.
getData() Retrieves the data of the processing instruction.
getTarget() Retrieves the target of the processing instruction.
setData() Sets the data of the processing instruction.
Text methods --
isNull() Tests if the text is NULL.
makeNode() Casts the text to a node.
splitText() Splits the contents of the text node into 2 text nodes.
Document methods --
isNull() Tests if the document is NULL.
makeNode() Casts the document to a node.
newDOMDocument() Creates a new document.
freeDocument() Frees the document.
getVersion() Retrieves the version of the document. [Not
supported in this release]
setVersion() Sets the version of the document. [Not supported in
this release]
getCharset() Retrieves the Character set of the document. [Not
supported in this release]
Table 81 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
setCharset() Sets the Character set of the document. [Not
supported in this release]
getStandalone() Retrieves if the document is specied as standalone.
[Not supported in this release]
setStandalone() Sets the document standalone. [Not supported in
this release]
writeToFile() Writes the document to a le.
writeToBuffer() Writes the document to a buffer.
writeToClob() Writes the document to a clob.
writeExternalDTDToFile() Writes the DTD of the document to a le. [Not
supported in this release]
writeExternalDTDToBuffer() Writes the DTD of the document to a buffer. [Not
supported in this release]
writeExternalDTDToClob() Writes the DTD of the document to a clob. [Not
supported in this release]
getDoctype() Retrieves the DTD of the document.
getImplementation() Retrieves the DOM implementation.
getDocumentElement() Retrieves the root element of the document.
createElement() Creates a new element.
createDocumentFragment() Creates a new document fragment.
createTextNode() Creates a Text node.
createComment() Creates a comment node.
createCDATASection() Creates a CDatasection node.
createProcessingInstruction() Creates a processing instruction.
createAttribute() Creates an attribute.
createEntityReference() Creates an Entity reference.
getElementsByTagName() Retrieves the elements in the by tag name.
Table 81 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-19
Table 82 DBMS_XMLDOM Methods Added in Release 2 (9.2.0.2)
Method Syntax
createDocument FUNCTION createDocument (namspaceURI IN VARCHAR2, qualiedName
IN VARCHAR2, doctype IN DOMType :=NULL) REURN DocDocument;
getPrex FUNCTION getPrex(n DOMNode) RETURN VARCHAR2;
setPrex PROCEDURE setPrex (n DOMNode) RETURN VARCHAR2;
hasAttributes FUNCTION hasAttributes (n DOMNode) RETURN BOOLEAN;
getNamedItem FUNCTION getNamedItem (nnm DOMNamedNodeMap, name IN
VARCHAR2, ns IN VARCHAR2) RETURN DOMNode;
setNamedItem FUNCTION getNamedItem (nnm DOMNamedNodeMap, arg IN DOMNode,
ns IN VARCHAR2) RETURN DOMNode;
removeNamedItem FUNCTION removeNamedItem (nnm DOMNamesNodeMap, name in
VARCHAR2, ns IN VARCHAR2) RETURN DOMNode;
getOwnerElement FUNCTION getOwnerElement (a DOMAttr) RETURN DOMElement;
getAttribute FUNCTION getAttribute (elem DOMElement, name IN VARCHAR2, ns IN
VARCHAR2) RETURN VARCHAR2;
hasAttribute FUNCTION hasAttribute (elem DOMElement, name IN VARCHAR2)
RETURN BOOLEAN;
hasAttribute FUNCTION hasAttribute (elem DOMElement, name IN VARCHAR2, ns IN
VARCHAR2) RETURN BOOLEAN;
setAttribute PROCEDURE setAttribute (elem DOMElement, name IN VARCHAR2,
newvalue IN VARCHAR2, ns IN VARCHAR2);
removeAttribute PROCEDURE removeAttribute (elem DOMElement, name IN VARCHAR2,
ns IN VARCHAR2);
getAttributeNode FUNCTION getAttributeNode(elem DOMElement, name IN VARCHAR2, ns
IN VARCHAR2) RETURN DOMAttr;
setAttributeNode FUNCTION setAttributeNode(elem DOMElement, newAttr IN DOMAttr, ns IN
VARCHAR2) RETURN DOMAttr;
createElement FUNCTION createElement (doc DOMDocument, tagname IN VARCHAR2,
ns IN VARCHAR2) RETURN DOMElement;
createAttribute FUNCTION createAttribute (doc DOMDocument, name IN VARCHAR2, ns
IN VARCHAR2) RETURN DOMAttr;
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
PL/SQL DOM API for XMLType (DBMS_XMLDOM) Exceptions
The following lists the PL/SQL DOM API for XMLType (DBMS_XMLDOM)
exceptions. For further information, see Oracle9i XML Developers Kits Guide - XDK.
The exceptions have not changed since the prior release:
I INDEX_SIZE_ERR
I DOMSTRING_SIZE_ERR
I HIERARCHY_REQUEST_ERR
I WRONG_DOCUMENT_ERR
I INVALID_CHARACTER_ERR
I NO_DATA_ALLOWED_ERR
I NO_MODIFICATION_ALLOWED_ERR
I NOT_FOUND_ERR
I NOT_SUPPORTED_ERR
I INUSE_ATTRIBUTE_ERR
PL/SQL DOM API for XMLType: Node Types
In the DOM specication, the term document is used to describe a container for
many different kinds of information or data, which the DOM objecties. The DOM
species the way elements within an XML document container are used to create an
object-based tree structure and to dene and expose interfaces to manage and use
the objects stored in XML documents. Additionally, the DOM supports storage of
documents in diverse systems.
When a request such as getNodeType(myNode) is given, it returns myNodeType,
which is the node type supported by the parent node. These constants represent the
different types that a node can adopt:
I ELEMENT_NODE
I ATTRIBUTE_NODE
I TEXT_NODE
I CDATA_SECTION_NODE
I ENTITY_REFERENCE_NODE
I ENTITY_NODE
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-21
I PROCESSING_INSTRUCTION_NODE
I COMMENT_NODE
I DOCUMENT_NODE
I DOCUMENT_TYPE_NODE
I DOCUMENT_FRAGMENT_NODE
I NOTATION_NODE
Table 83 shows the node types for XML and HTML and the allowed corresponding
children node types.
Oracle XML DB DOM API for XMLType also species these interfaces:
I A NodeList interface to handle ordered lists of Nodes, for example:
The children of a Node
Elements returned by the getElementsByTagName method of the
element interface
Table 83 XML and HTML DOM Node Types and Corresponding Children Node Types
Node Type Children Node Types
Document Element (maximum of one), ProcessingInstruction, Comment, DocumentType
(maximum of one)
DocumentFragment Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
DocumentType No children
EntityReference Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
Element Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
Attr Text, EntityReference
ProcessingInstruction No children
Comment No children
Text No children
CDATASection No children
Entity Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
Notation No children
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I A NamedNodeMap interface to handle unordered sets of nodes, referenced by
their name attribute, such as the attributes of an element.
Working with XML Schema-Based XML Instances
This release introduces several extensions for character-set conversion and input
and output to and from a le system. As stated earlier in this chapter, applications
written against the PL/SQL Parser APIs in the previous release continue to work,
but require some modications that are described in the following sections.
PL/SQL API for XMLType is optimized to operate on XML schema-based XML
instances.
A new function is provided, newDOMDocument that constructs a DOM Document
handle given an XMLType value.
A typical usage scenario would be for a PL/SQL application to:
1. Fetch or construct an XMLType instance
2. Construct a DOMDocument node over the XMLType instance
3. Use the DOM API to access and manipulate the XML data
DOM NodeList and NamesNodeMap Objects
NodeList and NamedNodeMap objects in the DOM are live; that is, changes to the
underlying document structure are reected in all relevant NodeList and
NamedNodeMap objects.
For example, if a DOM user gets a NodeList object containing the children of an
element, and then subsequently adds more children to that element (or removes
children, or modies them), those changes are automatically propagated in the
NodeList, without further action from the user. Likewise, changes to a node in the
Note: For DOMDocument, node types represent handles to XML
fragments but do not represent the data itself.
For example, if you copy a node value, DOMDocument simply
clones the handle to the same underlying data. Any data modied
by one of the handles is visible when accessed by the other handle.
The XMLType value from which the DOMDocument handle is
constructed is the actual data and reects the results of all DOM
operations on it.
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-23
tree are propagated throughout all references to that node in NodeList and
NamedNodeMap objects.
The interfaces: Text, Comment, and CDATASection, all inherit from the
CharacterData interface.
PL/SQL DOM API for XMLType (DBMS_XMLDOM): Calling Sequence
Figure 81 illustrates the PL/SQL DOM API for XMLType (DBMS_XMLDOM) calling
sequence.
You can create a DOM document (DOMDocument) from an existing XMLType or as
an empty document.
1. The newDOMDocument procedure processes the XMLTYpe or empty document.
This creates a DOMDocument.
2. You can use the DOM API methods such as, createElement, createText,
createAttribute, and createComment, and so on, to traverse and extend
the DOM tree. See Table 81 for a full list of available methods.
3. The results of these methods (DOMElement, DOMText, and so on) can also be
passed to makeNode to obtain the DOMNode interface.
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
8-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 81 PL/SQL DOM API for XMLType: Calling Sequence
PL/SQL DOM API for XMLType Examples
Example 81 Creating and Manipulating a DOM Document
This example illustrates how to create a DOMDocument handle for an example
element PERSON:
-- This example illustrates how to create a DOMDocument handle for an example
element PERSON:
declare
var XMLType;
doc dbms_xmldom.DOMDocument;
ndoc dbms_xmldom.DOMNode;
docelem dbms_xmldom.DOMElement;
node dbms_xmldom.DOMNode;
childnode dbms_xmldom.DOMNode;
Select Statement Createxml
CreateAttribute CreateComment . . .
XMLType
newDOMDocument newDOMDocument
DOMDocument
DOMNode Interface
(Empty
document)
makeNode
DOMElement
Interface
DOMText
Interface
DOMAttibute
Interface
DOMComment
Interface
CreateTextNode CreateElement
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
PL/SQL API for XMLType 8-25
nodelist dbms_xmldom.DOMNodelist;
buf varchar2(2000);
begin
var := xmltype(<PERSON> <NAME> ramesh </NAME> </PERSON>);
-- Create DOMDocument handle:
doc := dbms_xmldom.newDOMDocument(var);
ndoc := dbms_xmldom.makeNode(doc);
dbms_xmldom.writetobuffer(ndoc, buf);
dbms_output.put_line(Before:||buf);
docelem := dbms_xmldom.getDocumentElement( doc );
-- Access element:
nodelist := dbms_xmldom.getElementsByTagName(docelem, NAME);
node := dbms_xmldom.item(nodelist, 0);
childnode := dbms_xmldom.getFirstChild(node);
-- Manipulate:
dbms_xmldom.setNodeValue(childnode, raj);
dbms_xmldom.writetobuffer(ndoc, buf);
dbms_output.put_line(After:||buf);
end;
/
Example 82 Creating a DOM Document Using sys.xmltype
This example creates a DOM document from an XMLType:
declare
doc dbms_xmldom.DOMDocument;
buf varchar2(32767);
begin
-- new document
doc := dbms_xmldom.newDOMDocument(sys.xmltype(<person> <name>Scott</name>
</person>));
dbms_xmldom.writeToBuffer(doc, buf);
dbms_output.put_line(buf);
end;
/
PL/SQL Parser API for XMLType (DBMS_XMLPARSER)
8-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 83 Creating an Element Node
-- This example creates an element node starting from an empty DOM document:
declare
doc dbms_xmldom.DOMDocument;
elem dbms_xmldom.DOMElement;
nelem dbms_xmldom.DOMNode;
begin
-- new document
doc := dbms_xmldom.newDOMDocument;
-- create a element node
elem := dbms_xmldom.createElement(doc, ELEM);
-- make node
nelem := dbms_xmldom.makeNode(elem);
dbms_output.put_line(dbms_xmldom.getNodeName(nelem));
dbms_output.put_line(dbms_xmldom.getNodeValue(nelem));
dbms_output.put_line(dbms_xmldom.getNodeType(nelem));
end;
/
PL/SQL Parser API for XMLType (DBMS_XMLPARSER)
XML documents are made up of storage units, called entities, that contain either
parsed or unparsed data. Parsed data is made up of characters, some of which form
character data and some of which form markup. Markup encodes a description of
the document's storage layout and logical structure. XML provides a mechanismfor
imposing constraints on the storage layout and logical structure.
A software module called an XML parser or processor reads XML documents and
provides access to their content and structure. An XML parser usually does its work
on behalf of another module, typically the application.
PL/SQL Parser API for XMLType: Features
In general, PL/SQL Parser API for XMLType (DBMS_XMLPARSER) performs the
following tasks:
I Builds a result tree that can be accessed by PL/SQL APIs
I Raises an error if the parsing fails
Table 84 lists the PL/SQL Parser API for XMLType (DBMS_XMLPARSER) methods.
PL/SQL Parser API for XMLType (DBMS_XMLPARSER)
PL/SQL API for XMLType 8-27
Table 84 DBMS_XMLPARSER Methods
Method Arguments, Return Values, and Results
parse Argument: (url VARCHAR2)
Result: Parses XML stored in the given URL or le and
returns the built DOM Document
newParser Returns: A new parser instance
parse Argument: (p Parser, url VARCHAR2)
Result: Parses XML stored in the given URL or le
parseBuffer Argument: (p Parser, doc VARCHAR2)
Result: Parses XML stored in the given buffer
parseClob Argument: (p Parser, doc CLOB)
Result: Parses XML stored in the given CLOB
parseDTD Argument: (p Parser, url VARCHAR2, root
VARCHAR2)
Result: Parses XML stored in the given URL or le
parseDTDBuffer Argument: (p Parser, dtd VARCHAR2, root
VARCHAR2)
Result: Parses XML stored in the given buffer
parseDTDClob Argument: (p Parser, dtd CLOB, root
VARCHAR2)
Result: Parses XML stored in the given clob
setBaseDir Argument: (p Parser, dir VARCHAR2)
Result: Sets base directory used to resolve relative
URLs
showWarnings Argument: (p Parser, yes BOOLEAN)
Result: Turns warnings on or off
setErrorLog Argument: (p Parser, fileName VARCHAR2)
Result: Sets errors to be sent to the specied le
setPreserveWhitespace Argument: (p Parser, yes BOOLEAN)
Result: Sets white space preserve mode
setValidationMode Argument: (p Parser, yes BOOLEAN)
Result: Sets validation mode
PL/SQL Parser API for XMLType (DBMS_XMLPARSER)
8-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
PL/SQL Parser API for XMLType (DBMS_XMLPARSER): Calling Sequence
Figure 82 illustrates the PL/SQL Parser for XMLType (DBMS_XMLPARSER) calling
sequence:
1. newParser method can be used to construct a Parser instance.
2. XML documents can then be parsed using the Parser with methods such as,
parseBuffer, parseClob, parse(URI), and so on. See Table 84 for a full
list of Parser methods.
3. An error is raised if the input is not a valid XML document.
4. To use the PL/SQL DOM API for XMLType on the parsed XML document
instance, you need to call getDocument on the Parser to obtain a
DOMDocument interface.
getValidationMode Argument: (p Parser)
Result: Gets validation mode
setDoctype Argument: (p Parser, dtd DOMDocumentType)
Result: Sets DTD
getDoctype Argument: (p Parser)
Result: Gets DTD
getDocument Argument: (p Parser)
Result: Gets DOM document
freeParser Argument: (p Parser)
Result: Frees a Parser object
Table 84 DBMS_XMLPARSER Methods (Cont.) (Cont.)
Method Arguments, Return Values, and Results
PL/SQL Parser API for XMLType (DBMS_XMLPARSER)
PL/SQL API for XMLType 8-29
Figure 82 PL/SQL Parser API for XMLType: Calling Sequence
PL/SQL Parser API for XMLType Example
Example 84 Parsing an XML Document
This example parses a simple XML document and enables DOM APIs to be used.
declare
indoc VARCHAR2(2000);
indomdoc dbms_xmldom.domdocument;
innode dbms_xmldom.domnode;
myParser dbms_xmlparser.Parser;
begin
indoc := <emp><name> Scott </name></emp>;
myParser := dbms_xmlparser.newParser;
dbms_xmlparser.parseBuffer(myParser, indoc);
indomdoc := dbms_xmlparser.getDocument(myParser);
innode := dbms_xmldom.makeNode(indomdoc);
-- DOM APIs can be used here
end;
/
newParser
getDocument
parse (URI) parseBuffer
Parser
DOMDocument
. . .
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
8-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
W3C XSL Recommendation describes rules for transforming a source tree into a
result tree. A transformation expressed in eXtensible Stylesheet Language
Transformation (XSLT) is called an XSL stylesheet. The transformation specied is
achieved by associating patterns with templates dened in the XSL stylesheet. A
template is instantiated to create part of the result tree.
Enabling Transformations and Conversions with XSLT
The Oracle XML DB PL/SQL DOM API for XMLType also supports eXtensible
Stylesheet Language Transformation (XSLT). This enables transformation from one
XML document to another, or conversion into HTML, PDF, or other formats. XSLT
is also widely used to convert XML to HTML for browser display.
The embedded XSLT processor follows eXtensible Stylesheet Language (XSL)
statements and traverses the DOM tree structure for XML data residing in
XMLType. Oracle XML DB applications do not require a separate parser as did the
prior releases XML Parser for PL/SQL. However, applications requiring external
processing can still use the XML Parser for PL/SQL rst to expose the document
structure.
PL/SQL XSLT Processor for XMLType: Features
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR) is Oracle XML DBs
implementation of the XSL processor. This follows the W3C XSLT nal
recommendation (REC-xslt-19991116). It includes the required behavior of an XSL
processor in terms of how it must read XSL stylesheets and the transformations it
must achieve.
Note: The XML Parser for PL/SQL in Oracle XDK parses an XML
document (or a standalone DTD) so that the XML document can be
processed by an application, typically running on the client.
PL/SQL APIs for XMLType are used for applications that run on
the server and are natively integrated in the database. Benets
include performance improvements and enhanced access and
manipulation options.
See Also: Appendix D, "XSLT Primer"
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
PL/SQL API for XMLType 8-31
The types and methods of PL/SQL XSLT Processor are made available by the
PL/SQL package, DBMS_XSLPROCESSOR.
PL/SQL XSLT Processor API (DBMS_XSLPROCESSOR): Methods
The methods in PL/SQL XSLT Processor API (DBMS_XSLPROCESSOR) use two
PL/SQL types specic to the XSL Processor implementation. These are the
Processor type and the Stylesheet type.
Table 85 lists PL/SQL XSLT Processor (DBMS_XSLPROCESSOR) methods.
Note: There is no space between the method declaration and the
arguments, for example: processXSL(p Processor, ss
Stylesheet, xmldoc DOMDocument)
Table 85 DBMS_XSLPROCESSOR Methods
Method Argument or Return Values or Result
newProcessor Returns: a new processor instance
processXSL Argument: (p Processor, ss Stylesheet, xmldoc DOMDocument)
Result: Transforms input XML document using given DOMDocument and
stylesheet
processXSL Argument: (p Processor, ss Stylesheet, xmldoc DOMDocumentFragment)
Result: Transforms input XML document using given DOMDocumentFragment
and stylesheet
showWarnings Argument: (p Processor, yes BOOLEAN)
Result: Turn warnings on or off
setErrorLog Argument: (p Processor, Filename VARCHAR2)
Result: Sets errors to be sent to the specied le
NewStylesheet Argument: (Input VARCHAR2, Reference VARCHAR2)
Result: Sets errors to be sent to the specied le
transformNode Argument: (n DOMNode, ss Stylesheet)
Result: Transforms a node in a DOM tree using the given stylesheet
selectNodes Argument: (n DOMNode, pattern VARCHAR2)
Result: Selects nodes from a DOM tree which match the given pattern
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
8-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
PL/SQL Parser API for XMLType (DBMS_XSLPROCESSOR): Calling Sequence
Figure 82 illustrates the XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
calling sequence:
1. An XSLT Processor can be constructed using the method newProcessor.
2. To build a Stylesheet from a DOM document use method newStylesheet.
3. Optionally, you can set parameters to the Stylesheet using the call
setParams.
4. The XSLT processing can then be executed with the call processXSL using the
processor and Stylesheet created in Steps 1 - 3.
5. Pass the XML document to be transformed to the call processXSL.
6. The resulting DOMDocumentFragment interface can be operated on using the
PL/SQL DOM API for XMLType.
selectSingleNodes Argument: (n DOMNode, pattern VARCHAR2)
Result: Selects the rst node from the tree that matches the given pattern
valueOf Argument: (n DOMNode, pattern VARCHAR2)
Result: Retrieves the value of the rst node from the tree that matches the given
pattern
setParam Argument: (ss Stylesheet, name VARCHAR2, value VARCHAR2)
Result: Sets a top level paramter in the stylesheet
removeParam Argument: (ss Stylesheet, name VARCHAR2)
Result: Removes a top level stylesheet parameter
ResetParams Argument: (ss Stylesheet)
Result: Resets the top-level stylesheet parameters
freeStylesheet Argument: (ss Stylesheet)
Result: Frees a Stylesheet object
freeProcessor Argument: (p Processor)
Result: Frees a Processor object
Table 85 DBMS_XSLPROCESSOR Methods (Cont.)
Method Argument or Return Values or Result
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
PL/SQL API for XMLType 8-33
Figure 83 PL/SQL XSLT Processor for XMLType: Calling Sequence
PL/SQL XSLT Processor for XMLType Example
Example 85 Transforming an XML Document Using an XSL Stylesheet
This example transforms an XML document by using the processXSL call.Expect
the following output (XML with tags ordered based on tag name):
<emp>
<empno>1</empno>
<fname>robert</fname>
<job>engineer</job>
<lname>smith</lname>
<sal>1000</sal>
</emp>
declare
indoc VARCHAR2(2000);
xsldoc VARCHAR2(2000);
newStylesheet newProcessor
Stylesheet xmldoc Processor
DOMNode Interface
makeNode
XSL Document
(DOMDocument)
ProcessXSL
(DOMDocument)
setParams
DOMDocumentFragment Interface
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
8-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
myParser dbms_xmlparser.Parser;
indomdoc dbms_xmldom.domdocument;
xsltdomdoc dbms_xmldom.domdocument;
xsl dbms_xslprocessor.stylesheet;
outdomdocf dbms_xmldom.domdocumentfragment;
outnode dbms_xmldom.domnode;
proc dbms_xslprocessor.processor;
buf varchar2(2000);
begin
indoc := <emp><empno> 1</empno> <fname> robert </fname> <lname>
smith</lname> <sal>1000</sal> <job> engineer </job> </emp>;
xsldoc :=
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8"/>
<!-- alphabetizes an xml tree -->
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="*|text()">
<xsl:sort select="name(.)" data-type="text" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
</xsl:stylesheet>;
myParser := dbms_xmlparser.newParser;
dbms_xmlparser.parseBuffer(myParser, indoc);
indomdoc := dbms_xmlparser.getDocument(myParser);
dbms_xmlparser.parseBuffer(myParser, xsldoc);
xsltdomdoc := dbms_xmlparser.getDocument(myParser);
xsl := dbms_xslprocessor.newstylesheet(xsltdomdoc, );
proc := dbms_xslprocessor.newProcessor;
--apply stylesheet to DOM document
outdomdocf := dbms_xslprocessor.processxsl(proc, xsl, indomdoc);
outnode := dbms_xmldom.makenode(outdomdocf);
-- PL/SQL DOM API for XMLType can be used here
dbms_xmldom.writetobuffer(outnode, buf);
dbms_output.put_line(buf);
end;
/
Java API for XMLType 9-1
9
Java API for XMLType
This chapter describes how to use XMLType in Java, including fetching XMLType
data through JDBC.
I Introducing Java DOM API for XMLType
I Java DOM API for XMLType
I Java DOM API for XMLType Features
I Java DOM API for XMLType Classes
Introducing Java DOM API for XMLType
9-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Java DOM API for XMLType
Oracle XML DB supports the Java Document Object Model (DOM) API for
XMLType. This is a generic API for client and server, for both XML schema-based
and non- schema-based documents. It is implemented using the Java package
oracle.xdb.dom.
To access XMLType data using JDBC use the class oracle.xdb.XMLType.
For XML documents that do not conform to any XML schema, you can use the Java
DOM API for XMLType as it can handle any valid XML document.
Java DOM API for XMLType
Java DOMAPI for XMLType handles all kinds of valid XML documents irrespective
of how they are stored in Oracle XML DB. It presents to the application a uniform
view of the XML document irrespective of whether it is XML schema-based or non-
schema-based, whatever the underlying storage. Java DOM API works on client
and server.
As discussed in Chapter 8, "PL/SQL API for XMLType", the Oracle XML DB DOM
APIs are compliant with W3C DOM Level 1.0 and Level 2.0 Core Recommendation.
Accessing XML Documents in Repository
Oracle XML DB Resource API for Java API allows Java applications to access XML
documents stored in the Oracle XML DB Repository. Naming conforms to the Java
binding for DOM as specied by the W3C DOM Recommendation. Oracle XML DB
Repository hierarchy can store both XML schema-based and non- schema-based
documents.
Accessing XML Documents Stored in Oracle9i Database (Java)
Oracle XML DB provides the following way (part of the Java Resource APIs) for
Java applications to access XML data stored in a database:
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
See: Chapter 17, "Oracle XML DB Resource API for Java"
Java DOM API for XMLType
Java API for XMLType 9-3
Using JDBC
This is an SQL-based approach for Java applications for accessing any data in
Oracle9i database, including XML documents in Oracle XML DB. Use the
oracle.xdb.dom.XMLType class, createXML() method.
How Java Applications Use JDBC to Access XML Documents in Oracle XML DB
JDBC users can query an XMLType table to obtain a JDBC XMLType interface that
supports all methods supported by the SQL XMLType data type. The Java (JDBC)
API for XMLType interface can implement the DOM document interface.
Example 91 XMLType Java: Using JDBC to Query an XMLType Table
The following is an example that illustrates using JDBC to query an XMLType table:
import oracle.xdb.XMLType;
...
OraclePreparedStatement stmt = (OraclePreparedStatement)
conn.prepareStatement("select e.poDoc from po_xml_tab e");
ResultSet rset = stmt.executeQuery();
OracleResultSet orset = (OracleResultSet) rset;
while(orset.next())
{
// get the XMLType
XMLType poxml = XMLType.createXML(orset.getOPAQUE(1));
// get the XMLDocument as a string...
Document podoc = (Document)poxml.getDOM();
}
Example 92 XMLType Java: Selecting XMLType Data
You can select the XMLType data in JDBC in one of two ways:
I Use the getClobVal() or getStringVal() in SQL and get the result as a
oracle.sql.CLOB or java.lang.String in Java. The following Java code
snippet shows how to do this:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn =
DriverManager.getConnection("jdbc:oracle:oci8:@", "scott", "tiger");
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
Java DOM API for XMLType
9-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
"select e.poDoc.getClobVal() poDoc, "+
"e.poDoc.getStringVal() poString "+
" from po_xml_tab e");
ResultSet rset = stmt.executeQuery();
OracleResultSet orset = (OracleResultSet) rset;
while(orset.next())
{
// the first argument is a CLOB
oracle.sql.CLOB clb = orset.getCLOB(1);
// the second argument is a string..
String poString = orset.getString(2);
// now use the CLOB inside the program
}
I Use the getOPAQUE() call in the PreparedStatement to get the whole
XMLType instance, and use the XMLType constructor to construct an
oracle.xdb.XMLType class out of it. Then you can use the Java functions on
the XMLType class to access the data.
import oracle.xdb.XMLType;
...
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"select e.poDoc from po_xml_tab e");
ResultSet rset = stmt.executeQuery();
OracleResultSet orset = (OracleResultSet) rset;
// get the XMLType
XMLType poxml = XMLType(orset.getOPAQUE(1));
// get the XML as a string...
String poString = poxml.getStringVal();
Example 93 XMLType Java: Directly Returning XMLType Data
This example shows the use of getObject to directly get the XMLType from the
ResultSet. This is the easiest way to get the XMLType from the ResultSet.
import oracle.xdb.XMLType;
Java DOM API for XMLType
Java API for XMLType 9-5
...
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"select e.poDoc from po_xml_tab e");
ResultSet rset = stmt.executeQuery();
OracleResultSet orset = (OracleResultSet) rset;
while(orset.next())
{
// get the XMLType
XMLType poxml = (XMLType)orset.getObject(1);
// get the XML as a string...
String poString = poxml.getStringVal();
}
Using JDBC to Manipulate XML Documents Stored in a Database
You can also update, insert, and delete XMLType data using JDBC.
Example 94 XMLType Java: Updating/Inserting/Deleting XMLType Data
You can insert an XMLType in java in one of two ways:
I Bind a CLOB or a string to an INSERT/UPDATE/DELETE statement, and use
the XMLType constructor inside SQL to construct the XML instance:
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"update po_xml_tab set poDoc = XMLType(?) ");
// the second argument is a string..
String poString = "<PO><PONO>200</PONO><PNAME>PO_2</PNAME></PO>";
// now bind the string..
stmt.setString(1,poString);
stmt.execute();
I Use the setObject() (or setOPAQUE()) call in the PreparedStatement to
set the whole XMLType instance:
import oracle.xdb.XMLType;
...
OraclePreparedStatement stmt =
Java DOM API for XMLType
9-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
(OraclePreparedStatement) conn.prepareStatement(
"update po_xml_tab set poDoc = ? ");
// the second argument is a string
String poString = "<PO><PONO>200</PONO><PNAME>PO_2</PNAME></PO>";
XMLType poXML = XMLType.createXML(conn, poString);
// now bind the string..
stmt.setObject(1,poXML);
stmt.execute();
Example 95 XMLType Java: Getting Metadata on XMLType
When selecting out XMLType values, JDBC describes the column as an OPAQUE
type. You can select the column type name out and compare it with XMLTYPE to
check if you are dealing with an XMLType:
import oracle.sql.*;
import oracle.jdbc.*;
...
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"select poDoc from po_xml_tab");
OracleResultSet rset = (OracleResultSet)stmt.exuecuteQuery();
// Now, we can get the resultset metadata
OracleResultSetMetaData mdata =
(OracleResultSetMetaData)rset.getMetaData();
// Describe the column = the column type comes out as OPAQUE
// and column type name comes out as XMLTYPE
if (mdata.getColumnType(1) == OracleTypes.OPAQUE &&
mdata.getColumnTypeName(1).compareTo("SYS.XMLTYPE") == 0)
{
// we know it is an XMLtype
}
Example 96 XMLType Java: Updating an Element in an XMLType Column
This example updates the discount element inside PurchaseOrder stored in an
XMLType column. It uses Java (JDBC) and the oracle.xdb.XMLType class. This
example also shows you howto insert/update/delete XMLTypes using Java (JDBC).
It uses the parser to update an in-memory DOM tree and write the updated XML
value to the column.
Java DOM API for XMLType
Java API for XMLType 9-7
-- create po_xml_hist table to store old PurchaseOrders
create table po_xml_hist (
xpo xmltype
);
/*
DESCRIPTION
Example for oracle.xdb.XMLType
NOTES
Have classes12.zip, xmlparserv2.jar, and oraxdb.jar in CLASSPATH
*/
import java.sql.*;
import java.io.*;
import oracle.xml.parser.v2.*;
import org.xml.sax.*;
import org.w3c.dom.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;
import oracle.xdb.XMLType;
public class tkxmtpje
{
static String conStr = "jdbc:oracle:oci8:@";
static String user = "scott";
static String pass = "tiger";
static String qryStr =
"SELECT x.poDoc from po_xml_tab x "+
"WHERE x.poDoc.extract('/PO/PONO/text()').getNumberVal()=200";
static String updateXML(String xmlTypeStr)
{
System.out.println("\n===============================");
System.out.println("xmlType.getStringVal():");
System.out.println(xmlTypeStr);
System.out.println("===============================");
String outXML = null;
try{
DOMParser parser = new DOMParser();
Java DOM API for XMLType
9-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
parser.setValidationMode(false);
parser.setPreserveWhitespace (true);
parser.parse(new StringReader(xmlTypeStr));
System.out.println("xmlType.getStringVal(): xml String is well-formed");
XMLDocument doc = parser.getDocument();
NodeList nl = doc.getElementsByTagName("DISCOUNT");
for(int i=0;i<nl.getLength();i++){
XMLElement discount = (XMLElement)nl.item(i);
XMLNode textNode = (XMLNode)discount.getFirstChild();
textNode.setNodeValue("10");
}
StringWriter sw = new StringWriter();
doc.print(new PrintWriter(sw));
outXML = sw.toString();
//print modified xml
System.out.println("\n===============================");
System.out.println("Updated PurchaseOrder:");
System.out.println(outXML);
System.out.println("===============================");
}
catch ( Exception e )
{
e.printStackTrace(System.out);
}
return outXML;
}
public static void main(String args[]) throws Exception
{
try{
System.out.println("qryStr="+ qryStr);
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn =
DriverManager.getConnection("jdbc:oracle:oci8:@", user, pass);
Java DOM API for XMLType
Java API for XMLType 9-9
Statement s = conn.createStatement();
OraclePreparedStatement stmt;
ResultSet rset = s.executeQuery(qryStr);
OracleResultSet orset = (OracleResultSet) rset;
while(orset.next()){
//retrieve PurchaseOrder xml document from database
XMLType xt = XMLType.createXML(orset.getOPAQUE(1));
//store this PurchaseOrder in po_xml_hist table
stmt = (OraclePreparedStatement)conn.prepareStatement(
"insert into po_xml_hist values(?)");
stmt.setObject(1,xt); // bind the XMLType instance
stmt.execute();
//update "DISCOUNT" element
String newXML = updateXML(xt.getStringVal());
// create a new instance of an XMLtype from the updated value
xt = XMLType.createXML(conn,newXML);
// update PurchaseOrder xml document in database
stmt = (OraclePreparedStatement)conn.prepareStatement(
"update po_xml_tab x set x.poDoc =? where "+
"x.poDoc.extract('/PO/PONO/text()').getNumberVal()=200");
stmt.setObject(1,xt); // bind the XMLType instance
stmt.execute();
conn.commit();
System.out.println("PurchaseOrder 200 Updated!");
}
//delete PurchaseOrder 1001
s.execute("delete from po_xml x"+
"where x.xpo.extract"+
"('/PurchaseOrder/PONO/text()').getNumberVal()=1001");
System.out.println("PurchaseOrder 1001 deleted!");
}
catch( Exception e )
{
Java DOM API for XMLType
9-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
e.printStackTrace(System.out);
}
}
}
----------------------
-- list PurchaseOrders
----------------------
set long 20000
set pages 100
select x.xpo.getClobVal()
from po_xml x;
Here is the resulting updated purchase order in XML:
<?xml version = '1.0'?>
<PurchaseOrder>
<PONO>200</PONO>
<CUSTOMER>
<CUSTNO>2</CUSTNO>
<CUSTNAME>John Nike</CUSTNAME>
<ADDRESS>
<STREET>323 College Drive</STREET>
<CITY>Edison</CITY>
<STATE>NJ</STATE>
<ZIP>08820</ZIP>
</ADDRESS>
<PHONELIST>
<VARCHAR2>609-555-1212</VARCHAR2>
<VARCHAR2>201-555-1212</VARCHAR2>
</PHONELIST>
</CUSTOMER>
<ORDERDATE>20-APR-97</ORDERDATE>
<SHIPDATE>20-MAY-97 12.00.00.000000 AM</SHIPDATE>
<LINEITEMS>
<LINEITEM_TYP LineItemNo="1">
<ITEM StockNo="1004">
<PRICE>6750</PRICE>
<TAXRATE>2</TAXRATE>
</ITEM>
<QUANTITY>1</QUANTITY>
<DISCOUNT>10</DISCOUNT>
</LINEITEM_TYP>
<LINEITEM_TYP LineItemNo="2">
Java DOM API for XMLType
Java API for XMLType 9-11
<ITEM StockNo="1011">
<PRICE>4500.23</PRICE>
<TAXRATE>2</TAXRATE>
</ITEM>
<QUANTITY>2</QUANTITY>
<DISCOUNT>10</DISCOUNT>
</LINEITEM_TYP>
</LINEITEMS>
<SHIPTOADDR>
<STREET>55 Madison Ave</STREET>
<CITY>Madison</CITY>
<STATE>WI</STATE>
<ZIP>53715</ZIP>
</SHIPTOADDR>
</PurchaseOrder>
Example 97 Manipulating an XMLType Column
This example performs the following:
I Selects an XMLType from an XMLType table
I Extracts portions of the XMLType based on an XPath expression
I Checks for the existence of elements
I Transforms the XMLType to another XML format based on XSL
I Checks the validity of the XMLType document against an XML schema
import java.sql.*;
import java.io.*;
import java.net.*;
import java.util.*;
import oracle.xml.parser.v2.*;
import oracle.xml.parser.schema.*;
import org.xml.sax.*;
import org.w3c.dom.*;
import oracle.xml.sql.dataset.*;
import oracle.xml.sql.query.*;
import oracle.xml.sql.docgen.*;
import oracle.xml.sql.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;
Java DOM API for XMLType
9-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
import oracle.xdb.XMLType;
public class tkxmtpk1
{
static String conStr = "jdbc:oracle:oci8:@";
static String user = "tpjc";
static String pass = "tpjc";
static String qryStr = "select x.resume from t1 x where id<3";
static String xslStr =
"<?xml version='1.0' ?> " +
"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1
999/XSL/Transform'> " +
"<xsl:template match='ROOT'> " +
"<xsl:apply-templates/> " +
"</xsl:template> " +
"<xsl:template match='NAME'> " +
"<html> " +
" <body> " +
" This is Test " +
" </body> " +
"</html> " +
"</xsl:template> " +
"</xsl:stylesheet>";
static void parseArg(String args[])
{
conStr = (args.length >= 1 ? args[0]:conStr);
user = (args.length >= 2 ? args[1].substring(0, args[1].indexOf("/")):user);
pass = (args.length >= 2 ? args[1].substring(args[1].indexOf("/")+1):pass);
qryStr = (args.length >= 3 ? args[2]:qryStr);
}
/**
* Print the byte array contents
*/
static void showValue(byte[] bytes) throws SQLException
{
if (bytes == null)
System.out.println("null");
else if (bytes.length == 0)
System.out.println("empty");
else
{
for(int i=0; i<bytes.length; i++)
Java DOM API for XMLType
Java API for XMLType 9-13
System.out.print((bytes[i]&0xff)+" ");
System.out.println();
}
}
public static void main(String args[]) throws Exception
{
tkxmjnd1 util = new tkxmjnd1();
try{
if( args != null )
parseArg(args);
// System.out.println("conStr=" + conStr);
System.out.println("user/pass=" + user + "/" +pass );
System.out.println("qryStr="+ qryStr);
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection(conStr, user, pass);
Statement s = conn.createStatement();
ResultSet rset = s.executeQuery(qryStr);
OracleResultSet orset = (OracleResultSet) rset;
OPAQUE xml;
while(orset.next()){
xml = orset.getOPAQUE(1);
oracle.xdb.XMLType xt = oracle.xdb.XMLType.createXML(xml);
System.out.println("Testing getDOM() ...");
Document doc = xt.getDOM();
util.printDocument(doc);
System.out.println("Testing getBytesValue() ...");
showValue(xt.getBytesValue());
System.out.println("Testing existsNode() ...");
try {
System.out.println("existsNode(/)" + xt.existsNode("/", null));
}
catch (SQLException e) {
System.out.println("Thin driver Expected exception: " + e);
}
Java DOM API for XMLType
9-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
System.out.println("Testing extract() ...");
try {
XMLType xt1 = xt.extract("/RESUME", null);
System.out.println("extract RESUME: " + xt1.getStringVal());
System.out.println("should be Fragment: " + xt1.isFragment());
}
catch (SQLException e) {
System.out.println("Thin driver Expected exception: " + e);
}
System.out.println("Testing isFragment() ...");
try {
System.out.println("isFragment = " + xt.isFragment()); }
catch (SQLException e)
{
System.out.println("Thin driver Expected exception: " + e);
}
System.out.println("Testing isSchemaValid() ...");
try {
System.out.println("isSchemaValid(): " + xt.isSchemaValid(null,"RES UME"));
}
catch (SQLException e) {
System.out.println("Thin driver Expected exception: " + e);
}
System.out.println("Testing transform() ...");
System.out.println("XSLDOC: \n" + xslStr + "\n");
try {
/* XMLType xslDoc = XMLType.createXML(conn, xslStr);
System.out.println("XSLDOC Generated");
System.out.println("After transformation:\n" + (xt.transform(xslDoc,
null)).getStringVal()); */
System.out.println("After transformation:\n" + (xt.transform(null,
null)).getStringVal());
}
catch (SQLException e) {
System.out.println("Thin driver Expected exception: " + e);
}
System.out.println("Testing createXML(conn, doc) ...");
try {
XMLType xt1 = XMLType.createXML(conn, doc);
System.out.println(xt1.getStringVal());
Java DOM API for XMLType Features
Java API for XMLType 9-15
}
catch (SQLException e) {
System.out.println("Got exception: " + e);
}
}
}
catch( Exception e )
{
e.printStackTrace(System.out);
}
}
}
Java DOM API for XMLType Features
When you use the Java DOMAPI to get XML data fromOracle XML DB, you get an
XMLDocument object that represents the XML data or le you retrieve. From this
document interface you can get the elements of the document and perform all the
operations specied in the W3C DOM specication. The DOM works on:
I Any type of XML document:
I XML schema-based
I Non-XML schema-based
I Any type of underlying storage used by the document:
I CLOB
I BLOB
I Object-relational.
The Java DOM API for XMLType supports deep or shallow searching in the
document to retrieve children and properties of XML objects such as name,
namespace, and so on. Conforming to the DOM 2.0 recommendation, Java DOM
API for XMLType is namespace aware.
Creating XML Documents Programmatically
Java API for XMLType also allows applications to create XML documents
programmatically. This way applications can create XML documents on the y (or
dynamically) that either conform to a preregistered XML schema or are non-XML
schema-based documents.
Java DOM API for XMLType Features
9-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Creating XML Schema-Based Documents
To create XML schema-based documents, Java DOM API for XMLType uses an
extension to specify which XML schema URL to use. For XML schema-based
documents, it also veries that the DOM being created conforms to the specied
XML schema, that is, that the appropriate children are being inserted under the
appropriate documents.
Once the DOM object has been created, it can be saved to Oracle XML DB
Repository using the Oracle XML DB Resource API for Java. The XML document is
stored in the appropriate format:
I As a CLOB or BLOB for non-XML schema-based documents
I In the format specied by the XML schema for XML schema-based documents
Example 98 Java DOM API for XMLType: Creating a DOM Object and Storing It in the
Format Specied by the XML Schema
The following example shows how you can use Java DOM API for XMLType to
create a DOM object and store it in the format specied by the XML schema. Note
that the validation against the XML schema is not shown here.
import oracle.xdb.XMLType;
...
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"update po_xml_tab set poDoc = ? ");
// the second argument is a string
String poString = "<PO><PONO>200</PONO><PNAME>PO_2</PNAME></PO>";
XMLType poXML = XMLType.createXML(conn, poString);
Document poDOM = (Document)poXML.getDOM();
Element rootElem = poDOM.createElement("PO");
poDOM.insertBefore(poDOM, rootElem, null);
// now bind the string..
stmt.setObject(1,poXML);
stmt.execute();
Note: In this release, Java DOM API for XMLType does not
perform type and constraint checks.
Java DOM API for XMLType Classes
Java API for XMLType 9-17
JDBC/SQLJ
An XMLType instance is represented in Java by oracle.xdb.XMLType. When an
instance of XMLType is fetched using JDBC, it is automatically manifested as an
object of the provided XMLType class. Similarly, objects of this class can be bound as
values to Data Manipulation Language (DML) statements where an XMLType is
expected. The same behavior is supported in SQLJ clients.
Java DOM API for XMLType Classes
Oracle XML DB supports the W3C DOM Level 2 Recommendation. In addition to
the W3C Recommendation, Oracle XML DB DOMAPI also provides Oracle-specic
extensions, mainly to facilitate your application interfacing with Oracle XDK for
Java. A list of the Oracle extensions is found at:
http://otn.oracle.com/docs/tech/xml/xdk_java/content.html
XMLDocument() is a class that represents the DOM for the instantiated XML
document. You can retrieve the XMLType from the XML document using the
function getXMLType() on XMLDocument() class.
Table 91 lists the Java DOMAPI for XMLType classes and the W3C DOMinterfaces
they implement.
Table 91 Java DOM API for XMLType: Classes
Java DOM API for XMLType Class
W3C DOM Interface Recommendation
Class
oracle.xdb.dom.XMLDocument org.w3c.dom.Document
oracle.xdb.dom.XMLCData org.w3c.dom.CDataSection
oracle.xdb.dom.XMLComment org.w3c.dom.Comment
oracle.xdb.dom.XMLPI org.w3c.dom.ProcessingInstruction
oracle.xdb.dom.XMLText org.w3c.dom.Text
oracle.xdb.dom.XMLEntity org.w3c.dom.Entity
oracle.xdb.dom.DTD org.w3c.dom.DocumentType
oracle.xdb.dom.XMLNotation org.w3c.dom.Notation
oracle.xdb.dom.XMLNodeList org.w3c.dom.NodeList
oracle.xdb.dom.XMLAttribute org.w3c.dom.Attribute
Java DOM API for XMLType Classes
9-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Non-Supported Java Methods
The following are methods documented in Release 2 (9.2.0.1) but not currently
supported:
I XDBDocument.getElementByID
I XDBDocument.importNode
I XDBNode.normalize
I XDBNode.isSupported
I XDBDomImplementation.hasFeature
Java DOM API for XMLType: Calling Sequence
The following Java DOM API for XMLType calling sequence description assumes
that your XML data is pre-registered with an XML schema and that it is stored in an
XMLType datatype column. To use the Java DOM API for XMLType, follow these
steps:
1. Retrieve the XML data from the XMLType table or XMLType column in the
table. When you fetch XML data, Oracle XML DB creates a DOMDocument
instance of XMLType, parsing the document into a DOM tree. You can then
manipulate elements in the DOM tree using Java DOM API for XMLType.
2. Use the Java DOM API for XMLType to perform operations and manipulations
on elements of the DOM tree.
3. The Java DOM API for XMLType sends the changed XML data back to Oracle
XML DB.
Figure 91 illustrates the Java DOM API for XMLType calling sequence.
oracle.xdb.dom.XMLDOMImplementation org.w3c.dom.DOMImplementation
oracle.xdb.dom.XMLElement org.w3c.dom.Element
oracle.xdb.dom.XMLNamedNodeMap org.w3c.dom.NamedNodeMap
oracle.xdb.dom.XMLNode org.w3c.dom.Node
Table 91 Java DOM API for XMLType: Classes (Cont.)
Java DOM API for XMLType Class
W3C DOM Interface Recommendation
Class
Java DOM API for XMLType Classes
Java API for XMLType 9-19
Figure 91 Java DOM API for XMLType: Calling Sequence
XMLType
Tables,
Columns,
Views
Oracle9i
Database
Oracle
XML DB
Oracle
XML DB
XMLType
Instance
XML DOM
Tree
Java DOM
API
Changed XML Data
Saved
back
in the
Database
getDOM()
Method
JDBC
JDBC
Java DOM API for XMLType Classes
9-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Part IV
Viewing Existing Data as XML
Part IV of this manual introduces you to ways you can view your existing data as
XML. It contains the following chapters:
I Chapter 10, "Generating XML Data from the Database"
I Chapter 11, "XMLType Views"
I Chapter 12, "Creating and Accessing Data Through URLs"
Generating XML Data from the Database 10-1
10
Generating XML Data from the Database
This chapter describes Oracle XML DB options for generating XML from the
database. It explains in detail, the SQLX standard functions and Oracle-provided
functions and packages for generating XML data from relational content.
It contains these sections:
I Oracle XML DB Options for Generating XML Data From Oracle9i Database
I Generating XML from the Database Using SQLX Functions
I XMLElement() Function
I XMLForest() Function
I XMLSEQUENCE() Function
I XMLConcat() Function
I XMLAgg() Function
I Generating XML from the Database Using SQLX Functions
I XMLColAttVal() Function
I Generating XML from Oracle9i Database Using DBMS_XMLGEN
I Generating XML Using Oracle-Provided SQL Functions
I SYS_XMLGEN() Function
I SYS_XMLAGG() Function
I Generating XML Using XSQL Pages Publishing Framework
I Generating XML Using XML SQL Utility (XSU)
Oracle XML DB Options for Generating XML Data From Oracle9i Database
10-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Options for Generating XML Data From Oracle9i
Database
Oracle9i supports native XML generation. In this release, Oracle provides you with
several new options for generating or regenerating XML data when stored in:
I Oracle9i database, in general
I Oracle9i database in XMLTypes columns and tables
Figure 101 illustrates the Oracle XML DB options you can use to generate XML
from Oracle9i database.
Generating XML Using SQLX Functions
The following SQLX functions are supported in Oracle XML DB:
I "XMLElement() Function" on page 10-5
I "XMLForest() Function" on page 10-9
I "XMLConcat() Function" on page 10-15
I "XMLAgg() Function" on page 10-17
Generating XML Using Oracle Extensions to SQLX
The following are Oracle extension functions to SQLX:
I "XMLColAttVal() Function" on page 10-20
Generating XML Using DBMS_XMLGEN
Oracle XML DB supports DBMS_XMLGEN, a PL/SQL supplied package. DBMS_
XMLGEN generates XML from SQL queries. See "Generating XML from Oracle9i
Database Using DBMS_XMLGEN" on page 10-21.
Generating XML Using SQL Functions
Oracle XML DB also supports the following Oracle-provided SQL functions that
generate XML from SQL queries:
I "SYS_XMLGEN() Function" on page 10-42. This operates on rows, generating
XML documents.
Oracle XML DB Options for Generating XML Data From Oracle9i Database
Generating XML Data from the Database 10-3
I "SYS_XMLAGG() Function" on page 10-51. This operates on groups of rows,
aggregating several XML documents into one.
I "XMLSEQUENCE() Function" on page 10-11. Note that only the cursor
version of this function generates XML. This function is also classied as an
SQLX function.
Generating XML with XSQL Pages Publishing Framework
"Generating XML Using XSQL Pages Publishing Framework" on page 10-52 can
also be used to generate XML from Oracle9i database.
XSQL Pages Publishing Framework, also known as XSQL Servlet, is part of the
XDK for Java.
Generating XML Using XML SQL Utility (XSU)
XML SQL Utility (XSU) enables you to perform the following tasks on data in
XMLType tables and columns:
I Transform data retrieved from object-relational database tables or views into
XML.
I Extract data froman XML document, and using a canonical mapping, insert the
data into appropriate columns or attributes of a table or a view.
I Extract data from an XML document and apply this data to updating or
deleting values of the appropriate columns or attributes.
See Also: "Generating XML Using XML SQL Utility (XSU)" on
page 10-54
Oracle XML DB Options for Generating XML Data From Oracle9i Database
10-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 101 Oracle XML DB Options for Generating XML from Oracle9i Database
See Also:
I Chapter 6, "Transforming and Validating XMLType Data"
I Chapter 8, "PL/SQL API for XMLType"
I Chapter 9, "Java API for XMLType"
I Oracle9i XML API Reference - XDK and Oracle XML DB
XDK for Java
Oracle9i Database
XSQL Pages
Publishing
Framework
XML SQL
Utility
(XSU)
SQLX Functions
XMLElement
XMLForest
XMLColAttVal
XMLConcat
XMLAgg
SQL Functions
SYS_XMLGEN
SYS_XMLAGG
XMLSequence
PL/SQL Package
DBMS_XMLGEN
Generated XML:
XMLType instances
XML as DOM
XML as String
XML Document
Varray of XMLType
Sequences
Forest of XML
Elements
Oracle XML DB
XMLType
Columns or
Tables
XMLElement() Function
Generating XML Data from the Database 10-5
Generating XML from the Database Using SQLX Functions
XMLElement(), XMLForest(), XMLConcat(), and XMLAgg() belong to the
SQLX standard, an emerging SQL standard for XML. Because these are emerging
standards the syntax and semantics of these functions are subject to change in the
future in order to conform to the standard.
All of the generation functions convert user-dened types (UDTs) to their canonical
XML format. In the canonical mapping the user-dened types attributes are
mapped to XML elements.
XMLElement() Function
XMLElement() function is based on the emerging SQL XML standard. It takes an
element name, an optional collection of attributes for the element, and zero or more
arguments that make up the elements content and returns an instance of type
XMLType. See Figure 102. The XML_attributes_clause is described in the following
section.
Figure 102 XMLElement() Syntax
It is similar to SYS_XMLGEN(), but unlike SYS_XMLGEN(), XMLElement() does
not create an XML document with the prolog (the XML version information). It
allows multiple arguments and can include attributes in the XML returned.
XMLElement() is primarily used to construct XML instances from relational data.
It takes an identier that is partially escaped to give the name of the root XML
element to be created. The identier does not have to be a column name, or column
reference, and cannot be an expression. If the identier specied is NULL, then no
element is returned.
As part of generating a valid XML element name from an SQL identier, characters
that are disallowed in an XML element name are escaped. Partial escaping implies
that SQL identiers other than the : sign which are not representable in XML, are
escaped using the # sign followed by the characters unicode representation in
hexadecimal format. This can be used to specify namespace prexes for the
XMLELEMENT (
NAME
identifier
, XML_attributes_clause , value_expr
,
)
XMLElement() Function
10-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
elements being generated. The fully escaped mapping escapes all non-XML
characters in the SQL identier name, including the : character.
XML_Attributes_Clause
XMLElement() also takes an optional XMLAttributes() clause, which species
the attributes of that element. This can be followed by a list of values that make up
the children of the newly created element. See Figure 103.
Figure 103 XML_attributes_clause Syntax
In the XMLAttributes() clause, the value expressions are evaluated to get the
values for the attributes. For a given value expression, if the AS clause is omitted,
the fully escaped form of the column name is used as the name of the attribute. If
the AS clause is specied, then the partially escaped form of the alias is used as the
name of the attribute. If the expression evaluates to NULL, then no attribute is
created for that expression. The type of the expression cannot be an object type or
collection.
The list of values that follow the XMLAttributes() clause are converted to XML
format, and are made as children of the top-level element. If the expression
evaluates to NULL, then no element is created for that expression.
Example 101 XMLElement(): Generating an Element for Each Employee
The following example produces an Emp XML element for each employee, with the
employees name as its content:
SELECT e.employee_id, XMLELEMENT ( "Emp", e.fname ||' ' || e.lname ) AS "result"
FROM employees e
WHERE employee_id > 200;
-- This query produces the following typical result:
-- ID result
-- --------------------
-- 1001 <Emp>John Smith</Emp>
-- 1206 <Emp>Mary Martin</Emp>
XMLATTRIBUTES ( value_expr
AS c_alias
,
)
XMLElement() Function
Generating XML Data from the Database 10-7
XMLElement() can also be nested to produce XML data with a nested structure.
Example 102 XMLElement(): Generating Nested XML
To produce an Emp element for each employee, with elements that provide the
employees name and start date:
SELECT XMLELEMENT("Emp", XMLELEMENT("name", e.fname ||' '|| e.lname),
XMLELEMENT ( "hiredate", e.hire)) AS "result"
FROM employees e
WHERE employee_id > 200 ;
This query produces the following typical XML result:
result
-----------------
<Emp>
<name>John Smith</name>
<hiredate>2000-05-24</hiredate>
</Emp>
<Emp>
<name>Mary Martin</name>
<hiredate>1996-02-01</hiredate>
</Emp>
Example 103 XMLElement(): Generating an Element for Each Employee with ID and
Name Attribute
This example produces an Emp element for each employee, with an id and name
attribute:
SELECT XMLELEMENT ( "Emp",
XMLATTRIBUTES (e.id,e.fname ||' ' || e.lname AS "name")) AS "result"
FROM employees e
WHERE employee_id > 200;
This query produces the following typical XML result fragment:
result
--------------
Note: Attributes, if they are specied, appear in the second
argument of XMLElement() as:
XMLATTRIBUTES (attribute, ).
XMLElement() Function
10-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<Emp ID="1001" name="John Smith"/>
<Emp ID="1206" name="Mary Martin"/>
If the name of the element or attribute is being created from the ALIAS specied in
the AS clause, then partially escaped mapping is used. If the name of the element or
attribute is being created from a column reference, then fully escaped mapping is
used. The following example illustrates these mappings:
SELECT XMLELEMENT ( "Emp:Exempt",
XMLATTRIBUTES ( e.fname, e.lname AS "name:last", e."name:middle")) AS "result"
FROM employees e
WHERE ... ;
This query could produce the following XML result:
<Emp:Exempt FNAME="John" name:last="Smith" name_x003A_middle="Quincy" /> ...
Example 104 XMLElement(): Using Namespaces to Create a Schema-Based XML
Document
The following example illustrates the use of namespaces to create an XML
schema-based document. Assuming that an XML schema
http://www.oracle.com/Employee.xsd exists and has no target
namespace, then the following query creates an XMLType instance conforming to
that schema:
SELECT XMLELEMENT ( "Employee",
XMLATTRIBUTES ( http://www.w3.org/2001/XMLSchema AS "xmlns:xsi",
http://www.oracle.com/Employee.xsd AS
"xsi:nonamespaceSchemaLocation" ),
XMLForest(empno, ename, sal)) AS "result"
FROM scott.emp
WHERE deptno = 100;
This creates an XML document that conforms to the Employee.xsd XMLSchema,
result:
--------------
Note: XMLElement() does not validate the document produced
with these namespace prexes and it is the responsibility of the
user to ensure that the appropriate namespace declarations are
included as well. A full description of partial and full escaping has
been specied as part of the emerging SQL XML standard.
XMLForest() Function
Generating XML Data from the Database 10-9
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema"
xsi:nonamespaceSchemaLocation="http://www.oracle.com/Employee.xsd">
<EMPNO>1769</EMPNO>
<ENAME>John</ENAME>
<SAL>200000</SAL>
</Employee>
Example 105 XMLElement(): Generating an Element from a UDT
Using the same example as given in the following DBMS_XMLGEN section
(Example 1018, "DBMS_XMLGEN: Generating Complex XML" on page 10-30), you
can generate a hierarchical XML for the employee, department example as follows:
SELECT XMLElement("Department",
dept_t(deptno,dname,
CAST(MULTISET(
select empno, ename
from emp e
where e.deptno = d.deptno) AS emplist_t)))
AS deptxml
FROM dept d;
This produces an XML document which contains the Department element and the
canonical mapping of the dept_t type.
<Department>
<DEPT_T DEPTNO="100">
<DNAME>Sports</DNAME>
<EMPLIST>
<EMP_T EMPNO="200">
<ENAME>John</ENAME>
<EMP_T>
<EMP_T>
<ENAME>Jack</ENAME>
</EMP_T>
</EMPLIST>
</DEPT_T>
</Department>
XMLForest() Function
XMLForest() function produces a forest of XML elements from the given list of
arguments. The arguments may be value expressions with optional aliases.
Figure 104 describes the XMLForest() syntax.
XMLForest() Function
10-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 104 XMLForest() Syntax
The list of value expressions are converted to XML format. For a given expression, if
the AS clause is omitted, the fully escaped form of the column name is used as the
name of the enclosing tag of the element.
For an object type or collection, the AS clause is mandatory, and for other types, it
can still be optionally specied. If the AS clause is specied, then the partially
escaped form of the alias is used as the name of the enclosing tag. If the expression
evaluates to NULL, then no element is created for that expression.
Example 106 XMLForest(): Generating Elements for Each Employee with Name
Attribute, Start Date, and Dept as Content
This example generates an Emp element for each employee, with a name attribute
and elements with the employees start date and department as the content.
SELECT XMLELEMENT("Emp", XMLATTRIBUTES ( e.fname ||' '|| e.lname AS "name" ),
XMLForest ( e.hire, e.dept AS "department")) AS "result"
FROM employees e;
This query might produce the following XML result:
<Emp name="John Smith">
<HIRE>2000-05-24</HIRE>
<department>Accounting</department>
</Emp>
<Emp name="Mary Martin">
<HIRE>1996-02-01</HIRE>
<department>Shipping</department>
</Emp>
Example 107 XMLForest(): Generating an Element from an UDT
You can also use XMLForest() to generate XML from user-dened types (UDTs).
Using the same example as given in the following DBMS_XMLGEN section
(Example 1018, "DBMS_XMLGEN: Generating Complex XML" on page 10-30), you
can generate a hierarchical XML for the employee, department example as follows:
SELECT XMLForest(
XMLFOREST ( value_expr
AS c_alias
,
)
XMLSEQUENCE() Function
Generating XML Data from the Database 10-11
dept_t(deptno,dname,
CAST(MULTISET(
select empno, ename
from emp e
where e.deptno = d.deptno) AS emplist_t)) AS "Department")
AS deptxml
FROM dept d;
This produces an XML document which contains the Department element and the
canonical mapping of the dept_t type.
<Department DEPTNO="100">
<DNAME>Sports</DNAME>
<EMPLIST>
<EMP_T EMPNO="200">
<ENAME>John</ENAME>
</EMP_T>
<EMP_T>
<ENAME>Jack</ENAME>
</EMP_T>
</EMPLIST>
</Department>
XMLSEQUENCE() Function
XMLSequence() function returns a sequence of XMLType. The function returns an
XMLSequenceType which is a VARRAY of XMLType instances. Since this function
returns a collection, it can be used in the FROM clause of SQL queries. See
Figure 105.
Figure 105 XMLSequence() Syntax
Note: Unlike in the XMLElement() case, the DEPT_T element is
missing.
XMLSEQUENCE (
XMLType_instance
sys_refcursor_instance
, fmt
)
XMLSEQUENCE() Function
10-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The XMLSequence() function has two forms
I The rst form inputs an XMLType instance and returns a VARRAY of top-level
nodes. This form can be used to shred XML fragments into multiple rows.
I The second form takes as input a REFCURSOR argument, with an optional
instance of the XMLFormat object and returns the VARRAY of XMLTypes
corresponding to each row of the cursor. This form can be used to construct
XMLType instances from arbitrary SQL queries. Note that in this release, this
use of XMLFormat does not support XML schemas.
XMLSequence() is essential for effective SQL queries involving XMLTypes.
Example 108 XMLSequence(): Generating One XML Document from Another
Suppose you had the following XML document containing employee information:
<EMPLOYEES>
<EMP>
<EMPNO>112</EMPNO>
<EMPNAME>Joe</EMPNAME>
<SALARY>50000</SALARY>
</EMP>
<EMP>
<EMPNO>217</EMPNO>
<EMPNAME>Jane</EMPNAME>
<SALARY>60000</SALARY>
</EMP>
<EMP>
<EMPNO>412</EMPNO>7
<EMPNAME>Jack</EMPNAME>
<SALARY>40000</SALARY>
</EMP>
</EMPLOYEES>
To create a newXML document containing only those employees who make $50,000
or more for each year, you can use the following syntax:
SELECT SYS_XMLAGG(value(e), xmlformat('EMPLOYEES'))
FROM TABLE(XMLSequence(Extract(doc, '/EMPLOYEES/EMP'))) e
WHERE EXTRACTVALUE(value(e), '/EMP/SALARY') >= 50000;
This returns the following XML document:
<EMPLOYEES>
<EMP>
<EMPNO>112</EMPNO>
XMLSEQUENCE() Function
Generating XML Data from the Database 10-13
<EMPNAME>Joe</EMPNAME>
<SALARY>50000</SALARY>
</EMP>
<EMP>
<EMPNO>217</EMPNO>
<EMPNAME>Jane</EMPNAME>
<SALARY>60000</SALARY>
</EMP>
</EMPLOYEES>
Notice howXMLExtract() was used to extract out all the employees:
1. XMLExtract() returns a fragment of EMP elements.
2. XMLSequence() creates a collection of these top level elements into XMLType
instances and returns that.
3. The TABLE function was then used to makes the collection into a table value
which can be used in the FROM clause of queries.
Example 109 XMLSequence(): Generating An XML Document for Each Row of a
Cursor Expression, Using SYS_REFCURSOR Argument
Here XMLSequence() creates an XML document for each row of the cursor
expression and returns the value as an XMLSequenceType. The XMLFormat object
can be used to inuence the structure of the resulting XML documents. For
example, a call such as:
SELECT value(e).getClobVal()
FROM TABLE(XMLSequence(Cursor(SELECT * FROM emp))) e;
might return the following XML:
XMLType
---------------------------------
<ROW>
<EMPNO>300</EMPNO>
<ENAME>John</ENAME>
</ROW>
<ROW>
<EMPNO>413</EMPNO>
<ENAME>Jane</ENAME>
</ROW>
<ROW>
XMLSEQUENCE() Function
10-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<EMPNO>968</EMPNO>
<ENAME>Jack</ENAME>
</ROW>
...
The row tag used for each row can be changed using the XMLFormat object.
Example 1010 XMLSequence(): Unnesting Collections inside XML Documents into
SQL Rows
XMLSequence() being a TABLE function, can be used to unnest the elements
inside an XML document. If you have a XML documents such as:
<Department deptno="100">
<DeptName>Sports</DeptName>
<EmployeeList>
<Employee empno="200">
<Ename>John</Ename>
<Salary>33333</Salary>
</Employee>
<Employee empno="300">
<Ename>Jack</Ename>
<Salary>333444</Salary>
</Employee>
</EmployeeList>
</Department>
<Department deptno="200">
<DeptName>Garment</DeptName>
<EmployeeList>
<Employee empno="400">
<Ename>Marlin</Ename>
<Salary>20000</Salary>
</Employee>
</EmployeeList>
</Department>
stored in an XMLType table dept_xml_tab, you can use the XMLSequence()
function to unnest the Employee list items as top level SQL rows:
CREATE TABLE dept_xml_tab OF XMLTYPE;
INSERT INTO dept_xml_tab VALUES(
xmltype(<Department deptno="100">
<DeptName>Sports</DeptName><EmployeeList>
<Employee empno="200"><Ename>John</Ename><Salary>33333</Salary></Employee>
XMLConcat() Function
Generating XML Data from the Database 10-15
<Employee empno="300"><Ename>Jack</Ename><Salary>333444</Salary></Employee>
</EmployeeList></Department>));
INSERT INTO dept_xml_tab VALUES (
xmltype(<Department deptno="200">
<DeptName>Sports</DeptName><EmployeeList>
<Employee empno="400"><Ename>Marlin</Ename><Salary>20000</Salary></Employee>
</EmployeeList></Department>));
SELECT extractvalue(value(d),/Department/@deptno) as deptno,
extractvalue(value(e),/Employee/@empno) as empno,
extractvalue(value(e),/Employee/Ename) as ename
FROM dept_xml_tab d,
TABLE(XMLSequence(extract(value(d),/Department/EmployeeList/Employee))) e;
This returns the following:
DEPTNO EMPNO ENAME
---------------------------------
100 200 John
100 300 Jack
200 400 Marlin
3 rows selected
For each row in table dept_xml_tab, the TABLE function is evaluated. Here, the
extract() function creates a newXMLType instance that contains a fragment of
all employee elements. This is fed to the XMLSequence() which creates a collection
of all employees.
The TABLE function then explodes the collection elements into multiple rows which
are correlated with the parent table dept_xml_tab. Thus you get a list of all the
parent dept_xml_tab rows with the associated employees.
The extractValue() functions extract out the scalar values for the department
number, employee number, and name.
XMLConcat() Function
XMLConcat() function concatenates all the arguments passed in to create a XML
fragment. Figure 106 shows the XMLConcat() syntax. XMLConcat() has two
forms:
I The rst form takes an XMLSequenceType, which is a VARRAY of XMLType
and returns a single XMLType instance that is the concatenation of all of the
XMLConcat() Function
10-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
elements of the varray. This form is useful to collapse lists of XMLTypes into a
single instance.
I The second form takes an arbitrary number of XMLType values and
concatenates them together. If one of the value is null, it is ignored in the result.
If all the values are NULL, the result is NULL. This form is used to concatenate
arbitrary number of XMLType instances in the same row. XMLAgg() can be
used to concatenate XMLType instances across rows.
Figure 106 XMLConcat() Syntax
Example 1011 XMLConcat(): Returning a Concatenation of XML Elements Used in
the Argument Sequence
This example shows howXMLConcat() returns the concatenation of XMLTypes
from the XMLSequenceType:
SELECT XMLConcat(XMLSequenceType(
xmltype('<PartNo>1236</PartNo>'),
xmltype('<PartName>Widget</PartName>'),
xmltype('<PartPrice>29.99</PartPrice>'))).getClobVal()
FROM dual;
returns a single fragment of the form:
<PartNo>1236</PartNo>
<PartName>Widget</PartName>
<PartPrice>29.99</PartPrice>
Example 1012 XMLConcat(): Returning XML Elements By Concatenating the
Elements in the Arguments
The following example creates an XML element for the rst and the last names and
then concatenates the result:
SELECT XMLConcat ( XMLElement ("first", e.fname), XMLElement ("last", e.lname))
AS "result"
FROM employees e ;
This query might produce the following XML document:
XMLCONCAT ( XMLType_instance
,
)
XMLAgg() Function
Generating XML Data from the Database 10-17
<first>Mary</first>
<last>Martin</last>
<first>John</first>
<last>Smith</last>
XMLAgg() Function
XMLAgg() is an aggregate function that produces a forest of XML elements from a
collection of XML elements. Figure 107 describes the XMLAgg() syntax, where the
order_by_clause is:
ORDER BY [list of: expr [ASC|DESC] [NULLS {FIRST|LAST} ] ]
and number literals are not interpreted as column positions. For example, ORDER
BY 1 does not mean order by the rst column. Instead the number literals are
interpreted just as any other literal.
As with XMLConcat(), any arguments that are null are dropped from the result.
XMLAgg() function is similar to the SYS_XMLAGG() function except that it returns
a forest of nodes, and does not take the XMLFormat() parameter. This function can
be used to concatenate XMLType instances across multiple rows. It also allows an
optional ORDER BY clause to order the XML values being aggregated.
XMLAgg() is an aggregation function and hence produces one aggregated XML
result for each group. If there is no group by specied in the query, then it returns a
single aggregated XML result for all the rows of the query. NULL values are
dropped from the result.
Figure 107 XMLAgg() Syntax
Example 1013 XMLAgg(): Generating Department Elements with a List of Employee
Elements
The following example produces a Department element containing Employee
elements with employee job ID and last name as the contents of the elements. It also
orders the employee XML elements within the department by their last name.
SELECT XMLELEMENT("Department",
XMLAGG(
XMLAGG ( XMLType_instance
order_by_clause
)
XMLAgg() Function
10-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XMLELEMENT("Employee", e.job_id|| ||e.last_name)
ORDER BY last_name))
as "Dept_list"
FROM employees e
WHERE e.department_id = 30;
Dept_list
-------------------------------------------------------------
<Department>
<Employee>PU_CLERK Baida</Employee>
<Employee>PU_CLERK Colmenares</Employee>
<Employee>PU_CLERK Himuro</Employee>
<Employee>PU_CLERK Khoo</Employee>
<Employee>PU_MAN Raphaely</Employee>
<Employee>PU_CLERK Tobias</Employee>
</Department>
The result is a single row, because XMLAgg() aggregates the rows. You can use the
GROUP BY clause to group the returned set of rows into multiple groups:
SELECT XMLELEMENT("Department", XMLAttributes(department_id AS deptno),
XMLAGG(XMLELEMENT("Employee", e.job_id|| ||e.last_name)))
AS "Dept_list"
FROM employees e
GROUP BY e.department_id;
Dept_list
---------------------------------------------------------
<Department deptno="1001">
<Employee>AD_ASST Whalen</Employee>
</Department>
<Department deptno="2002">
<Employee>MK_MAN Hartstein</Employee>
<Employee>MK_REP Fay</Employee>
</Department>
<Department deptno="3003">
<Employee>PU_MAN Raphaely</Employee>
<Employee>PU_CLERK Khoo</Employee>
<Employee>PU_CLERK Tobias</Employee>
<Employee>PU_CLERK Baida</Employee>
<Employee>PU_CLERK Colmenares</Employee>
<Employee>PU_CLERK Himuro</Employee>
</Department>
XMLAgg() Function
Generating XML Data from the Database 10-19
You can order the employees within each department by using the ORDER BY
clause inside the XMLAgg() expression.
Example 1014 XMLAgg(): Generating Department Elements, Employee Elements Per
Department, and Employee Dependents
XMLAgg() can be used to reect the hierarchical nature of some relationships that
exist in tables. The following example generates a department element for each
department. Within this it creates elements for all employees of the department.
Within each employee, it lists their dependents:
SELECT XMLELEMENT( "Department", XMLATTRIBUTES ( d.dname AS "name" ),
(SELECT XMLAGG(XMLELEMENT ("emp", XMLATTRIBUTES (e.ename AS name),
( SELECT XMLAGG(XMLELEMENT( "dependent",
XMLATTRIBUTES(de.name AS "name")))
FROM dependents de
WHERE de.empno = e.empno ) ))
FROM emp e
WHERE e.deptno = d.deptno) ) AS "dept_list"
FROM dept d ;
The query might produce a row containing the XMLType instance for each
department:
<Department name="Accounting">
<emp name="Smith">
<dependent name="Sara Smith"/d>
<dependent name="Joyce Smith"/>
</emp>
<emp name="Yates"/>
</Department>
<Department name="Shipping">
<emp name="Martin">
<dependent name="Alan Martin"/>
</emp>
<emp name="Oppenheimer">
<dependent name="Ellen Oppenheimer"/>
</emp>
Note: Within the order_by_clause, Oracle does not interpret
number literals as column positions, as it does in other uses of this
clause, but simply as number literals.
Generating XML from the Database Using SQLX Functions
10-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</Department>
Generating XML from the Database Using SQLX Functions
XMLColAttVal() is an Oracle SQLX extension function.
XMLColAttVal() Function
XMLColAttVal() function generates a forest of XML column elements containing
the value of the arguments passed in. Figure 108 shows the XMLColAttVal()
syntax.
Figure 108 XMLColAttVal() Syntax
The name of the arguments are put in the name attribute of the column element.
Unlike the XMLForest() function, the name of the element is not escaped in any
way and hence this function can be used to transport SQL columns and values
without escaped names.
Example 1015 XMLColAttVal(): Generating an Emp Element Per Employee with
Name Attribute and Elements with Start Date and Dept as Content
This example generates an Emp element for each employee, with a name attribute
and elements with the employees start date and department as the content.
SELECT XMLELEMENT("Emp",XMLATTRIBUTES(e.fname ||' '||e.lname AS "name" ),
XMLCOLATTVAL ( e.hire, e.dept AS "department")) AS "result"
FROM employees e;
This query might produce the following XML result:
<Emp name="John Smith">
<column name="HIRE">2000-05-24</column>
<column name="department">Accounting</column>
</Emp>
<Emp name="Mary Martin">
<column name="HIRE">1996-02-01</column>
XMLCOLATTVAL ( value_expr
AS c_alias
,
)
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-21
<column name="department">Shipping</column>
</Emp>
<Emp name="Samantha Stevens">
<column name="HIRE">1992-11-15</column>
<column name="department">Standards</column>
</Emp>
Because the name associated with each XMLColAttVal() argument is used to
populate an attribute value, neither the fully escaped mapping nor the partially
escaped mapping is used.
Generating XML from Oracle9i Database Using DBMS_XMLGEN
DBMS_XMLGEN creates XML documents from any SQL query by mapping the
database query results into XML. It gets the XML document as a CLOB or XMLType.
It provides a fetch interface whereby you can specify the maximum rows and
rows to skip. This is useful for pagination requirements in Web applications. DBMS_
XMLGEN also provides options for changing tag names for ROW, ROWSET, and so on.
The parameters of the package can restrict the number of rows retrieved, the
enclosing tag names. To summarize, DBMS_XMLGEN PL/SQL package allows you:
I To create an XML document instance from any SQL query and get the
document as a CLOB or XMLType.
I To use a fetch interface with maximum rows and rows to skip. For example,
the rst fetch could retrieve a maximum of 10 rows, skipping the rst four. This
is useful for pagination in Web-based applications.
I Options for changing tag names for ROW, ROWSET, and so on.
Sample DBMS_XMLGEN Query Result
The following shows a sample result from executing a select * from scott.emp
query on a database:
<?xml version="1.0"?>
<ROWSET>
<ROW>
<EMPNO>30</EMPNO>
<ENAME>Scott</ENAME>
See Also: "Generating XML with XSUs OracleXMLQuery", in
Chapter 7, "XML SQL Utility (XSU)", and compare the functionality
of OracleXMLQuery with DBMS_XMLGEN.
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<SALARY>20000</SALARY>
</ROW>
<ROW>
<EMPNO>30</EMPNO>
<ENAME>Mary</ENAME>
<AGE>40</AGE>
</ROW>
</ROWSET>
The result of the getXML() using DBMS_XMLGen package is a CLOB. The default
mapping is as follows:
I Every row of the query result maps to an XML element with the default tag
name ROW.
I The entire result is enclosed in a ROWSET element. These names are both
congurable, using the setRowTagName() and setRowSetTagName()
procedures in DBMS_XMLGEN.
I Each column in the SQL query result, maps as a subelement of the ROW element.
I Binary data is transformed to its hexadecimal representation.
When the document is in a CLOB, it has the same encoding as the database
character set. If the database character set is SHIFTJIS, then the XML document is
SHIFTJIS.
DBMS_XMLGEN Calling Sequence
Figure 109 summarizes the DBMS_XMLGEN calling sequence.
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-23
Figure 109 DBMS_XMLGEN Calling Sequence
Here is DBMS_XMLGENs calling sequence:
1. Get the context from the package by supplying a SQL query and calling the
newContext() call.
2. Pass the context to all the procedures/functions in the package to set the
various options. For example to set the ROW elements name, use
setRowTag(ctx), where ctx is the context got from the previous
newContext() call.
3. Get the XML result, using the getXML() or getXMLType(). By setting the
maximum rows to be retrieved for each fetch using the setMaxRows() call,
you can call this function repeatedly, getting the maximum number of row set
for each call. The function returns null if there are no rows left in the query.
getXML() and getXMLType() always return an XML document, even if there
were no rows to retrieve. If you want to know if there were any rows retrieved,
use the function getNumRowsProcessed().
4. You can reset the query to start again and repeat step 3.
set
the options
REGISTER
Query
close
User / Browser /
Client /
Application
bind
values
Generated
XML
as DOM
User / Browser
Client /
Application
Generated
XML
as String
fetch
XML
Using DBMS_XMLGEN to Generate XML
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
5. Close the closeContext() to free up any resource allocated inside.
Table 101 summarizes DBMS_XMLGEN functions and procedures.
Table 101 DBMS_XMLGEN Functions and Procedures
Function or Procedure Description
DBMS_XMLGEN Type denitions
SUBTYPE ctxHandle IS NUMBER
The context handle used by all functions.
DTD or schema specications:
NONE CONSTANT NUMBER:= 0; -- supported for this release.
DTD CONSTANT NUMBER:= 1;
SCHEMA CONSTANT NUMBER:= 2;
Can be used in getXML function to specify whether to generate a DTD
or XML Schema or none. Only the NONE specication is supported in
the getXML functions for this release.
FUNCTION PROTOTYPES
newContext()
Given a query string, generate a new context handle to be used in
subsequent functions.
FUNCTION
newContext(queryString IN VARCHAR2)
Returns a new context
PARAMETERS: queryString (IN)- the query string, the result of which
needs to be converted to XML
RETURNS: Context handle. Call this function rst to obtain a handle
that you can use in the getXML() and other functions to get the XML
back from the result.
FUNCTION
newContext(queryString IN SYS_REFCURSOR)
RETURN ctxHandle;
Creates a new context handle from a passed in PL/SQL ref cursor. The
context handle can be used for the rest of the functions. See the example:
setRowTag() Sets the name of the element separating all the rows. The default name is
ROW.
PROCEDURE
setRowTag(ctx IN ctxHandle,rowTag IN
VARCHAR2);
PARAMETERS:
ctx (IN) - the context handle obtained from the newContext call,
rowTag (IN) - the name of the ROW element. NULL indicates that you
do not want the ROW element to be present. Call this function to set the
name of the ROW element, if you do not want the default ROW name
to show up. You can also set this to NULL to suppress the ROW element
itself. Its an error if both the row and the rowset are null and there is
more than one column or row in the output.
setRowSetTag() Sets the name of the documents root element. The default name is
ROWSET
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-25
PROCEDURE
setRowSetTag(ctx IN ctxHandle, rowSetTag IN
VARCHAR2);
PARAMETERS:
ctx (IN) - the context handle obtained from the newContext call,
rowsetTag (IN) - the name of the document element. NULL indicates
that you do not want the ROW element to be present. Call this to set the
name of the document root element, if you do not want the default
ROWSET name in the output. You can also set this to NULL to
suppress the printing of this element. However, this is an error if both
the row and the rowset are null and there is more than one column or
row in the output.
getXML() Gets the XML document by fetching the maximum number of rows
specied. It appends the XML document to the CLOB passed in.
PROCEDURE
getXML(ctx IN ctxHandle,
clobval IN OUT NCOPY clob,
dtdOrSchema IN number:= NONE);
PARAMETERS:
ctx (IN) - The context handle obtained from the newContext() call,
clobval (IN/OUT) - the clob to which the XML document is to be
appended,
dtdOrSchema (IN) - whether you should generate the DTD or Schema.
This parameter is NOT supported.
Use this version of the getXML function, to avoid any extra CLOB copies
and if you want to reuse the same CLOB for subsequent calls. This
getXML call is more efcient than the next avor, though this involves
that you create the lob locator. When generating the XML, the number of
rows indicated by the setSkipRows call are skipped, then the maximum
number of rows as specied by the setMaxRows call (or the entire result
if not specied) is fetched and converted to XML. Use the
getNumRowsProcessed function to check if any rows were retrieved or
not.
getXML() Generates the XML document and returns it as a CLOB.
FUNCTION
getXML(ctx IN ctxHandle, dtdOrSchema IN
number:= NONE) RETURN clob
PARAMETERS: ctx (IN) - The context handle obtained from the
newContext() call,
dtdOrSchema (IN) - whether we should generate the DTD or Schema.
This parameter is NOT supported.
RETURNS: A temporary CLOB containing the document. Free the
temporary CLOB obtained from this function using the dbms_
lob.freetemporary call.
FUNCTION
getXMLType(ctx IN ctxHandle, dtdOrSchema IN
number:= NONE) RETURN XMLTYPE
PARAMETERS: ctx (IN) - The context handle obtained from the
newContext() call,
dtdOrSchema (IN) - whether we should generate the DTD or Schema.
This parameter is NOT supported.
RETURNS: An XMLType instance containing the document.
Table 101 DBMS_XMLGEN Functions and Procedures (Cont.)
Function or Procedure Description
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
FUNCTION
getXML(sqlQuery IN VARCHAR2, dtdOrSchema
IN NUMBER := NONE) RETURN CLOB;
Converts the query results from the passed in SQL query string to XML
format, and returns the XML as a CLOB.
FUNCTION
getXMLType(sqlQuery IN VARCHAR2,
dtdOrSchema IN NUMBER := NONE) RETURN
XMLTYPE;
Converts the query results from the passed in SQL query string to XML
format, and returns the XML as a CLOB.
getNumRowsProcessed() Gets the number of SQL rows processed when generating the XML
using the getXML call. This count does not include the number of rows
skipped before generating the XML.
FUNCTION
getNumRowsProcessed(ctx IN ctxHandle)
RETURN number
PARAMETERS: queryString (IN)- the query string, the result of which
needs to be converted to XML RETURNS:
This gets the number of SQL rows that were processed in the last call to
getXML. You can call this to nd out if the end of the result set has been
reached. This does not include the number of rows skipped. Use this
function to determine the terminating condition if you are calling
getXML in a loop. Note that getXML would always generate a XML
document even if there are no rows present.
setMaxRows() Sets the maximum number of rows to fetch from the SQL query result
for every invocation of the getXML call.
PROCEDURE
setMaxRows(ctx IN ctxHandle, maxRows IN
NUMBER);
PARAMETERS: ctx (IN) - the context handle corresponding to the query
executed,
maxRows (IN) - the maximum number of rows to get for each call to
getXML.
The maxRows parameter can be used when generating paginated results
using this utility. For instance when generating a page of XML or HTML
data, you can restrict the number of rows converted to XML and then in
subsequent calls, you can get the next set of rows and so on. This also
can provide for faster response times.
setSkipRows() Skips a given number of rows before generating the XML output for
every call to the getXML routine.
PROCEDURE
setSkipRows(ctx IN ctxHandle,
skipRows IN NUMBER);
PARAMETERS: ctx (IN) - the context handle corresponding to the query
executed,
skipRows (IN) - the number of rows to skip for each call to getXML.
The skipRows parameter can be used when generating paginated results
for stateless web pages using this utility. For instance when generating
the rst page of XML or HTML data, you can set skipRows to zero. For
the next set, you can set the skipRows to the number of rows that you
got in the rst case.
Table 101 DBMS_XMLGEN Functions and Procedures (Cont.)
Function or Procedure Description
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-27
setConvertSpecialChars() Sets whether special characters in the XML data need to be converted
into their escaped XML equivalent or not. For example, the "<" sign is
converted to &lt;. The default is to perform conversions.
PROCEDURE
setConvertSpecialChars(ctx IN ctxHandle,
conv IN boolean);
PARAMETERS: ctx (IN) - the context handle to use,
conv (IN) - true indicates that conversion is needed.
You can use this function to speed up the XML processing whenever you
are sure that the input data cannot contain any special characters such as
<, >, ", , and so on, which need to be escaped. Note that it is expensive
to actually scan the character data to replace the special characters,
particularly if it involves a lot of data. So in cases when the data is
XML-safe, then this function can be called to improve performance.
useItemTagsForColl() Sets the name of the collection elements. The default name for collection
elements it the type name itself. You can override that to use the name of
the column with the _ITEM tag appended to it using this function.
PROCEDURE useItemTagsForColl(ctx IN
ctxHandle);
PARAMETERS: ctx (IN) - the context handle.
If you have a collection of NUMBER, say, the default tag name for the
collection elements is NUMBER. You can override this behavior and
generate the collection column name with the _ITEM tag appended to it,
by calling this procedure.
restartQuery() Restarts the query and generate the XML from the rst row again.
PROCEDURE
restartQuery(ctx IN ctxHandle);
PARAMETERS: ctx (IN) - the context handle corresponding to the
current query. You can call this to start executing the query again,
without having to create a new context.
closeContext() Closes a given context and releases all resources associated with that
context, including the SQL cursor and bind and dene buffers, and so
on.
PROCEDURE
closeContext(ctx IN ctxHandle);
PARAMETERS: ctx (IN) - the context handle to close. Closes all
resources associated with this handle. After this you cannot use
the handle for any other DBMS_XMLGEN function call.
Conversion Functions
FUNCTION
convert(xmlData IN varchar2, ag IN NUMBER :=
ENTITY_ENCODE) return varchar2;
Encodes or decodes the passed in XML data string.
I Encoding refers to replacing entity references such as '<' to
their escaped equivalent, such as '&lt;'.
I Decoding refers to the reverse conversion.
FUNCTION
convert(xmlData IN CLOB, ag IN NUMBER :=
ENTITY_ENCODE) return CLOB;
Encodes or decodes the passed in XML CLOB data.
I Encoding refers to replacing entity references such as '<' to
their escaped equivalent, such as '&lt;'.
I Decoding refers to the reverse conversion.
Table 101 DBMS_XMLGEN Functions and Procedures (Cont.)
Function or Procedure Description
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 1016 DBMS_XMLGEN: Generating Simple XML
This example creates an XML document by selecting out the employee data froman
object-relational table and putting the resulting CLOB into a table.
CREATE TABLE temp_clob_tab(result CLOB);
DECLARE
qryCtx DBMS_XMLGEN.ctxHandle;
result CLOB;
BEGIN
qryCtx := dbms_xmlgen.newContext('SELECT * from scott.emp');
-- set the row header to be EMPLOYEE
DBMS_XMLGEN.setRowTag(qryCtx, 'EMPLOYEE');
-- now get the result
result := DBMS_XMLGEN.getXML(qryCtx);
INSERT INTO temp_clob_tab VALUES(result);
--close context
DBMS_XMLGEN.closeContext(qryCtx);
END;
/
This query example generates the following XML:
SELECT * FROM temp_clob_tab;
RESULT
------------------------------------
<?xml version=''1.0''?>
<ROWSET>
<EMPLOYEE>
<EMPNO>7369</EMPNO>
<ENAME>SMITH</ENAME>
<JOB>CLERK</JOB>
<MGR>7902</MGR>
<HIREDATE>17-DEC-80</HIREDATE>
<SAL>800</SAL>
<DEPTNO>20</DEPTNO>
</EMPLOYEE>
<EMPLOYEE>
<EMPNO>7499</EMPNO>
<ENAME>ALLEN</ENAME>
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-29
<JOB>SALESMAN</JOB>
<MGR>7698</MGR>
<HIREDATE>20-FEB-81</HIREDATE>
<SAL>1600</SAL>
<COMM>300</COMM>
<DEPTNO>30</DEPTNO>
</EMPLOYEE>
...
</ROWSET>
Example 1017 DBMS_XMLGEN: Generating Simple XML with Pagination
Instead of generating all the XML for all rows, you can use the fetch interface that
DBMS_XMLGEN provides to retrieve a xed number of rows each time. This speeds
up response time and also can help in scaling applications that need a DOM API on
the resulting XML, particularly if the number of rows is large.
The following example illustrates howto use DBMS_XMLGEN to retrieve results from
table scott.emp:
-- create a table to hold the results..!
CREATE TABLE temp_clob_tab ( result clob);
declare
qryCtx dbms_xmlgen.ctxHandle;
result CLOB;
begin
-- get the query context;
qryCtx := dbms_xmlgen.newContext('select * from scott.emp');
-- set the maximum number of rows to be 5,
dbms_xmlgen.setMaxRows(qryCtx, 5);
loop
-- now get the result
result := dbms_xmlgen.getXML(qryCtx);
-- if there were no rows processed, then quit..!
exit when dbms_xmlgen.getNumRowsProcessed(qryCtx) = 0;
-- do some processing with the lob data..!
-- Here, we are inserting the results
-- into a table. You can print the lob out, output it to a stream,
-- put it in a queure
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
-- or do any other processing.
insert into temp_clob_tab values(result);
end loop;
--close context
dbms_xmlgen.closeContext(qryCtx);
end;
/
Here, for each set of 5 rows, you generate an XML document.
Example 1018 DBMS_XMLGEN: Generating Complex XML
Complex XML can be generated using object types to represent nested structures:
CREATE TABLE new_departments (
department_id NUMBER PRIMARY KEY,
department_name VARCHAR2(20)
);
CREATE TABLE new_employees (
employee_id NUMBER PRIMARY KEY,
last_name VARCHAR2(20),
department_id NUMBER REFERENCES new_departments
);
CREATE TYPE emp_t AS OBJECT(
"@employee_id" NUMBER,
last_name VARCHAR2(20)
);
/
CREATE TYPE emplist_t AS TABLE OF emp_t;
/
CREATE TYPE dept_t AS OBJECT(
"@department_id" NUMBER,
department_name VARCHAR2(20),
emplist emplist_t
);
/
qryCtx := dbms_xmlgen.newContext
('SELECT dept_t(department_id, department_name,
CAST(MULTISET
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-31
(SELECT e.employee_id, e.last_name
FROM new_employees e
WHERE e.department_id = d.department_id)
AS emplist_t)) AS deptxml
FROM new_departments d');
DBMS_XMLGEN.setRowTag(qryCtx, NULL);
-- Here is the resulting XML:
-- <ROWSET>
-- <DEPTXML DEPARTMENT_ID="10">
-- <DEPARTMENT_NAME>SALES</DEPARTMENT_NAME>
-- <EMPLIST>
-- <EMP_T EMPLOYEE_ID="30">
-- <LAST_NAME>Scott</LAST_NAME>
-- </EMP_T>
-- <EMP_T EMPLOYEE_ID="31">
-- <LAST_NAME>Mary</LAST_NAME>
-- </EMP_T>
-- </EMPLIST>
-- </DEPTXML>
-- <DEPTXML DEPARTMENT_ID="20">
-- ...
-- </ROWSET>
Now, you can select the LOB data from the temp_clob_Tab table and verify the
results. The result looks like the sample result shown in the previous section,
"Sample DBMS_XMLGEN Query Result" on page 10-21.
With relational data, the results are a at non-nested XML document. To obtain
nested XML structures, you can use object-relational data, where the mapping is as
follows:
I Object types map as an XML element -- see Chapter 5, "Structured Mapping of
XMLType".
I Attributes of the type, map to sub-elements of the parent element
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 1019 DBMS_XMLGEN: Generating Complex XML #2 - Inputting User
Dened Types For Nested XML Documents
When you input a user-dened type (UDT) value to DBMS_XMLGEN functions, the
user-dened type is mapped to an XML document using canonical mapping. In the
canonical mapping, user-dened types attributes are mapped to XML elements.
Attributes with names starting with @ are mapped to attributes of the preceding
element.
User-dened types can be used for nesting in the resulting XML document. For
example, consider tables, EMP and DEPT:
CREATE TABLE DEPT
(
deptno number primary key,
dname varchar2(20)
);
CREATE TABLE EMP
(
empno number primary key,
ename varchar2(20),
deptno number references dept
);
To generate a hierarchical view of the data, that is, departments with employees in
them, you can dene suitable object types to create the structure inside the database
as follows:
CREATE TYPE EMP_T AS OBJECT
(
"@empno" number, -- empno defined as an attribute!
ename varchar2(20)
);
/
-- You have defined the empno with an @ sign in front, to denote that it must
-- be mapped as an attribute of the enclosing Employee element.
Note: Complex structures can be obtained by using object types
and creating object views or object tables. A canonical mapping is
used to map object instances to XML.
The @ sign, when used in column or attribute names, is translated
into an attribute of the enclosing XML element in the mapping.
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-33
CREATE TYPE EMPLIST_T AS TABLE OF EMP_T;
/
CREATE TYPE DEPT_T AS OBJECT
(
"@deptno" number,
dname varchar2(20),
emplist emplist_t
);
/
-- Department type, DEPT_T, denotes the department as containing a list of
-- employees. You can now query the employee and department tables and get
-- the result as an XML document, as follows:
declare
qryCtx dbms_xmlgen.ctxHandle;
result CLOB;
begin
-- get the query context;
qryCtx := dbms_xmlgen.newContext(
'SELECT
dept_t(deptno,dname,
CAST(MULTISET(select empno, ename
from emp e
where e.deptno = d.deptno) AS emplist_t)) AS deptxml
FROM dept d');
-- set the maximum number of rows to be 5,
dbms_xmlgen.setMaxRows(qryCtx, 5);
-- set no row tag for this result as we have a single ADT column
dbms_xmlgen.setRowTag(qryCtx,null);
loop
-- now get the result
result := dbms_xmlgen.getXML(qryCtx);
-- if there were no rows processed, then quit..!
exit when dbms_xmlgen.getNumRowsProcessed(qryCtx) = 0;
-- do whatever with the result..!
end loop;
end;
/
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The MULTISET operator treats the result of the subset of employees working in the
department as a list and the CAST around it, cast's it to the appropriate collection
type. You then create a department instance around it and call the DBMS_XMLGEN
routines to create the XML for the object instance. The result is:
-- <?xml version="1.0"?>
-- <ROWSET>
-- <DEPTXML deptno="10">
-- <DNAME>Sports</DNAME>
-- <EMPLIST>
-- <EMP_T empno="200">
-- <ENAME>John</ENAME>
-- </EMP_T>
-- <EMP_T empno="300">
-- <ENAME>Jack</ENAME>
-- </EMP_T>
-- </EMPLIST>
-- </DEPTXML>
-- <DEPTXML deptno="20">
-- <!-- .. other columns -->
-- </DEPTXML>
-- </ROWSET>
The default name ROW is not present because you set that to NULL. The deptno
and empno have become attributes of the enclosing element.
Example 1020 DBMS_XMLGEN: Generating a Purchase Order from the Database in
XML Format
This example uses DBMS_XMLGEN.getXMLType() to generate PurchaseOrder in
XML format from a relational database using object views. Note that the example is
ve pages long.
-- Create relational schema and define Object Views
-- Note: DBMS_XMLGEN Package maps UDT attributes names
-- starting with '@' to xml attributes
------------------------------------------------------
-- Purchase Order Object View Model
-- PhoneList Varray object type
CREATE TYPE PhoneList_vartyp AS VARRAY(10) OF VARCHAR2(20)
/
-- Address object type
CREATE TYPE Address_typ AS OBJECT (
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-35
Street VARCHAR2(200),
City VARCHAR2(200),
State CHAR(2),
Zip VARCHAR2(20)
)
/
-- Customer object type
CREATE TYPE Customer_typ AS OBJECT (
CustNo NUMBER,
CustName VARCHAR2(200),
Address Address_typ,
PhoneList PhoneList_vartyp
)
/
-- StockItem object type
CREATE TYPE StockItem_typ AS OBJECT (
"@StockNo" NUMBER,
Price NUMBER,
TaxRate NUMBER
)
/
-- LineItems object type
CREATE TYPE LineItem_typ AS OBJECT (
"@LineItemNo" NUMBER,
Item StockItem_typ,
Quantity NUMBER,
Discount NUMBER
)
/
-- LineItems Nested table
CREATE TYPE LineItems_ntabtyp AS TABLE OF LineItem_typ
/
-- Purchase Order object type
CREATE TYPE PO_typ AUTHID CURRENT_USER AS OBJECT (
PONO NUMBER,
Cust_ref REF Customer_typ,
OrderDate DATE,
ShipDate TIMESTAMP,
LineItems_ntab LineItems_ntabtyp,
ShipToAddr Address_typ
)
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
/
-- Create Purchase Order Relational Model tables
--Customer table
CREATE TABLE Customer_tab(
CustNo NUMBER NOT NULL,
CustName VARCHAR2(200) ,
Street VARCHAR2(200) ,
City VARCHAR2(200) ,
State CHAR(2) ,
Zip VARCHAR2(20) ,
Phone1 VARCHAR2(20),
Phone2 VARCHAR2(20),
Phone3 VARCHAR2(20),
constraint cust_pk PRIMARY KEY (CustNo)
)
ORGANIZATION INDEX OVERFLOW;
-- Purchase Order table
CREATE TABLE po_tab (
PONo NUMBER, /* purchase order no */
Custno NUMBER constraint po_cust_fk references Customer_tab,
/* Foreign KEY referencing customer */
OrderDate DATE, /* date of order */
ShipDate TIMESTAMP, /* date to be shipped */
ToStreet VARCHAR2(200), /* shipto address */
ToCity VARCHAR2(200),
ToState CHAR(2),
ToZip VARCHAR2(20),
constraint po_pk PRIMARY KEY(PONo)
);
--Stock Table
CREATE TABLE Stock_tab (
StockNo NUMBER constraint stock_uk UNIQUE,
Price NUMBER,
TaxRate NUMBER
);
--Line Items Table
CREATE TABLE LineItems_tab(
LineItemNo NUMBER,
PONo NUMBER constraint LI_PO_FK REFERENCES po_tab,
StockNo NUMBER ,
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-37
Quantity NUMBER,
Discount NUMBER,
constraint LI_PK PRIMARY KEY (PONo, LineItemNo)
);
-- create Object Views
--Customer Object View
CREATE OR REPLACE VIEW Customer OF Customer_typ
WITH OBJECT IDENTIFIER(CustNo)
AS SELECT c.Custno, C.custname,
Address_typ(C.Street, C.City, C.State, C.Zip),
PhoneList_vartyp(Phone1, Phone2, Phone3)
FROM Customer_tab c;
--Purchase order view
CREATE OR REPLACE VIEW PO OF PO_typ
WITH OBJECT IDENTIFIER (PONO)
AS SELECT P.PONo,
MAKE_REF(Customer, P.Custno),
P.OrderDate,
P.ShipDate,
CAST( MULTISET(
SELECT LineItem_typ( L.LineItemNo,
StockItem_typ(L.StockNo,S.Price,S.TaxRate),
L.Quantity, L.Discount)
FROM LineItems_tab L, Stock_tab S
WHERE L.PONo = P.PONo and S.StockNo=L.StockNo )
AS LineItems_ntabtyp),
Address_typ(P.ToStreet,P.ToCity, P.ToState, P.ToZip)
FROM PO_tab P;
-- create table with XMLType column to store po in XML format
create table po_xml_tab(
poid number,
poDoc XMLTYPE /* purchase order in XML format */
)
/
--------------------
-- Populate data
-------------------
-- Establish Inventory
INSERT INTO Stock_tab VALUES(1004, 6750.00, 2) ;
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
INSERT INTO Stock_tab VALUES(1011, 4500.23, 2) ;
INSERT INTO Stock_tab VALUES(1534, 2234.00, 2) ;
INSERT INTO Stock_tab VALUES(1535, 3456.23, 2) ;
-- Register Customers
INSERT INTO Customer_tab
VALUES (1, 'Jean Nance', '2 Avocet Drive',
'Redwood Shores', 'CA', '95054',
'415-555-1212', NULL, NULL) ;
INSERT INTO Customer_tab
VALUES (2, 'John Nike', '323 College Drive',
'Edison', 'NJ', '08820',
'609-555-1212', '201-555-1212', NULL) ;
-- Place Orders
INSERT INTO PO_tab
VALUES (1001, 1, '10-APR-1997', '10-MAY-1997',
NULL, NULL, NULL, NULL) ;
INSERT INTO PO_tab
VALUES (2001, 2, '20-APR-1997', '20-MAY-1997',
'55 Madison Ave', 'Madison', 'WI', '53715') ;
-- Detail Line Items
INSERT INTO LineItems_tab VALUES(01, 1001, 1534, 12, 0) ;
INSERT INTO LineItems_tab VALUES(02, 1001, 1535, 10, 10) ;
INSERT INTO LineItems_tab VALUES(01, 2001, 1004, 1, 0) ;
INSERT INTO LineItems_tab VALUES(02, 2001, 1011, 2, 1) ;
-------------------------------------------------------
-- Use DBMS_XMLGEN Package to generate PO in XML format
-- and store XMLTYPE in po_xml table
-------------------------------------------------------
declare
qryCtx dbms_xmlgen.ctxHandle;
pxml XMLTYPE;
cxml clob;
begin
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-39
-- get the query context;
qryCtx := dbms_xmlgen.newContext('
select pono,deref(cust_ref) customer,p.OrderDate,p.shipdate,
lineitems_ntab lineitems,shiptoaddr
from po p'
);
-- set the maximum number of rows to be 1,
dbms_xmlgen.setMaxRows(qryCtx, 1);
-- set rowset tag to null and row tag to PurchaseOrder
dbms_xmlgen.setRowSetTag(qryCtx,null);
dbms_xmlgen.setRowTag(qryCtx,'PurchaseOrder');
loop
-- now get the po in xml format
pxml := dbms_xmlgen.getXMLType(qryCtx);
-- if there were no rows processed, then quit..!
exit when dbms_xmlgen.getNumRowsProcessed(qryCtx) = 0;
-- Store XMLTYPE po in po_xml table (get the pono out)
insert into po_xml_tab (poid, poDoc)
values(
pxml.extract(//PONO/text()).getNumberVal(),
pxml);
end loop;
end;
/
---------------------------
-- list xml PurchaseOrders
---------------------------
set long 100000
set pages 100
select x.podoc.getClobVal() xpo
from po_xml_tab x;
This produces the following purchase order XML documents:
PurchaseOrder 1001:
<?xml version="1.0"?>
<PurchaseOrder>
<PONO>1001</PONO>
<CUSTOMER>
Generating XML from Oracle9i Database Using DBMS_XMLGEN
10-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<CUSTNO>1</CUSTNO>
<CUSTNAME>Jean Nance</CUSTNAME>
<ADDRESS>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
<ZIP>95054</ZIP>
</ADDRESS>
<PHONELIST>
<VARCHAR2>415-555-1212</VARCHAR2>
</PHONELIST>
</CUSTOMER>
<ORDERDATE>10-APR-97</ORDERDATE>
<SHIPDATE>10-MAY-97 12.00.00.000000 AM</SHIPDATE>
<LINEITEMS>
<LINEITEM_TYP LineItemNo="1">
<ITEM StockNo="1534">
<PRICE>2234</PRICE>
<TAXRATE>2</TAXRATE>
</ITEM>
<QUANTITY>12</QUANTITY>
<DISCOUNT>0</DISCOUNT>
</LINEITEM_TYP>
<LINEITEM_TYP LineItemNo="2">
<ITEM StockNo="1535">
<PRICE>3456.23</PRICE>
<TAXRATE>2</TAXRATE>
</ITEM>
<QUANTITY>10</QUANTITY>
<DISCOUNT>10</DISCOUNT>
</LINEITEM_TYP>
</LINEITEMS>
<SHIPTOADDR/>
</PurchaseOrder>
PurchaseOrder 2001:
<?xml version="1.0"?>
<PurchaseOrder>
<PONO>2001</PONO>
<CUSTOMER>
<CUSTNO>2</CUSTNO>
<CUSTNAME>John Nike</CUSTNAME>
<ADDRESS>
<STREET>323 College Drive</STREET>
Generating XML from Oracle9i Database Using DBMS_XMLGEN
Generating XML Data from the Database 10-41
<CITY>Edison</CITY>
<STATE>NJ</STATE>
<ZIP>08820</ZIP>
</ADDRESS>
<PHONELIST>
<VARCHAR2>609-555-1212</VARCHAR2>
<VARCHAR2>201-555-1212</VARCHAR2>
</PHONELIST>
</CUSTOMER>
<ORDERDATE>20-APR-97</ORDERDATE>
<SHIPDATE>20-MAY-97 12.00.00.000000 AM</SHIPDATE>
<LINEITEMS>
<LINEITEM_TYP LineItemNo="1">
<ITEM StockNo="1004">
<PRICE>6750</PRICE>
<TAXRATE>2</TAXRATE>
</ITEM>
<QUANTITY>1</QUANTITY>
<DISCOUNT>0</DISCOUNT>
</LINEITEM_TYP>
<LINEITEM_TYP LineItemNo="2">
<ITEM StockNo="1011">
<PRICE>4500.23</PRICE>
<TAXRATE>2</TAXRATE>
</ITEM>
<QUANTITY>2</QUANTITY>
<DISCOUNT>1</DISCOUNT>
</LINEITEM_TYP>
</LINEITEMS>
<SHIPTOADDR>
<STREET>55 Madison Ave</STREET>
<CITY>Madison</CITY>
<STATE>WI</STATE>
<ZIP>53715</ZIP>
</SHIPTOADDR>
</PurchaseOrder>
Example 1021 DBMS_XMLGEN: Generating a New Context Handle from a Passed in
PL/SQL Ref Cursor
CREATE OR REPLACE FUNCTION joe3 RETURN CLOB
IS
ctx1 number := 2;
ctx2 number;
xmldoc CLOB;
Generating XML Using Oracle-Provided SQL Functions
10-42 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
page NUMBER := 0;
xmlpage boolean := true;
refcur SYS_REFCURSOR;
BEGIN
OPEN refcur FOR 'select * from emp where rownum < :1' USING ctx1;
ctx2 := DBMS_XMLGEN.newContext( refcur);
ctx1 := 4;
OPEN refcur FOR 'select * from emp where rownum < :1' USING ctx1;
ctx1 := 5;
OPEN refcur FOR 'select * from emp where rownum < :1' USING ctx1;
dbms_lob.createtemporary(xmldoc, TRUE);
-- xmldoc will have 4 rows
xmldoc := DBMS_XMLGEN.getXML(ctx2,DBMS_XMLGEN.NONE);
DBMS_XMLGEN.closeContext(ctx2);
return xmldoc;
END;
/
Generating XML Using Oracle-Provided SQL Functions
In addition to the SQL standard functions, Oracle9i provides the SYS_XMLGEN and
SYS_XMLAGG functions to aid in generating XML.
SYS_XMLGEN() Function
This Oracle specic SQL function is similar to the XMLElement() except that it
takes a single argument and converts the result to XML. Unlike the other XML
generation functions, SYS_XMLGEN() always returns a well-formed XML
document. Unlike DBMS_XMLGEN which operates at a query level, SYS_XMLGEN()
operates at the row level returning a XML document for each row.
Example 1022 Using SQL_XMLGEN to Create XML
SYS_XMLGEN() creates and queries XML instances in SQL queries, as follows:
SELECT SYS_XMLGEN(employee_id)
FROM employees WHERE last_name LIKE 'Scott%';
The resulting XML document is:
<?xml version=''1.0''?>
<employee_id>60</employee_id>
SYS_XMLGEN() Function
Generating XML Data from the Database 10-43
SYS_XMLGEN Syntax
SYS_XMLGEN() takes in a scalar value, object type, or XMLType instance to be
converted to an XML document. It also takes an optional XMLFormat (the old name
was XMLGenFormatType) object that you can use to specify formatting options for
the resulting XML document. See Figure 1010.
Figure 1010 SYS_XMLGEN Syntax
SYS_XMLGEN() takes an expression that evaluates to a particular row and column
of the database, and returns an instance of type XMLType containing an XML
document. The expr can be a scalar value, a user-dened type, or a XMLType
instance.
I If expr is a scalar value, the function returns an XML element containing the
scalar value.
I If expr is a type, the function maps the user-dened type attributes to XML
elements.
I If expr is a XMLType instance, then the function encloses the document in an
XML element whose default tag name is ROW.
By default the elements of the XML document match the elements of expr. For
example, if expr resolves to a column name, the enclosing XML element will have
the same name as the column. If you want to format the XML document differently,
specify fmt, which is an instance of the XMLFormat object.
In this release, the formatting argument for SYS_XMLGEN() accepts the schema and
element name, and generates the XML document conforming to that registered
schema.
SELECT sys_xmlgen(
dept_t(d.deptno, d.dname, d.loc,
cast(multiset(
SELECT emp_t(e.empno, e.ename, e.job, e.mgr, e.hiredate,e.sal, e.comm)
FROM emp e
WHERE e.deptno = d.deptno) AS emplist_t),
xmlformat.createformat('Department', 'http://www.oracle.com/dept.xsd'))
FROM dept d;
SYS_XMLGEN ( expr
fmt
)
SYS_XMLGEN() Function
10-44 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 1023 SYS_XMLGEN(): Retrieving Employee Email ID From Employees
Table and Generating XML with EMail Element
The following example retrieves the employee email ID from the sample table
oe.employees where the employee_id value is 205, and generates an instance of
a XMLType containing an XML document with an EMAIL element.
SELECT SYS_XMLGEN(email).getStringVal()
FROM employees
WHERE employee_id = 205;
SYS_XMLGEN(EMAIL).GETSTRINGVAL()
------------------------------------------------------------------
<EMAIL>SHIGGENS</EMAIL>
Why is SYS_XMLGEN() so Powerful?
SYS_XMLGEN() is powerful for the following reasons:
I You can create and query XML instances within SQL queries.
I Using the object-relational infrastructure, you can create complex and nested
XML instances from simple relational tables.
SYS_XMLGEN() creates an XML document from either of the following:
I A user-dened type (UDT) instance
I A scalar value passed
I XML
and returns an XMLType instance contained in the document.
SYS_XMLGEN() also optionally inputs a XMLFormat object type through which
you can customize the SQL results. A NULL format object implies that the default
mapping behavior is to be used.
Using XMLFormat Object Type
You can use XMLFormat to specify formatting arguments for SYS_XMLGEN() and
SYS_XMLAGG() functions.
SYS_XMLGEN() returns an instance of type XMLType containing an XML
document. Oracle9i provides the XMLFormat object, which lets you format the
output of the SYS_XMLGEN function.
Table 102 lists the XMLFormat attributes. of the XMLFormat object. The function
that implements this type follows the table.
SYS_XMLGEN() Function
Generating XML Data from the Database 10-45
Example 1024 Creating a Formatting Object with createFormat
You can use the static member function createformat to implement the
XMLFormat object. This function has most of the values defaulted. For example:
STATIC FUNCTION createFormat(
enclTag IN varchar2 := ROWSET,
schemaType IN varchar2 := NO_SCHEMA,
schemaName IN varchar2 := null,
targetNameSpace IN varchar2 := null,
dburlPrefix IN varchar2 := null,
processingIns IN varchar2 := null) RETURN XMLGenFormatType,
MEMBER PROCEDURE genSchema (spec IN varchar2),
MEMBER PROCEDURE setSchemaName(schemaName IN varchar2),
MEMBER PROCEDURE setTargetNameSpace(targetNameSpace IN varchar2),
MEMBER PROCEDURE setEnclosingElementName(enclTag IN varchar2),
MEMBER PROCEDURE setDbUrlPrefix(prefix IN varchar2),
MEMBER PROCEDURE setProcessingIns(pi IN varchar2),
CONSTRUCTOR FUNCTION XMLGenFormatType (
enclTag IN varchar2 := ROWSET,
Table 102 Attributes of the XMLFormat Object
Attribute Datatype Purpose
enclTag VARCHAR2(100) The name of the enclosing tag for the result of the SYS_XMLGEN
function. If the input to the function is a column name, the default
is the column name. Otherwise the default is ROW. When
schemaType is set to USE_GIVEN_SCHEMA, this attribute also
gives the name of the XMLSchema element.
schemaType VARCHAR2(100) The type of schema generation for the output document. Valid
values are NO_SCHEMA and USE_GIVEN_SCHEMA. The default
is NO_SCHEMA.
schemaName VARCHAR2(4000) The name of the target schema Oracle uses if the value of the
schemaType is USE_GIVEN_SCHEMA. If you specify
schemaName, then Oracle uses the enclosing tag as the element
name.
targetNameSpace VARCHAR2(4000) The target namespace if the schema is specied (that is,
schemaType is GEN_SCHEMA_*, or USE_GIVEN_SCHEMA)
dburl VARCHAR2(2000) The URL to the database to use if WITH_SCHEMA is specied. If
this attribute is not specied, the Oracle declares the URL to the
types as a relative URL reference.
processingIns VARCHAR2(4000) User-provided processing instructions, which are appended to the
top of the function output before the element.
SYS_XMLGEN() Function
10-46 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
schemaType IN varchar2 := NO_SCHEMA,
schemaName IN varchar2 := null,
targetNameSpace IN varchar2 := null,
dbUrlPrefix IN varchar2 := null,
processingIns IN varchar2 := null) RETURN SELF AS RESULT
Example 1025 SYS_XMLGEN(): Converting a Scalar Value to an XML Document
Elements Contents
When you input a scalar value to SYS_XMLGEN(), it converts the scalar value to an
element containing the scalar value. For example:
select sys_xmlgen(empno) from scott.emp where rownum < 2;
returns an XML document that contains the empno value as an element, as follows:
<?xml version="1.0"?>
<EMPNO>30</EMPNO>
The enclosing element name, in this case EMPNO, is derived from the column name
passed to the operator. Also, note that the result of the SELECT statement is a row
containing a XMLType.
Example 1026 Generating Default Column Name, ROW
In the last example, you used the column name EMPNO for the document. If the
column name cannot be derived directly, then the default name ROW is used. For
example, in the following case:
SELECT sys_xmlgen(empno).getclobval()
FROM scott.emp
WHERE rownum < 2;
you get the following XML output:
<?xml version="1.0"?>
<ROW>60</ROW>
Note: XMLFormat object is the new name for
XMLGenFormatType. You can use both names.
SYS_XMLGEN() Function
Generating XML Data from the Database 10-47
since the function cannot infer the name of the expression. You can override the
default ROW tag by supplying an XMLFormat (the old name was
"XMLGenFormatType") object to the rst argument of the operator.
Example 1027 Overriding the Default Column Name: Supplying an XMLFormat
Object to the Operators First Argument
For example, in the last case, if you wanted the result to have EMPNO as the tag
name, you can supply a formatting argument to the function, as follows:
SELECT sys_xmlgen(empno *2,
xmlformat.createformat(EMPNO)).getClobVal()
FROM emp;
This results in the following XML:
<?xml version="1.0"?>
<EMPNO>60</EMPNO>
Example 1028 SYS_XMLGEN(): Converting a User-Dened Type to XML
When you input a user-dened type value to SYS_XMLGEN(), the user-dened
type gets mapped to an XML document using a canonical mapping. In the
canonical mapping the user-dened types attributes are mapped to XML elements.
Any type attributes with names starting with @ are mapped to an attribute of the
preceding element. User-dened types can be used to get nesting within the result
XML document.
Using the same example as given in the DBMS_XMLGEN section (Example 1018,
"DBMS_XMLGEN: Generating Complex XML" on page 10-30), you can generate a
hierarchical XML for the employee, department example as follows:
SELECT SYS_XMLGEN(
dept_t(deptno,dname,
CAST(MULTISET(
select empno, ename
from emp e
where e.deptno = d.deptno) AS emplist_t))).getClobVal()
AS deptxml
FROM dept d;
The MULTISET operator treats the result of the subset of employees working in the
department as a list and the CAST around it, casts it to the appropriate collection
type. You then create a department instance around it and call SYS_XMLGEN() to
create the XML for the object instance.
SYS_XMLGEN() Function
10-48 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The result is:
<?xml version="1.0"?>
<ROW DEPTNO="100">
<DNAME>Sports</DNAME>
<EMPLIST>
<EMP_T EMPNO="200">
<ENAME>John</ENAME>
<EMP_T>
<EMP_T>
<ENAME>Jack</ENAME>
</EMP_T>
</EMPLIST>
</ROW>
for each row of the department. The default name ROW is present because the function
cannot deduce the name of the input operand directly.
Example 1029 SYS_XMLGEN(): Converting an XMLType Instance
If you pass an XML document into SYS_XMLGEN(), SYS_XMLGEN() encloses the
document (or fragment) with an element, whose tag name is the default ROW, or the
name passed in through the formatting object. This functionality can be used to turn
document fragments into well formed documents.
For example, the extract() operation on the following document, can return a
fragment. If you extract out the EMPNO elements from the following document:
<DOCUMENT>
<EMPLOYEE>
<ENAME>John</ENAME>
<EMPNO>200</EMPNO>
</EMPLOYEE>
<EMPLOYEE>
<ENAME>Jack</ENAME>
<EMPNO>400</EMPNO>
</EMPLOYEE>
Note: The difference between SYS_XMLGEN() function and
DBMS_XMLGEN package is apparent from the preceding example:
I SYS_XMLGEN works inside SQL queries and operates on the
expressions and columns within the rows
I DBMS_XMLGEN works on the entire result set
SYS_XMLGEN() Function
Generating XML Data from the Database 10-49
<EMPLOYEE>
<ENAME>Joseph</ENAME>
<EMPNO>300</EMPNO>
</EMPLOYEE>
</DOCUMENT>
using the following statement:
SELECT e.podoc.extract(/DOCUMENT/EMPLOYEE/ENAME)
FROM po_xml_tab e;
you get an XML document fragment such as the following:
<ENAME>John</ENAME>
<ENAME>Jack</ENAME>
<ENAME>Joseph</ENAME>
You can make this fragment a valid XML document, by calling SYS_XMLGEN() to
put an enclosing element around the document, as follows:
select SYS_XMLGEN(e.podoc.extract(/DOCUMENT/EMPLOYEE/ENAME)).getclobval()
from po_xml_tab e;
This places an element ROW around the result, as follows:
<?xml version="1.0"?>
<ROW>
<ENAME>John</ENAME>
<ENAME>Jack</ENAME>
<ENAME>Joseph</ENAME>
</ROW>
Example 1030 SYS_XMLGEN(): Using SYS_XMLGEN() with Object Views
-- create Purchase Order object type
CREATE OR REPLACE TYPE PO_typ AUTHID CURRENT_USER AS OBJECT (
PONO NUMBER,
Customer Customer_typ,
OrderDate DATE,
Note: If the input was a column, then the column name would
have been used as default. You can override the enclosing element
name using the formatting object that can be passed in as an
additional argument to the function. See "Using XMLFormat Object
Type" on page 10-44.
SYS_XMLGEN() Function
10-50 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
ShipDate TIMESTAMP,
LineItems_ntab LineItems_ntabtyp,
ShipToAddr Address_typ
)
/
--Purchase order view
CREATE OR REPLACE VIEW PO OF PO_typ
WITH OBJECT IDENTIFIER (PONO)
AS SELECT P.PONo,
Customer_typ(P.Custno,C.CustName,C.Address,C.PhoneList),
P.OrderDate,
P.ShipDate,
CAST( MULTISET(
SELECT LineItem_typ( L.LineItemNo,
StockItem_typ(L.StockNo,S.Price,S.TaxRate),
L.Quantity, L.Discount)
FROM LineItems_tab L, Stock_tab S
WHERE L.PONo = P.PONo and S.StockNo=L.StockNo )
AS LineItems_ntabtyp),
Address_typ(P.ToStreet,P.ToCity, P.ToState, P.ToZip)
FROM PO_tab P, Customer C
WHERE P.CustNo=C.custNo;
-------------------------------------------------------
-- Use SYS_XMLGEN() to generate PO in XML format
-------------------------------------------------------
set long 20000
set pages 100
SELECT SYS_XMLGEN(value(p),
sys.xmlformat.createFormat('PurchaseOrder')).getClobVal() PO
FROM po p
WHERE p.pono=1001;
This returns the Purchase Order in XML format:
<?xml version="1.0"?>
<PurchaseOrder>
<PONO>1001</PONO>
<CUSTOMER>
<CUSTNO>1</CUSTNO>
<CUSTNAME>Jean Nance</CUSTNAME>
<ADDRESS>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
SYS_XMLAGG() Function
Generating XML Data from the Database 10-51
<STATE>CA</STATE>
<ZIP>95054</ZIP>
</ADDRESS>
<PHONELIST>
<VARCHAR2>415-555-1212</VARCHAR2>
</PHONELIST>
</CUSTOMER>
<ORDERDATE>10-APR-97</ORDERDATE>
<SHIPDATE>10-MAY-97 12.00.00.000000 AM</SHIPDATE>
<LINEITEMS_NTAB>
<LINEITEM_TYP LineItemNo="1">
<ITEM StockNo="1534">
<PRICE>2234</PRICE>
<TAXRATE>2</TAXRATE>
</ITEM>
<QUANTITY>12</QUANTITY>
<DISCOUNT>0</DISCOUNT>
</LINEITEM_TYP>
<LINEITEM_TYP LineItemNo="2">
<ITEM StockNo="1535">
<PRICE>3456.23</PRICE>
<TAXRATE>2</TAXRATE>
</ITEM>
<QUANTITY>10</QUANTITY>
<DISCOUNT>10</DISCOUNT>
</LINEITEM_TYP>
</LINEITEMS_NTAB>
<SHIPTOADDR/>
</PurchaseOrder>
SYS_XMLAGG() Function
SYS_XMLAGG() function aggregates all XML documents or fragments represented
by expr and produces a single XML document. It adds a new enclosing element
with a default name, ROWSET. To format the XML document differently then specify
fmt, the instance of XMLFORMAT object
Figure 1011 SYS_XMLAGG() Syntax
SYS_XMLAGG ( expr
fmt
)
Generating XML Using XSQL Pages Publishing Framework
10-52 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Generating XML Using XSQL Pages Publishing Framework
Oracle9i introduced XMLType for use with storing and querying XML-based
database content. You can use these database XML features to produce XML for
inclusion in your XSQL pages by using the <xsql:include-xml> action element.
The SELECT statement that appears inside the <xsql:include-xml> element
should return a single row containing a single column. The column can either be a
CLOB or a VARCHAR2 value containing a well-formed XML document. The XML
document will be parsed and included in your XSQL page.
Example 1031 Using XSQL Servlets <xsql:include-xml> and Nested XMLAgg()
Functions to Aggregate the Results Into One XML Document
The following example uses nested xmlagg() functions to aggregate the results of
a dynamically-constructed XML document containing departments and nested
employees into a single XML result document, wrapped in a
<DepartmentList> element:
<xsql:include-xml connection="orcl92" xmlns:xsql="urn:oracle-xsql">
select XmlElement("DepartmentList",
XmlAgg(
XmlElement("Department",
XmlAttributes(deptno as "Id"),
XmlForest(dname as "Name"),
(select XmlElement("Employees",
XmlAgg(
XmlElement("Employee",
XmlAttributes(empno as "Id"),
XmlForest(ename as "Name",
sal as "Salary",
job as "Job")
)
)
)
from emp e
where e.deptno = d.deptno
)
)
)
).getClobVal()
from dept d
See Also: Oracle9i SQL Reference
Generating XML Using XSQL Pages Publishing Framework
Generating XML Data from the Database 10-53
order by dname
</xsql:include-xml>
Example 1032 Using XSQL Servlets <xsql:include-xml>, XMLElement(), and
XMLAgg() to Generate XML from Oracle9i Database
Since it is more efcient for the database to aggregate XML fragments into a single
result document, the <xsql:include-xml> element encourages this approach by
only retrieving the rst row from the query you provide.
For example, if you have a number of <Movie> XML documents stored in a table of
XmlType called MOVIES, each document might look something like this:
<Movie Title="The Talented Mr.Ripley" RunningTime="139" Rating="R">
<Director>
<First>Anthony</First>
<Last>Minghella</Last>
</Director>
<Cast>
<Actor Role="Tom Ripley">
<First>Matt</First>
<Last>Damon</Last>
</Actor>
<Actress Role="Marge Sherwood">
<First>Gwenyth</First>
<Last>Paltrow</Last>
</Actress>
<Actor Role="Dickie Greenleaf">
<First>Jude</First>
<Last>Law</Last>
<Award From="BAFTA" Category="Best Supporting Actor"/>
</Actor>
</Cast>
</Movie>
You can use the built-in Oracle9i XPath query features to extract an aggregate list of
all cast members who have received Oscar awards from any movie in the database
using a query like this:
SELECT xmlelement("AwardedActors",
xmlagg(extract(value(m),
'/Movie/Cast/*[Award[@From="Oscar"]]')))
FROM movies m;
-- To include this query result of XMLType into your XSQL page,
Generating XML Using XML SQL Utility (XSU)
10-54 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
-- simply paste the query inside an <xsql:include-xml> element, and add
-- a getClobVal() method call to the query expression so that the result will
-- be returned as a CLOB instead of as an XMLType to the client:
<xsql:include-xml connection="orcl92" xmlns:xsql="urn:oracle-xsql">
select xmlelement("AwardedActors",
xmlagg(extract(value(m),
'/Movie/Cast/*[Award[@From="Oscar"]]'))).getClobVal()
from movies m
</xsql:include-xml>
Failing to do this results in an attempt by the XSQL page processor to parse a CLOB
that looks like:
<Actor>...</Actor>
<Actress>...</Actress>
Which is not well-formed XML because it does not have a single document element
as required by the XML 1.0 specication. The combination of xmlelement() and
xmlagg() work together to produce a well-formed result like this:
<AwardedActors>
<Actor>...</Actor>
<Actress>...</Actress>
</AwardedActors>
This well-formed XML is then parsed and included in your XSQL page.
Generating XML Using XML SQL Utility (XSU)
The Oracle XML SQL Utility (XSU) can still be used with Oracle9i to generate XML.
This might be useful if you want to generate XML on the middle-tier or the client.
XSU now additionally supports generating XML on tables with XMLType columns.
Note: Again we use the combination of XMLElement() and
XMLAgg() to have the database aggregate all of the XML fragments
identied by the query into a single, well-formed XML document.
See Also: Oracle9i XML Developers Kits Guide - XDK, the chapter
in XDK for Java on XSQL Page Publishing Framework.
Generating XML Using XML SQL Utility (XSU)
Generating XML Data from the Database 10-55
Example 1033 Generating XML Using XSU for Java getXML
For example, if you have table, parts:
CREATE TABLE parts ( PartNo number, PartName varchar2(20), PartDesc xmltype );
You can generate XML on this table using Java with the call:
java OracleXML getXML -user "scott/tiger" -rowTag "Part" "select * from parts"
This produces the result:
<Parts>
<Part>
<PartNo>1735</PartNo>
<PartName>Gizmo</PartName>
<PartDesc>
<Description>
<Title>Description of the Gizmo</Title>
<Author>John Smith</Author>
<Body>
The <b>Gizmo</b> is <i>grand</i>.
</Body>
</Description>
</PartDesc>
</Part>
...
</Parts>
See Also : Oracle9i XML Developers Kits Guide - XDK for more
information on XSU
Generating XML Using XML SQL Utility (XSU)
10-56 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XMLType Views 11-1
11
XMLType Views
This chapter describes how to create and use XMLType views. It contains the
following sections:
I What Are XMLType Views?
I Creating Non-Schema-Based XMLType Views
I Creating XML Schema-Based XMLType Views
I Creating XMLType Views From XMLType Tables
I Referencing XMLType View Objects Using REF()
I DML (Data Manipulation Language) on XMLType Views
I Query Rewrite on XMLType Views
I Ad-Hoc Generation of XML Schema-Based XML
I Validating User-Specied Information
What Are XMLType Views?
11-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
What Are XMLType Views?
XMLType views wrap existing relational and object-relational data in XML formats.
The major advantages of using XMLType views are:
I You can exploit the new Oracle XML DB XML features that use XMLSchema
functionality without having to migrate your base legacy data.
I With XMLType views, you can experiment with various other forms of storage,
besides the object-relational or CLOB storage alternatives available to XMLType
tables.
XMLType views are similar to object views. Each row of an XMLType view
corresponds to an XMLType instance. The object identier for uniquely identifying
each row in the view can be created using an expression such as extract() on the
XMLType value.
Similar to XMLType tables, XMLType views can conform to an XML schema. This
provides stronger typing and enables optimization of queries over these views.
To use XMLType views with XML schemas, you must rst register your XML
schema with annotations that represent the bi-directional mapping from XML to
SQL object types. An XMLType viewconforming to this registered XML schema can
then be created by providing an underlying query that constructs instances of the
appropriate SQL object type.
This chapter describes the two main ways you can create XMLType views:
I Based on XML generation functions
I Based on object types
See Also:
I Chapter 5, "Structured Mapping of XMLType"
I Chapter 26, "Oracle XML DB Basic Demo", the section on "7.0
XML DB Demo: Using Views to Access XML from Relational
Tools"
I Appendix B, "XML Schema Primer"
Creating Non-Schema-Based XMLType Views
XMLType Views 11-3
Creating Non-Schema-Based XMLType Views
You can create a view of XMLType or a view with one or more XMLType columns,
by using the SQL XML generation functions, particularly those that comply with
the emerging SQLX standards.
Example 111 XMLType View: Creating XMLType View Using XMLElement() Function
The following statement creates an XMLType view using XMLElement()
generation function:
DROP TABLE employees;
CREATE TABLE employees
(empno number(4), fname varchar2(20), lname varchar2(20), hire date, salary
number(6));
INSERT INTO employees VALUES
(2100, John, Smith, Date2000-05-24, 30000);
INSERT INTO employees VALUES
(2200, Mary, Martin, Date1996-02-01, 30000);
CREATE OR REPLACE VIEW Emp_view OF XMLTYPE WITH OBJECT ID
(EXTRACT(sys_nc_rowinfo$,/Emp/@empno).getnumberval())
AS SELECT XMLELEMENT("Emp", XMLAttributes(empno),
XMLForest(e.fname || || e.lname AS "name",
e.hire AS "hiredate")) AS "result"
FROM employees e
WHERE salary > 20000;
A query against the XMLType view returns the following employee data in XML
format:
SELECT * FROM Emp_view;
<Emp empno="2100">
<name>John Smith</name>
<hiredate>2000-05-24</hiredate>
</Emp>
<Emp empno="2200">
<name>Mary Martin</name>
<hiredate>1996-02-01</hiredate>
</Emp>
See Also: Chapter 10, "Generating XML Data fromthe Database",
for details on SQLX generation functions.
Creating XML Schema-Based XMLType Views
11-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
empno attribute in the document should become the unique identier for each row.
SYS_NC_ROWINFO$ is a virtual column that references the rowXMLType instance.
You can perform DML operations on these XMLType views, but, in general, you
must write instead-of triggers to handle the DML operation.
XMLType Views can also be created using SYS_XMLGEN. An equivalent query that
produces the same query results using SYS_XMLGEN is as follows:
CREATE TYPE Emp_t AS OBJECT ("@empno" number(4), fname varchar2(2000),
lname varchar2(2000), hiredate date);
CREATE VIEW employee_view OF XMLTYPE WITH OBJECT ID
(EXTRACT(sys_nc_rowinfo$,/Emp/@empno).getnumberval())
AS SELECT SYS_XMLGEN(emp_t(empno, fname, lname, hire),
XMLFORMAT(EMP))
FROM employees e
WHERE salary > 20000;
Existing data in relational or object-relational tables or views can be exposed as
XML using this mechanism. In addition, queries involving simple XPath traversal
over SYS_XMLGEN views are candidates for query rewrite to directly access the
object attributes.
Creating XML Schema-Based XMLType Views
XML schema-based XMLType views are XMLType views whose resultant XML
value is constrained to be a particular element in a registered XML schema. There
are two main ways to create XML schema-based XMLType views:
I Using SQL/XML functions, such as XMLAgg, XMLElement, XMLForest, and
so on. Here you create the XMLType view using simple XML generation
functions, without the need for creating any object types. This mechanism of
creating XMLType views using SQL/XML functions is more simple as you do
not have to create any object types or object views. The use of object types with
Note: In prior releases, the object identier clause only supported
attributes of the object type of the view to be specied. In this
release, this has been enhanced to support any expression returning
a scalar value.
Creating XML Schema-Based XMLType Views
XMLType Views 11-5
XML schemas however, would also give you the advantage of using Query
Rewrite functionality.
I Using object types and or object views. Here you create the XMLType view
either using object types or from object views. This mechanism for creating
XMLType views is more convenient when you already have an object-relational
schema and want to map it directly to XML. Also, since the view is based on
XML schema, it derives several performance (memory and access)
optimizations.
Creating XML Schema-Based XMLType Views Using SQL/XML Generation Functions
SQL/XML generation functions can be used to create XML schema-based XMLType
views similar to the non-schema based case explained in the previous section. To
create XML schema-based XMLType views, perform the following steps:
1. Create and register the XML schema document that contains the necessary XML
structures.
2. Create an XMLType view conforming to that XML schema by using SQL/XML
functions.
See Also: "Creating XML Schema-Based XMLType Views Using
SQL/XML Generation Functions" on page 11-5.
See Also: "Creating XMLType Views Using Object Types and
Views" on page 11-11.
Note: In this release, XPath predicates over these SQL/XML
views are not rewritten. Consequently, queries expressed over such
views using predicates such as extract, existsNode,... are
evaluated functionally over all the rows of the view. If queriability
of the view is important, consider using the object-relational
approach instead.
Creating XML Schema-Based XMLType Views
11-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 112 Creating XML Schema-Based XMLType Views using SQL/XML
Functions
Step 1. Register XML Schema, emp_simple.xsd
Assume that you have an XML schema emp_simple.xsd that contains XML
structures dening an employee. First register the XML schema and identify it
using a URL:
BEGIN
dbms_xmlschema.deleteSchema(http://www.oracle.com/emp_simple.xsd, 4);
END;
/
BEGIN
dbms_xmlschema.registerSchema(http://www.oracle.com/emp_simple.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/emp_simple.xsd" version="1.0"
xmlns:xdb="http://xmlns.oracle.com/xdb"
elementFormDefault="qualified">
<element name = "Employee">
<complexType>
<sequence>
<element name = "EmployeeId" type = "positiveInteger"/>
<element name = "Name" type = "string"/>
<element name = "Job" type = "string"/>
<element name = "Manager" type = "positiveInteger"/>
<element name = "HireDate" type = "date"/>
<element name = "Salary" type = "positiveInteger"/>
<element name = "Commission" type = "positiveInteger"/>
<element name = "Dept">
<complexType>
<sequence>
<element name = "DeptNo" type = "positiveInteger" />
<element name = "DeptName" type = "string"/>
<element name = "Location" type = "string"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>, TRUE, TRUE, FALSE);
END;
/
Creating XML Schema-Based XMLType Views
XMLType Views 11-7
The preceding statement registers the XML schema with the target location:
"http://www.oracle.com/emp_simple.xsd"
Step 2. Create XMLType View Using SQL/XML Functions
You can now create an XML schema-based XMLType view using SQL/XML
functions. You can also use XMLTransform() or other SQL function that generate
XML.The resultant XML must conform to the XML schema specied for the view.
When using SQL/XML functions to generate XML schema-based content, you must
specify the appropriate namespace information for all the elements and also
indicate the location of the schema using the xsi:schemaLocation attribute. All
these can be specied using the XMLAttributes clause.
CREATE OR REPLACE VIEW emp_simple_xml OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/emp_simple.xsd" ELEMENT "Employee"
WITH OBJECT ID (extract(sys_nc_rowinfo$,
/Employee/EmployeeId/text()).getnumberval()) AS
SELECT XMLElement("Employee",
XMLAttributes( http://www.oracle.com/emp_simple.xsd AS "xmlns" ,
http://www.w3.org/2001/XMLSchema-instance AS "xmlns:xsi",
http://www.oracle.com/emp_simple.xsd
http://www.oracle.com/emp_simple.xsd AS "xsi:schemaLocation"),
XMLForest(e.empno AS "EmployeeId",
e.ename AS "Name",
e.job AS "Job",
e.mgr AS "Manager",
to_char(e.hiredate,SYYYY-MM-DD) AS "HireDate",
e.sal AS "Salary",
e.comm AS "Commission",
XMLForest(d.deptno AS "DeptNo",
d.dname AS "DeptName",
d.loc AS "Location") AS "Dept"))
FROM emp e, dept d
WHERE e.deptno = d.deptno;
In the preceding example, the XMLElement() function creates the Employee XML
element and the inner XMLForest() creates the kids of the employee element. The
XMLAttributes clause inside the XMLElement() constructs the required XML
namespace and schema location attributes so that the XML generated conforms
to the views XML schema.The innermost XMLForest() function creates the
department XML element that is nested inside the Employee element.
Creating XML Schema-Based XMLType Views
11-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The XML generation function simply generates a non-XML schema-based XML
instance. However, in the case of XMLType views, as long as the names of the
elements and attributes match those in the XML schema, Oracle converts this XML
implicitly into a well-formed and valid XML schema-based document. Any errors
in the generated XML will be caught when further operations, such as validate or
extract,... are performed on the XML instance.
The expression:
to_char(e.hiredate,SYYYY-MM-DD) AS "HireDate"
is needed to convert dates in SQL date format to the XML Schema format, since the
default Globalization Support date format for converting date to string may be
different.
You can now query the view and get the XML result from the employee and
department relational tables:
SQL> select value(p) as result from emp_simple_xml p where rownum < 2;
RESULT
--------------------------------------------------------------------------------
<Employee xmlns="http://www.oracle.com/emp_simple.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/emp_simple.xsd
http://www.oracle.com/emp_simple.xsd">
<EmployeeId>7782</EmployeeId>
<Name>CLARK</Name>
<Job>MANAGER</Job>
<Manager>7839</Manager>
<HireDate>1981-06-09</HireDate>
<Salary>2450</Salary>
<Dept>
<DeptNo>10</DeptNo>
<DeptName>ACCOUNTING</DeptName>
<Location>NEW YORK</Location>
</Dept>
</Employee>
Using Namespaces with SQL/XML Functions
If you have complicated XML schemas involving multiple namespaces, you need to
use the partially escaped mapping provided in the SQL functions and create
elements with appropriate namespaces and prexes.
Creating XML Schema-Based XMLType Views
XMLType Views 11-9
Example 113 Using Namespace Prexes in XMLType Views
For example the SQL query:
SELECT XMLElement("ipo:Employee",
XMLAttributes(http://www.oracle.com/emp_simple.xsd AS "xmlns:ipo",
http://www.oracle.com/emp_simple.xsd
http://www.oracle.com/emp_simple.xsd AS "xmlns:xsi"),
XMLForest(e.empno AS "ipo:EmployeeId",
e.ename AS "ipo:Name",
e.job AS "ipo:Job" ,
e.mgr AS "ipo:Manager",
to_char(e.hiredate,SYYYY-MM-DD) AS "ipo:HireDate",
e.sal AS "ipo:Salary",
e.comm AS "ipo:Commission",
XMLForest(d.deptno AS "ipo:DeptNo",
d.dname AS "ipo:DeptName",
d.loc AS "ipo:Location") AS "ipo:Dept"))
FROM emp e, dept d
WHERE e.deptno = d.deptno;
creates the XML instances with the correct namespace, prexes, and target schema
location, and can be used as the query in the emp_simple_xml view denition.
The instance created by this query looks like the following:
<ipo:Employee xmlns:ipo="http://www.oracle.com/emp_simple.xsd"
xmlns:xsi="http://www.oracle.com/emp_simple.xsd
http://www.oracle.com/emp_simple.xsd">
<ipo:EmployeeId>7782</ipo:EmployeeId>
<ipo:Name>CLARK</ipo:Name>
<ipo:Job>MANAGER</ipo:Job>
<ipo:Manager>7839</ipo:Manager>
<ipo:HireDate>1981-06-09</ipo:HireDate>
<ipo:Salary>2450</ipo:Salary>
<ipo:Dept>
<ipo:DeptNo>10</ipo:DeptNo>
<ipo:DeptName>ACCOUNTING</ipo:DeptName>
<ipo:Location>NEW YORK</ipo:Location>
</ipo:Dept>
</ipo:Employee>
If the XML schema had no target namespace you can use the
xsi:noNamespaceSchemaLocation attribute to denote that. For example,
consider the following XML schema that is registered at location:
emp-noname.xsd:
Creating XML Schema-Based XMLType Views
11-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
BEGIN
dbms_xmlschema.deleteSchema(emp-noname.xsd, 4);
END;
/
BEGIN
dbms_xmlschema.registerSchema(emp-noname.xsd,
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<xs:element name = "Employee" xdb:defaultTable="EMP37_TAB">
<xs:complexType>
<xs:sequence>
<xs:element name = "EmployeeId" type = "xs:positiveInteger"/>
<xs:element name = "FirstName" type = "xs:string"/>
<xs:element name = "LastName" type = "xs:string"/>
<xs:element name = "Salary" type = "xs:positiveInteger"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>);
END;
/
The following CREATE OR REPLACE VIEW statement creates a viewthat conforms
to this XML schema:
CREATE OR REPLACE VIEW emp_xml OF XMLTYPE
XMLSCHEMA "emp-noname.xsd" ELEMENT "Employee"
WITH OBJECT ID (extract(sys_nc_rowinfo$,
/Employee/EmployeeId/text()).getnumberval()) AS
SELECT XMLElement("Employee",
XMLAttributes(http://www.w3.org/2001/XMLSchema-instance AS "xmlns:xsi",
emp-noname.xsd AS "xsi:noNamespaceSchemaLocation"),
XMLForest(e.empno AS "EmployeeId",
e.ename AS "Name",
e.job AS "Job" ,
e.mgr AS "Manager",
to_char(e.hiredate,SYYYY-MM-DD) AS "HireDate",
e.sal AS "Salary",
e.comm AS "Commission",
XMLForest(d.deptno AS "DeptNo",
d.dname AS "DeptName",
d.loc AS "Location") AS "Dept"))
FROM emp e, dept d
WHERE e.deptno = d.deptno;
Creating XML Schema-Based XMLType Views
XMLType Views 11-11
The XMLAttributes clause creates an XML element that contains the
noNamespace schema location attribute.
Creating XMLType Views Using Object Types and Views
To wrap relational data with strongly-typed XML, using the object view approach,
perform these steps:
1. Create object types
2. Create or generate and then register an XML schema document that contains
the XML structures, along with its mapping to the SQL object types and
attributes. See Chapter 5, "Structured Mapping of XMLType".
3. Create the XMLType view and specify the XML schema URL and the root
element name. The underlying view query rst constructs the object instances
and then converts them to XML. This step can also be done in two steps:
1. Create an object view
2. Create an XMLType view over the object view
Consider the following examples based on the canonical employee -department
relational tables and XML views of this data:
I Creating Schema-Based XMLType Views over object views
I XMLType View: View 2, Wrapping Relational Department Data with Nested
Employee Data as XML
Example 114 Creating Schema-Based XMLType Views over object views
For the rst example view, to wrap the relational employee data with nested
department information as XML, follow these steps:
Step 1. Create Object Types
CREATE OR REPLACE TYPE dept_t AS OBJECT
(
DEPTNO NUMBER(2),
DNAME VARCHAR2(14),
LOC VARCHAR2(13)
);
/
CREATE OR REPLACE TYPE emp_t AS OBJECT
(
Creating XML Schema-Based XMLType Views
11-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
EMPNO NUMBER(4),
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPT DEPT_T
);
/
Step 2. Create or Generate XMLSchema, emp.xsd
You can create the XML schema by hand or you can use the DBMS_XMLSchema
package to generate the XML schema automatically from the existing object types.
For example:
SELECT DBMS_XMLSchema.generateSchema(SCOTT,EMP_T) AS result FROM DUAL;
generates the XML schema for the employee type. You can supply various
arguments to this function to add namespaces, and so on. You can further edit the
XML schema to change the various default mappings that were generated.
generateSchemas() function in the package generates a list of XML schemas one
for each different SQL database schema referenced by the object type and its
attributes.
Step 3. Register XML Schema, emp.xsd
XML schema, emp.xsd also species how the XML elements and attributes are
mapped to their corresponding attributes in the object types, as follows:
BEGIN
dbms_xmlschema.deleteSchema(http://www.oracle.com/emp.xsd, 4);
END;
/
BEGIN
dbms_xmlschema.registerSchema(http://www.oracle.com/emp.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/emp.xsd" version="1.0"
xmlns:xdb="http://xmlns.oracle.com/xdb"
elementFormDefault="qualified">
<element name = "Employee" xdb:SQLType="EMP_T" xdb:SQLSchema="SCOTT">
<complexType>
<sequence>
<element name = "EmployeeId" type = "positiveInteger" xdb:SQLName="EMPNO"
Creating XML Schema-Based XMLType Views
XMLType Views 11-13
xdb:SQLType="NUMBER"/>
<element name = "Name" type = "string" xdb:SQLName="ENAME"
xdb:SQLType="VARCHAR2"/>
<element name = "Job" type = "string" xdb:SQLName="JOB"
xdb:SQLType="VARCHAR2"/>
<element name = "Manager" type = "positiveInteger" xdb:SQLName="MGR"
xdb:SQLType="NUMBER"/>
<element name = "HireDate" type = "date" xdb:SQLName="HIREDATE"
xdb:SQLType="DATE"/>
<element name = "Salary" type = "positiveInteger" xdb:SQLName="SAL"
xdb:SQLType="NUMBER"/>
<element name = "Commission" type = "positiveInteger" xdb:SQLName="COMM"
xdb:SQLType="NUMBER"/>
<element name = "Dept" xdb:SQLName="DEPT" xdb:SQLType="DEPT_T"
xdb:SQLSchema="SCOTT">
<complexType>
<sequence>
<element name = "DeptNo" type = "positiveInteger"
xdb:SQLName="DEPTNO"
xdb:SQLType="NUMBER"/>
<element name = "DeptName" type = "string" xdb:SQLName="DNAME"
xdb:SQLType="VARCHAR2"/>
<element name = "Location" type = "string" xdb:SQLName="LOC"
xdb:SQLType="VARCHAR2"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>, TRUE, FALSE, FALSE);
END;
/
The preceding statement registers the XML schema with the target location:
"http://www.oracle.com/emp.xsd"
Step 4a. Create XMLType View Using the One-Step Process
With the one-step process you must create an XMLType viewon the relational tables
as follows:
Creating XML Schema-Based XMLType Views
11-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
CREATE OR REPLACE VIEW emp_xml OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/emp.xsd" ELEMENT "Employee"
WITH OBJECT ID (ExtractValue(sys_nc_rowinfo$, /Employee/EmployeeId)) AS
SELECT emp_t(e.empno, e.ename, e.job, e.mgr, e.hiredate, e.sal, e.comm,
dept_t(d.deptno, d.dname, d.loc))
FROM emp e, dept d
WHERE e.deptno = d.deptno;
This example uses the extractValue() SQL function here in the OBJECT ID clause,
since extractValue() can automatically gure out the appropriate SQL datatype
mapping (in this case a SQL Number) using the XML schema information.
Step 4b. Create XMLType View Using the Two-Step Process by First Creating an
Object View
In the two step process, you rst create an object-relational view, then create an
XMLType view on the object-relational view, as follows:
CREATE OR REPLACE VIEW emp_v OF emp_t WITH OBJECT ID (empno) AS
SELECT emp_t(e.empno, e.ename, e.job, e.mgr, e.hiredate, e.sal, e.comm,
dept_t(d.deptno, d.dname, d.loc))
FROM emp e, dept d
WHERE e.deptno = d.deptno;
-- Create the employee XMLType view over the emp_v object view
CREATE OR REPLACE VIEW emp_xml OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/emp.xsd" ELEMENT "Employee"
WITH OBJECT ID DEFAULT
AS SELECT VALUE(p) FROM emp_v p;
Example 115 XMLType View: View 2, Wrapping Relational Department Data with
Nested Employee Data as XML
For the second example view, to wrap the relational department data with nested
employee information as XML, follow these steps:
Step 1. Create Object Types
DROP TYPE emp_t FORCE;
DROP TYPE dept_t FORCE;
CREATE OR REPLACE TYPE emp_t AS OBJECT
(
EMPNO NUMBER(4),
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
Creating XML Schema-Based XMLType Views
XMLType Views 11-15
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2)
);
/
CREATE OR REPLACE TYPE emplist_t AS TABLE OF emp_t;
/
CREATE OR REPLACE TYPE dept_t AS OBJECT
(
DEPTNO NUMBER(2),
DNAME VARCHAR2(14),
LOC VARCHAR2(13),
EMPS EMPLIST_T
);
/
Step 2. Register XML Schema, dept.xsd
You can either use a pre-existing XML schema or you can generate an XML schema
from the object type using the DBMS_XMLSchema.generateSchema(s) functions:
BEGIN
dbms_xmlschema.deleteSchema(http://www.oracle.com/dept.xsd, 4);
END;
/
BEGIN
dbms_xmlschema.registerSchema(http://www.oracle.com/dept.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/dept.xsd" version="1.0"
xmlns:xdb="http://xmlns.oracle.com/xdb"
elementFormDefault="qualified">
<element name = "Department" xdb:SQLType="DEPT_T" xdb:SQLSchema="SCOTT">
<complexType>
<sequence>
<element name = "DeptNo" type = "positiveInteger" xdb:SQLName="DEPTNO"
xdb:SQLType="NUMBER"/>
<element name = "DeptName" type = "string" xdb:SQLName="DNAME"
xdb:SQLType="VARCHAR2"/>
<element name = "Location" type = "string" xdb:SQLName="LOC"
xdb:SQLType="VARCHAR2"/>
<element name = "Employee" maxOccurs = "unbounded" xdb:SQLName = "EMPS"
xdb:SQLType="EMPLIST_T"
xdb:SQLSchema="SCOTT">
<complexType>
Creating XML Schema-Based XMLType Views
11-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<sequence>
<element name = "EmployeeId" type = "positiveInteger"
xdb:SQLName="EMPNO"
xdb:SQLType="NUMBER"/>
<element name = "Name" type = "string" xdb:SQLName="ENAME"
xdb:SQLType="VARCHAR2"/>
<element name = "Job" type = "string" xdb:SQLName="JOB"
xdb:SQLType="VARCHAR2"/>
<element name = "Manager" type = "positiveInteger"
xdb:SQLName="MGR"
xdb:SQLType="NUMBER"/>
<element name = "HireDate" type = "date" xdb:SQLName="HIREDATE"
xdb:SQLType="DATE"/>
<element name = "Salary" type = "positiveInteger" xdb:SQLName="SAL"
xdb:SQLType="NUMBER"/>
<element name = "Commission" type = "positiveInteger"
xdb:SQLName="COMM"
xdb:SQLType="NUMBER"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>, TRUE, FALSE, FALSE);
END;
/
Step 3a. Create XMLType Views on Relational Tables
Create the dept_xml XMLType view from the department object type as follows:
CREATE OR REPLACE VIEW dept_xml OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/dept.xsd" ELEMENT "Department"
WITH OBJECT ID (EXTRACTVALUE(sys_nc_rowinfo$, /Department/DeptNo)) AS
SELECT dept_t(d.deptno, d.dname, d.loc,
cast(multiset(
SELECT emp_t(e.empno, e.ename, e.job, e.mgr, e.hiredate,
e.sal,e.comm) FROM emp e
WHERE e.deptno = d.deptno)
AS emplist_t))
FROM dept d;
Creating XMLType Views From XMLType Tables
XMLType Views 11-17
Step 3b. Create XMLType Views on Relational Tables using SQL functions
You can also create the dept_xml XMLType viewfromthe relational tables without
using the object type denitions.
CREATE OR REPLACE VIEW dept_xml OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/dept.xsd" ELEMENT "Department"
WITH OBJECT ID (EXTRACT(sys_nc_rowinfo$,
/Department/DeptNo).getNumberVal()) AS
SELECT XMLElement("Department",
XMLAttributes( http://www.oracle.com/emp.xsd AS "xmlns" ,
http://www.w3.org/2001/XMLSchema-instance AS "xmlns:xsi",
http://www.oracle.com/dept.xsd
http://www.oracle.com/dept.xsd AS "xsi:schemaLocation"),
XMLForest(d.deptno "DeptNo",
d.dname "DeptName",
d.loc "Location"),
(SELECT XMLAGG(XMLElement("Employee",
XMLForest(e.empno "EmployeeId",
e.ename "Name",
e.job "Job",
e.mgr "Manager",
to_char(e.hiredate,SYYYY-MM-DD)
"Hiredate"),
e.sal "Salary",
e.comm "Commission"))
FROM emp e
WHERE e.deptno = d.deptno))
FROM dept d;
Creating XMLType Views From XMLType Tables
An XMLType view can be created on an XMLType table, perhaps to transform the
XML or to restrict the rows returned by using some predicates.
Note: The XML schema and element information must be
specied at the viewlevel because the SELECT list could arbitrarily
construct XML of a different XML schema from the underlying
table.
Referencing XMLType View Objects Using REF()
11-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 116 Creating an XMLType View by Restricting rows From an XMLType Table
Here is an example of creating a XMLType view by restricting the rows returned
from an underlying XMLType table. We use the dept.xsd schema described in the
previous section to create the underlying table.
DROP TABLE dept_xml_tab;
CREATE TABLE dept_xml_tab OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/dept.xsd" ELEMENT "Department"
nested table xmldata."EMPS" store as dept_xml_tab_tab1;
CREATE OR REPLACE VIEW dallas_dept_view OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/dept.xsd" ELEMENT "Department"
AS SELECT VALUE(p) FROM dept_xml_tab p
WHERE Extractvalue(value(p), /Department/Location) = DALLAS;
Here, the dallas_dept_view restricts the XMLType table rows to those
departments whose location is Dallas.
Example 117 Creating an XMLType View by Transforming an XMLType Table
You can create an XMLType view by transforming the XML data using a stylesheet.
For example, consider the creation of XMLType table po_tab. Refer to Example 61,
"Transforming an XMLType Instance Using XMLTransform() and DBUriType to Get
the XSL Stylesheet" on page 6-6 for an xmltransform() example:
DROP TABLE po_tab;
CREATE TABLE po_tab OF xmltype xmlschema "ipo.xsd" element
"PurchaseOrder";
You can then create a view of the table as follows:
CREATE OR REPLACE VIEW HR_PO_tab OF xmltype xmlschema "hrpo.xsd" element
"PurchaseOrder"
WITH OBJECT ID DEFAULT
AS SELECT
xmltransform(value(p),xdburitype(/home/SCOTT/xsl/po2.xsl).getxml())
FROM po_tab p;
Referencing XMLType View Objects Using REF()
You can reference an XMLType view object using the REF() syntax:
SELECT REF(p) FROM dept_xml p;
DML (Data Manipulation Language) on XMLType Views
XMLType Views 11-19
XMLType view reference REF() is based on one of the following object IDs:
I On a system-generated OID for views on XMLType tables or object views
I On a primary key based OID -- for views with OBJECT ID expressions
These REFs can be used to fetch OCIXMLType instances in the OCI Object cache or
can be used inside SQL queries. These REFs behave in the same way as REFs to
object views.
DML (Data Manipulation Language) on XMLType Views
An XMLType view may not be inherently updatable. This means that you have to
write INSTEAD-OF -TRIGGERS to handle all data manipulation (DML). You can
identify cases where the view is implicitly updatable, by analyzing the underlying
view query.
Example 118 Identifying When a View is Implicitly Updatable
For example, if the XMLType view query is based on an object view or an object
constructor that is itself inherently updatable:
DROP TYPE dept_t force;
CREATE OR REPLACE TYPE dept_t AS OBJECT
(
DEPTNO NUMBER(2),
DNAME VARCHAR2(14),
LOC VARCHAR2(13)
);
/
BEGIN
dbms_xmlschema.deleteSchema(http://www.oracle.com/dept.xsd, 4);
END;
/
BEGIN
dbms_xmlschema.registerSchema(http://www.oracle.com/dept.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/dept.xsd" version="1.0"
xmlns:xdb="http://xmlns.oracle.com/xdb"
elementFormDefault="qualified">
<element name = "Department" xdb:SQLType="DEPT_T" xdb:SQLSchema="SCOTT">
<complexType>
<sequence>
Query Rewrite on XMLType Views
11-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<element name = "DeptNo" type = "positiveInteger" xdb:SQLName="DEPTNO"
xdb:SQLType="NUMBER"/>
<element name = "DeptName" type = "string" xdb:SQLName="DNAME"
xdb:SQLType="VARCHAR2"/>
<element name = "Location" type = "string" xdb:SQLName="LOC"
xdb:SQLType="VARCHAR2"/>
</sequence>
</complexType>
</element>
</schema>, TRUE, FALSE, FALSE);
END;
/
CREATE OR REPLACE VIEW dept_xml of xmltype
xmlschema "http://www.oracle.com/dept.xsd" element "Department"
with object id (sys_nc_rowinfo$.extract(/Department/DeptNo).getnumberval()) as
select dept_t(d.deptno, d.dname, d.loc) from dept d;
INSERT INTO dept_xml VALUES (XMLType.createXML(
<Department xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.oracle.com/dept.xsd">
<DeptNo>50</DeptNo>
<DeptName>EDP</DeptName>
<Location>NEW YORK</Location>
</Department>));
UPDATE dept_xml d
SET d.sys_nc_rowinfo$ = updateXML(d.sys_nc_rowinfo$,
/Department/DeptNo/text(), 60)
WHERE existsNode(d.sys_nc_rowinfo$, /Department[DeptNo=50]) = 1;
Query Rewrite on XMLType Views
For Query Rewrites, XMLType views are the same as regular XMLType table
columns. Hence, extract() or existsNode() operations on view columns, get
rewritten into underlying relational accesses for better performance.
In this release, XPath predicates over these SQL/XML views are not rewritten.
Consequently, queries expressed over such view using predicates such as extract,
existsNode,... would be evaluated functionally over all the rows of the view. If
queriability of the view is important, consider using the object-relational approach,
instead of the SQL/XML functions.
Query Rewrite on XMLType Views
XMLType Views 11-21
Query Rewrite on XML Schema-Based Views
For example consider the following:
Example 119 Query Rewrite on XMLType Views: Query-Rewrite on XML
Schema-Based Views
XCREATE OR REPLACE VIEW dept_ov OF dept_t
WITH OBJECT ID (deptno) as
SELECT d.deptno, d.dname, d.loc, cast(multiset(
SELECT emp_t(e.empno, e.ename, e.job, e.mgr, e.hiredate, e.sal, e.comm)
FROM emp e
WHERE e.deptno = d.deptno)
AS emplist_t)
FROM dept d;
CREATE OR REPLACE VIEW dept_xml OF XMLTYPE
WITH OBJECT ID (EXTRACT(sys_nc_rowinfo$, /ROW/DEPTNO).getNumberVal()) AS
SELECT sys_xmlgen(value(p)) FROM dept_ov p;
A query to select department numbers that have at least one employee making a
salary more than $200000:
SELECT EXTRACTVALUE(value(x),/ROW/DEPTNO)
FROM dept_xml x
WHERE EXISTSNODE(value(x), /ROW/EMPS/EMP_T[SAL > 200]) = 1;
becomes:
ELECT d.deptno
FROM dept d
WHERE EXISTS (SELECT NULL FROM emp e WHERE e.deptno = d.deptno
AND e.sal > 200);
Query Rewrite on Non-Schema-Based XMLType Views
Consider the following example:
Example 1110 Query Rewrite on Non-Schema-Based Views
Non-schema-based XMLType views can be created on existing relational and
object-relational tables and views. This provides users with an XML view of the
underlying data.
Query Rewrite on XMLType Views
11-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Existing relational data can be transformed into XMLType views by creating
appropriate types, and doing a SYS_XMLGEN at the top-level.For example, the data
in the emp table can be exposed as follows:
CREATE TYPE Emp_t AS OBJECT (
EMPNO NUMBER(4),
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2));
CREATE VIEW employee_xml OF XMLTYPE
WITH OBJECT ID
(SYS_NC_ROWINFO$.EXTRACT(/ROW/EMPNO/text()).getnumberval()) AS
SELECT SYS_XMLGEN(
emp_t(e.empno, e.ename, e.job, e.mgr, e.hiredate, e.sal, e.comm))
FROM emp e;
A major advantage of non-schema-based views is that existing object views can be
easily transformed into XMLType views without any additional DDLs. For example,
consider a database which contains the object viewemployee_ov with the
following denition:
CREATE VIEW employee_ov OF EMP_T
WITH OBJECT ID (empno) AS
SELECT emp_t(e.empno, e.ename, e.job, e.mgr, e.hiredate, e.sal, e.comm)
FROM emp e;
-- Creating a non-schema-based XMLType views can be achieved by simply
-- calling SYS_XMLGEN over the top-level object column. No additional
-- types need to be created.
CREATE OR REPLACE VIEW employee_ov_xml OF XMLTYPE
WITH OBJECT ID
(SYS_NC_ROWINFO$.EXTRACT(/ROW/EMPNO/text()).getnumberval()) AS
SELECT SYS_XMLGEN(value(x)) from employee_ov x;
-- Certain kinds of queries on SYS_XMLGEN views are rewritten to
access the object attributes directly. Simple XPath traversals with existsNode(),
extractValue(), and extract() are candidates for rewrite. See Chapter 5,
"Structured Mapping of XMLType", "Query Rewrite with XML Schema-Based
Structured Storage" on page 5-51, for details on query rewrite.
Ad-Hoc Generation of XML Schema-Based XML
XMLType Views 11-23
For example, a query such as the following:
SELECT EXTRACT(VALUE(x), /ROW/EMPNO) FROM employee_ov_xml x
WHERE EXTRACTVALUE(value(x), /ROW/ENAME) = SMITH;
is rewritten to:
SELECT SYS_XMLGEN(empno)
FROM emp e
WHERE e.ename = SMITH;
Ad-Hoc Generation of XML Schema-Based XML
In the preceding examples, the CREATE VIEW statement specied the XML schema
URL and element name, whereas the underlying view query simply constructed a
non-XML schema-based XMLType. However, there are several scenarios where you
may want to avoid the view creation step, but still need to construct XML
schema-based XML.
To achieve this, you can use the following XML generation functions to optionally
accept an XML schema URL and element name:
I createXML()
I SYS_XMLGEN()
I SYS_XMLAGG()
If the XML schema information is specied, the resulting XML is created to be XML
schema-based:
SELECT XMLTYPE.createXML(dept_t(d.deptno, d.dname, d.loc,
CAST(MULTISET(SELECT emp_t(e.empno, e.ename, e.job, e.mgr,
e.hiredate, e.sal, e.comm)
FROM emp e WHERE e.deptno = d.deptno) AS emplist_t),
'http://www.oracle.com/dept.xsd', 'Department')
FROM dept d;
Note: Query rewrite only happens with SYS_XMLGEN. Queries
over views based on other functions are not rewritten.
See Also: Chapter 10, "Generating XML Data from the Database".
Validating User-Specified Information
11-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Validating User-Specied Information
You can ll in the optional Oracle XML DB attributes before registering the XML
schema. In this case, Oracle validates the extra information to ensure that the
specied values for the Oracle XML DB attributes are compatible with the rest of
the XML schema declarations. This form of XML schema registration typically
happens when wrapping existing data using XMLType views.
You can use the DBMS_XMLSchema generateSchema() and
generateSchemas() functions to generate the default XML mapping for
specied object types. The generated XML schema document has the SQLType,
SQLSchema, and so on, attributes lled in. When these XML schema documents are
then registered, the following validation forms can occur:
I SQLType for attributes or elements based on simpleType. This is compatible
with the corresponding XMLType. For example, an XML string datatype can
only be mapped to VARCHAR2s or Large Objects (LOBs).
I SQLType specied for elements based on complexType. This is either a LOB or
an object type whose structure is compatible with the declaration of the
complexType, that is, the object type has the right number of attributes with
the right datatypes.
See: Chapter 5, "Structured Mapping of XMLType" for more
details on this process
Creating and Accessing Data Through URLs 12-1
12
Creating and Accessing Data Through
URLs
This chapter describes how to generate and store URLs inside the database and to
retrieve the data pointed to by the URLs. It also introduces the concept of DBUris
which are URLs to relational data stored inside the database. It explains how to
create and store references to data stored in Oracle XML DB Repository hierarchy.
This chapter contains these sections:
I How Oracle9i Database Works with URLs and URIs
I URI Concepts
I UriTypes Store Uri-References
I HttpUriType Functions
I DBUri, Intra-Database References
I Some Common DBUri Scenarios
I DBUriType Functions
I XDBUriType
I Creating Oracle Text Indexes on UriType Columns
I Using UriType Objects
I Creating Instances of UriType Objects with the UriFactory Package
I Why Dene New Subtypes of UriType?
I SYS_DBURIGEN() SQL Function
I Turning a URL into a Database Query with DBUri Servlet
How Oracle9i Database Works with URLs and URIs
12-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
How Oracle9i Database Works with URLs and URIs
In developing Internet applications, and particularly Internet-based XML
applications, you often need to refer to data somewhere on a network using URLs
or URIs.
I A URL, or Uniform Resource Locator, refers to a complete document or a
particular spot within a document.
I A URI, or Uniform Resource Identier, is a more general form of URL. A URI
can be identical to a URL, or it can use extra notation in place of the anchor to
identify an enclosed section of a document (rather than a single location).
Oracle9i can represent various kinds of paths within the database. Each corresponds
to a different object type, all derived from a general type called UriType:
I HttpUriType represents a URL that begins with http://. It lets you create
objects that represent links to Web pages, and retrieve those Web pages by
calling object methods.
I DBUriType represents a URI that points to a set of rows, a single row, or a
single column within the database. It lets you create objects that represent links
to table data, and retrieve the data by calling object methods.
I XDBUriType represents a URI that points to an XML document stored in the
ORACLE XML DB Repository inside the database. We refer to these documents
or other data as resources. It lets you create objects that represent links to
resources, and retrieve all or part of any resource by calling object methods.
Note: Throughout this chapter, we refer to URIs because that is
the more general term, but the details apply to URLs as well. Some
of the type names use Uri instead of URI. Because most of this
information is based on SQL and PL/SQL, the names are usually
not case-sensitive; only when referring to a real lename on a Web
site or a Java API name does case matter.
How Oracle9i Database Works with URLs and URIs
Creating and Accessing Data Through URLs 12-3
Accessing and Processing Data Through HTTP
Any resources stored inside ORACLE XML DB Repository can also be retrieved by
using the HTTP Server in Oracle XML DB. Oracle9i also includes a servlet that
makes table data available through HTTP URLs. The data can be returned as plain
text, HTML, or XML.
Any Web-enabled client or application can use the data without SQL programming
or any specialized database API. You can retrieve the data by linking to it in a Web
page or by requesting it through the HTTP-aware APIs of Java, PL/SQL, or Perl.
You can display or process the data through any kind of application, including a
regular Web browser or an XML-aware application such as a spreadsheet. The
servlet supports generating XML and non-XML content and also transforming the
results using XSLT stylesheets.
Creating Columns and Storing Data Using UriType
You can create database columns using UriType or its child types, or you can store
just the text of each URI or URL and create the object types as needed. When storing
a mixture of subtypes in the database, you can dene a UriType column that can
store various subtypes within the same column.
Because these capabilities use object-oriented programming features such as object
types and methods, you can derive your own types that inherit from the
Oracle-supplied ones. Deriving new types lets you use specialized techniques for
retrieving the data or transforming or ltering it before returning it to the program.
UriFactory Package
When storing just the URI text in the database, you can use the UriFactory
package to turn each URI into an object of the appropriate subtype. UriFactory
package creates an instance of the appropriate type by checking what kind of URI is
represented by a given string. For example, any URI that begins with http:// is
considered an HTTP URL. When the UriFactory package is passed such a URI
string, it returns an instance of a HttpUriType object.
See Also: Chapter 26, "Oracle XML DB Basic Demo", section "8.0
XML DB Demo: Accessing Content Using DBUriServlet;
Transforming Content Using XSL".
See Also: "Registering New UriType Subtypes with the
UriFactory Package" on page 12-26
URI Concepts
12-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Other Sources of Information About URIs and URLs
Before you explore the features in this chapter, you should be familiar with the
notation for various kinds of URIs.
URI Concepts
This section introduces you to URI concepts.
What Is a URI?
A URI, or Uniform Resource Identier, is a generalized kind of URL. Like a URL, it
can reference any document, and can reference a specic part of a document. It is
more general than a URL because it has a powerful mechanism for specifying the
relevant part of the document. A URI consists of two parts:
I URL, that identies the document using the same notation as a regular URL.
I Fragment, that identies a fragment within the document. The notation for the
fragment depends on the document type. For HTML documents, it has the form
#anchor_name. For XML documents, it uses XPath notation.
The fragment appears after the # in the following examples.
See:
I http://www.w3.org/2002/ws/Activity.html an
explanation of HTTP URL notation
I http://www.w3.org/TR/xpath for an explanation of the
XML XPath notation
I http://www.w3.org/TR/xptr/ for an explanation of the
XML XPointer notation
I http://xml.coverpages.org/xmlMediaMIME.html for a
discussion of MIME types
Note: Only XDBUriType and HttpUriType support the URI
fragment in this release. DBUriType does not support the URI
fragment.
URI Concepts
Creating and Accessing Data Through URLs 12-5
How to Create a URL Path from an XML Document View
Figure 121 shows a view of the XML data stored in a relational table, EMP, in the
database, and the columns of data mapped to elements in the XML document. This
mapping is referred to as an XML visualization. The resulting URL path can be
derived from the XML document view.
Typical URIs look like the following:
I For HTML: http://www.url.com/document1#Anchor
where Anchor is a named anchor inside the document.
I For XML: http://www.xml.com/xml_doc#//po/cust/custname
where:
The portion before the # identies the location of the document.
The portion after the # identies a fragment within the document. This
portion is dened by the W3C XPointer recommendation.
UriType Objects Can Use Different Protocols to Retrieve Data
Oracle9i introduces new datatypes in the database to store and retrieve objects that
represent URIs. See "UriTypes Store Uri-References" in the following section. Each
datatype uses a different protocol, such as HTTP, to retrieve data.
Oracle9i also introduces new forms of URIs that represent references to rows and
columns of database tables.
Advantages of Using DBUri and XDBUri
The following are advantages of using DBUri and XDBUri:
I Reference stylesheets within database-generated Web pages. Oracle-supplied
package DBMS_METADATA uses DBUris to reference XSL stylesheets. XDBUri
can also be used to reference XSL stylesheets stored in ORACLE XML DB
Repository.
I Reference HTML, images and other data stored in the database. The URLs can
be used to point to data stored in tables or in the Repository hierarchical
folders.
I Improved Performance by bypassing the Web server. If you already have a
URL in your XML document, you can replace it with a reference to the database
by either:
UriTypes Store Uri-References
12-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Using a servlet
Using a DBUri/XDBUri to bring back the results
Using DBUri/XDBUri has performance benets because you interact directly
with the database rather than through a Web server.
I Accessing XML Documents in the Database Without SQL. You do not need to
know SQL to access an XML document stored in the database. With DBUri you
can access an XML document from the database without using SQL.
Since the les or resources in ORACLE XML DB Repository are stored in tables,
you can access them either through the XDBUri or by using the table metaphor
through the DBUri.
UriTypes Store Uri-References
URIs or Universal Resource Identiers identify resources such as Web pages
anywhere on the Web. Oracle9i provides the following UriTypes for storing and
accessing external and internal Uri-references:
I DBUriType.Stores references to relational data inside the database.
I HttpUriType.Implements the HTTP protocol for accessing remote pages.
Stores URLs to external Web pages or les. Accesses these les using Hyper
Text Transfer Protocol (HTTP) protocol.
I XDBUriType. Stores references to resources in Oracle XML DB Repository.
These datatypes are object types with member functions that can be used to access
objects or pages pointed to by the objects. By using UriType, you can:
I Create table columns that point to data inside or outside the database.
I Query the database columns using functions provided by UriType.
These are related by an inheritance hierarchy. UriType is an abstract type and the
DBUriType, HttpUriType, and XDBUriType are subtypes of UriType. You can
reference data stored in CLOBs or other columns and expose them as URLs to the
external world. Oracle9i provides a standard servlet than can be installed and run
under the Oracle Servlet engine that interprets these URLs.
UriTypes Store Uri-References
Creating and Accessing Data Through URLs 12-7
Advantages of Using UriTypes
Oracle already provides the PL/SQL package UTL_HTTP and the Java class
java.net.URL to fetch URL references. The advantages of dening this new
UriType datatype in SQL are:
I I mproved Mapping of XML Documents to Columns. Uri-ref support is needed
when exploding XML documents into object-relational columns, so that the
Uri-ref specied in documents can map to a URL column in the database.
I Unied access to data stored inside and outside the server. Since you can use
the UriRefs to store pointers to HTTP/DB urls, you get a unied access to the
data wherever it is stored. This lets you create queries and indexes without
having to worry about where the data resides.
UriType Functions
The UriType abstract type supports a variety of functions that can be used over
any subtype. Table 121 lists the UriType member functions.
See Also: "Using UriType Objects" on page 12-23.
Table 121 UriType Member Functions
UriType Member
Functions Description
getClob() Returns the value pointed to by the URL as a character LOB
value. The character encoding will be that of the database
character set.
getUrl() Returns the URL stored in the UriType. Do not use the
attribute url directly. Use this function instead. This can be
overridden by subtypes to give you the correct URL. For
example, HttpUriType stores only the URL and not the
http:// prex. Hence getUrl() actually prepends the
prex and returns the value.
getExternalUrl() Similar to the former (getUrl), except that it calls the escaping
mechanism to escape the characters in the URL as to conform
to the URL specication. For example spaces are converted to
the escaped value %20.
See How Oracle9i Database Works with URLs and URIs on
page 12-2.
getContentType() Returns the MIME information for the URL. For UriType, this
is an abstract function.
HttpUriType Functions
12-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
HttpUriType Functions
Use HttpUriType to store references to data that can be accessed through the
HTTP protocol. HttpUriType uses the UTL_HTTP package to fetch the data and
hence the session settings for the package can also be used to inuence the HTTP
fetch using this mechanism. Table 122 lists the HttpUriType member functions.
getXML() Returns the XMLType object corresponding to the given URI.
This is provided so that an application that needs to perform
operations other than getClob/getBlob can use the
XMLType methods to do those operations.
This throws an exception if the URI does not point to a valid
XML document.
getBlob() Returns the BLOB value pointed to by the URL. No character
conversions are performed and the character encoding is the
same as the one pointed to by the URL. This can also be used to
fetch binary data.
createUri(uri IN VARCHAR2) This constructs the UriType. It is not actually in UriType,
rather it is used for creating URI subtypes.
Table 122 HttpUriType Member Functions (Page 1 of 2)
HttpUriType Method Description
getClob Returns the value pointed to by the URL as a character LOB value.
The character encoding is the same as the database character set.
getUrl Returns stored URL.
getExternalUrl Similar to getUrl, except that it calls the escaping mechanism to
escape the characters in the URL as to conform to the URL
specication. For example, spaces are converted to the escaped
value %20.
getBlob Gets the binary content as a BLOB. If the target data is non-binary
then the BLOB will contain the XML or text representation of the
data in the database character set.
getXML Returns the XMLType object corresponding to this URI. Will
throw an error if the target data is not XML. See also "getXML()
Function" on page 12-9.
Table 121 UriType Member Functions (Cont.)
UriType Member
Functions Description
HttpUriType Functions
Creating and Accessing Data Through URLs 12-9
getContentType() Function
getContentType() function returns the MIME information for the URL. The
HttpUriType de-references the URL and gets the MIME header information. You
can use this information to decide whether to retrieve the URL as BLOB or CLOB
based on the MIME type. You would treat a Web page with a MIME type of
x/jpeg as a BLOB, and one with a MIME type of text/plain or text/html as
a CLOB.
Example 121 Using getContentType() and HttpUriType to Return HTTP Headers
Getting the content type does not fetch all the data. The only data transferred is the
HTTP headers (for HTTPURiType) or the metadata of the column (for DBUriType).
For example:
declare
httpuri HttpUriType;
x clob;
y blob;
begin
httpuri := HttpUriType('http://www.oracle.com/object1');
if httpuri.getContentType() = 'application-x/bin' then
y := httpuri.getblob();
else
x := httpuri.getclob();
end if;
end;
getXML() Function
getXML() function returns XMLType information for the result. If the document is
not valid XML (or XHTML) an error is thrown.
getContentType() Returns the MIME information for the URL. See also
"getContentType() Function" on page 12-9.
createUri() httpUriType constructor. Constructs in httpUriType.
httpUriType() httpUriType constructor. Constructs in httpUriType.
Table 122 HttpUriType Member Functions (Cont.) (Page 2 of 2)
HttpUriType Method Description
DBUri, Intra-Database References
12-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
DBUri, Intra-Database References
DBUri, a database relative to URI, is a special case of the Uri-ref mechanism,
where ref is guaranteed to work inside the context of a database and session. This
ref is not a global ref like the HTTP URL; instead it is local ref (URL) within the
database.
You can also access objects pointed to by this URL globally, by appending this
DBUri to an HTTP URL path that identies the servlet that can handle DBUri. This
is discussed in "Turning a URL into a Database Query with DBUri Servlet" on
page 12-34.
Formulating the DBUri
The URL syntax is obtained by specifying XPath-like syntax over a virtual XML
visualization of the database. See Figure 121, "DBUri: Visual or SQL View, XML
View, and Associated XPath":
I The visual model is a hierarchical view of what a current connected user would
see in terms of SQL schemas, tables, rows, and columns.
I The XML view contains a root element that maps to the database. The root XML
element contains child elements, which are the schemas on which the user has
some privileges on any object. The schema elements contain tables and views
that the user can see.
Example 122 The Virtual XML Document that Scott Sees
For example, the user scott can see the following virtual XML document.
<?xml version=1.0?>
<oradb SID="ORCL">
<PUBLIC>
<ALL_TABLES>
..
</ALL_TABLES>
<EMP>
<!-- EMp table -->
</EMP>
</PUBLIC>
<SCOTT>
<ALL_TABLES>
....
</ALL_TABLES>
<EMP>
DBUri, Intra-Database References
Creating and Accessing Data Through URLs 12-11
<ROW>
<EMPNO>1001</EMPNO>
<ENAME>John</ENAME>
<EMP_SALARY>20000</EMP_SALARY>
</ROW>
<ROW>
<EMPNO>2001</EMPNO>
</ROW>
</EMP>
<DEPT>
<ROW>
<DEPTNO>200</DEPTNO>
<DNAME>Sports</DNAME>
</ROW>
</DEPT>
</SCOTT>
<JONES>
<CUSTOMER_OBJ_TAB>
<ROW>
<NAME>xxx</NAME>
<ADDRESS>
<STATE>CA</STATE>
<ZIP>94065</ZIP>
</ADDRESS>
</ROW>
</CUSTOMER_OBJ_TAB>
</JONES>
</oradb>
DBUri, Intra-Database References
12-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 121 DBUri: Visual or SQL View, XML View, and Associated XPath
This XML document is constructed at the time you do the query and based on the
privileges that you have at that moment.
You can make the following observations from the previous example:
I User scott can see the scott database schema and jones database schema.
These are schemas on which the user has some table or views that he can read.
I Table emp shows up as EMP with rowelement tags. This is the default mapping
for all tables. The same for dept and the customer_obj_tab table under the
jones schema.
I In this release, null elements are absent
I There is also a PUBLIC element under which tables and views are accessible
without schema qualication. For example, a SELECT query such as:
SELECT * FROM emp;
when queried by user scott, matches the table emp under the scott schema
and, if not found, tries to match a public synonym named emp. In the same
way, the PUBLIC element contains:
All the tables and views visible to users through their database schema
All the tables visible through the PUBLIC synonym
URL becomes . . .
/oracle/scott/emp/row/[empno=21]/ename..
XML document
XMLview
Data stored in tables
Visual model
URI-Reference
Database
Table Emp
Empno Ename Job
.
x
x
x
.
John
Mary
x
.
21
33
x
<oracle>
<scott>
<emp>
<row>
<EmpNo> 21
<Ename> John
</row>
</emp>
</scott>
</oracle>
XML
Visualization
DBUri, Intra-Database References
Creating and Accessing Data Through URLs 12-13
Notation for DBUriType Fragments
With the Oracle9i database being visualized as an XML tree, you can performXPath
traversals to any part of the virtual document. This translates to any row-column
intersection of the database tables or views. By specifying an XPath over the
visualization model, you can create references to any piece of data in the database.
DbUri is specied in a simplied XPath format. Currently, Oracle does not support
the full XPath or XPointer recommendation for DBURType. The following sections
discuss the structure of the DBUri.
As stated in the previous paragraphs, you can now create DBUris to any piece of
data. You can use the following instances in a column as reference:
I Scalar
I Object
I Collection
I An attribute of an object type within a column. For
example:.../ROW[empno=7263]/COL_OBJ/OBJ_ATTR
These are the smallest addressable units. For example, you can use:
/oradb/SCOTT/EMP
or
/oradb/SCOTT/EMP/ROW[empno=7263]
DBUri Syntax Guidelines
There are restrictions on the kind of XPath queries that can be used to specify a
reference. In general, the fragment part must:
I Include the user database schema name or specify PUBLIC to resolve the table
name without a specic schema.
I Include a table or view name.
I Include the ROW tag for identifying the ROW element.
I Identify the column or object attribute that you wish to extract.
Note: Oracle does not currently support references within a
scalar, XMLType or LOB data column.
DBUri, Intra-Database References
12-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Include predicates at any level in the path other than the schema and table
elements.
I Indicate predicates not on the selection path in the ROW element.
Example 123 Specifying Predicate pono=100 With the ROW Node
For example, if you wanted to specify the predicate pono = 100, but the
selection path is:
/oradb/scott/purchase_obj_tab/ROW/line_item_list
you must include the pono predicate along with the ROW node as:
/oradb/scott/purchase_obj_tab/ROW[pono=100]/line_item_list
I A DBUri must identify exactly a single data value, either an object type or a
collection. If the data value is an entire row, you indicate that by including a
ROW node. The DBUri can also point to an entire table.
Using Predicate (XPath) Expressions in DBUris
The predicate expressions can use the following XPath expressions:
I Boolean operators AND, OR, and NOT
I Relational operators - <, >, <=,!=, >=, =, mod, div, * (multiply)
The predicates can be dened at any element other than the schema and table
elements. If you have object columns, you can search on the attribute values as well.
Example 124 Searching for Attribute Values on Object Columns Using DBUri
For example, the following DBUri refers to an ADDRESS column containing state,
city, street, and zip code attributes:
/oradb/SCOTT/EMP/ROW[ADDRESS/STATE=CA OR
Note:
I No XPath axes other than the child axes are supported. The
wild card (*), descendant (//), and other operations are not
valid.
I Only the text() XPath function is supported. text() is valid
only on a scalar node, not at the row or table level.
Some Common DBUri Scenarios
Creating and Accessing Data Through URLs 12-15
ADDRESS/STATE=OR]/ADDRESS[CITY=Portland OR /ZIPCODE=94404]/CITY
This DBUri identies the city attribute whose state is either California or Oregon,
or whose city name is Portland, or whose zipcode is 94404.
Some Common DBUri Scenarios
The DBUri can identify various objects, such as a table, a particular row, a
particular column in a row, or a particular attribute of an object column. The
following subsections describe how to identify different object types.
Identifying the Whole Table
This returns an XML document that retrieves the whole table. The enclosing tag is
the name of the table. The row values are enclosed inside a ROW element, as follows,
using the following syntax:
/oradb/schemaname/tablename
Example 125 Using DBUri to Identify a Whole Table as an XML Document
For example:
/oradb/SCOTT/EMP
returns an XML document with a format like the following:
<?xml version="1.0"?>
<EMP>
<ROW>
<EMPNO>7369</EMPNO>
<ENAME>Smith</ENAME>
... <!-- other columns -->
</ROW>
<!-- other rows -->
</EMP>
See Also: http://www.w3.org/TR/xpath for an explanation
of the XML XPath notation
Some Common DBUri Scenarios
12-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Identifying a Particular Row of the Table
This identies a particular ROW element in the table. The result is an XML document
that contains the ROW element with its columns as child elements. Use the following
syntax:
/oradb/schemaname/tablename/ROW[predicate_expression]
Example 126 Using DBUri to Identify a Particular Row in the Table
For example:
/oradb/SCOTT/EMP/ROW[EMPNO=7369]
returns the XML document with a format like the following:
<?xml version="1.0"?>
<ROW>
<EMPNO>7369</EMPNO>
<ENAME>SMITH</ENAME>
<JOB>CLERK</JOB>
<!-- other columns -->
</ROW>
Identifying a Target Column
In this case, a target column or an attribute of a column is identied and retrieved
as XML.
Use the following syntax:
/oradb/schemaname/tablename/ROW[predicate_expression]/columnname
/oradb/schemaname/tablename/ROW[predicate_expression]/columnname/attribute1/../attributen
Example 127 Using DBUri to Identify a Specic Column
/oradb/SCOTT/EMP/ROW[EMPNO=7369 and DEPTNO=20]/ENAME
Note: In the previous example, the predicate expression must
identify a unique row.
Note: You cannot traverse into nested table or VARRAY columns.
Some Common DBUri Scenarios
Creating and Accessing Data Through URLs 12-17
retrieves the ename column in the emp table, where empno is 7369, and
department number is 20, as follows:
<?xml version="1.0"?>
<ENAME>SMITH</ENAME>
Example 128 Using DBUri to Identify an Attribute Inside a Column
/oradb/SCOTT/EMP/ROW[EMPNO=7369]/ADDRESS/STATE
retrieves the state attribute inside an address object column for the employee
whose empno is 7369, as follows:
<?xml version="1.0"?>
<STATE>CA</STATE>
Retrieving the Text Value of a Column
In many cases, it can be useful to retrieve only the text values of a column and not
the enclosing tags. For example, if XSL stylesheets are stored in a CLOB column,
you can retrieve the document text without having any enclosing column name
tags. You can use the text() function for this. It species that you only want the
text value of the node. Use the following syntax:
/oradb/schemaname/tablename/ROW[predicate_expression]/columnname/text()
Example 129 Using DBUri to Retrieve Only the Text Value of the Node
For example:
/oradb/SCOTT/EMP/ROW[EMPNO=7369]/ENAME/text()
retrieves the text value of the employee name, without the XML tags, for an
employee with empno = 7369. This returns a text document, not an XML
document, with value SMITH.
Note: The XPath alone does not constitute a valid URI. Oracle
calls it a DBUri since it behaves like a URI within the database, but
it can be translated into a globally valid Uri-ref.
Some Common DBUri Scenarios
12-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
How DBUris Differ from Object References
A DBUri can access columns and attributes and is loosely typed Object references
can only access row objects. DBUri is a superset of this reference mechanism.
DBUri Applies to a Database and Session
A DBUri is scoped to a database and session. You must already be connected to the
database in a particular session context. The schema and permissions needed to
access the data are resolved in that context.
Where Can DBUri Be Used?
Uri-ref can be used in a number of scenarios, including those described in the
following sections:
Storing URLs to Related Documents
In the case of a travel story Web site where you store travel stories in a table, you
might create links to related stories. By representing these links in a DBUriType
column, you can create intra-database links that let you retrieve related stories
through queries.
Storing Stylesheets in the Database
Applications can use XSL stylesheets to convert XML into other formats. The
stylesheets are represented as XML documents, stored as CLOBs. The application
can use DBUriType objects:
Note: The path is case-sensitive. To specify scott.emp, you use
SCOTT/EMP, because the actual table and column names are stored
capitalized in the Oracle data dictionary. If you need to use
lowercase path values, you can create a lowercase table or column
name by enclosing the name in double quotation marks.
Note: The same URI string may give different results based on the
session context used, particularly if the PUBLIC path is used.
For example, /PUBLIC/FOO_TAB can resolve to SCOTT.FOO_TAB
when connected as scott, and resolve as JONES.FOO_TAB when
connected as JONES.
DBUriType Functions
Creating and Accessing Data Through URLs 12-19
I To access the XSL stylesheets stored in the database for use during parsing.
I To make references, such as import or include, to related XSL stylesheets. You
can encode these references within the XSL stylesheet itself.
DBUriType Functions
Table 123 lists the DBUriType methods and functions.
Table 123 DBUriType Methods and Functions
Note:
I A DBUri is not a general purpose XPointer mechanism to XML
data.
I It is not a replacement for database object references. The
syntax and semantics of references differ from those of
Uri-refs.
I It does not enforce or create any new security models or
restrictions. Instead, it relies on the underlying security
architecture to enforce privileges.
Method/Function Description
getClob() Returns the value pointed to by the URL as a character LOB value. The character
encoding is the same as the database character set.
getUrl() Returns the URL that is stored in the DBUriType.
getExternalUrl() Similar to getUrl, except that it calls the escaping mechanism to escape the
characters in the URL as to conform to the URL specication. For example, spaces
are converted to the escaped value %20.
getBlob() Gets the binary content as a BLOB. If the target data is non-binary, then the BLOB
will contain the XML or text representation of the data in the database character
set.
getXML() Returns the XMLType object corresponding to this URI.
getContentType() Returns the MIME information for the URL.
createUri() Constructs a DBUriType instance.
dbUriType() Constructs a DBUriType instance.
XDBUriType
12-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Some of the functions that have a different or special behavior in the DBUriType
are described in the following subsections.
getContentType() Function
This function returns the MIME information for the URL. The content type for a
DBUriType object can be:
I If the DBUri points to a scalar value, where the MIME type is text/plain.
I In all other cases, the MIME type is text/xml.
For example, consider the table dbtab under SCOTT:
CREATE TABLE DBTAB( a varchar2(20), b blob);
A DBUriType of '/SCOTT/DBTAB/ROW/A' has a content type of text/xml, since
it points to the whole column and the result is XML.
A DBUriType of '/SCOTT/DBTAB/ROW/B' also has a content type of text/xml.
A DBUriType of '/SCOTT/DBTAB/ROW/A/text()' has a content type of
text/plain.
A DBUriType of '/SCOTT/DBTAB/ROW/B/text()' has a content type of
text/plain.
getClob() and getBlob() Functions
In the case of DBUri, scalar binary data is handled specially. In the case of a
getClob() call on a DBUri '/SCOTT/DBTAB/ROW/B/text()' where B is a
BLOB column, the data is converted to HEX and sent out.
In the case of a getBlob() call, the data is returned in binary form. However, if an
XML document is requested, as in '/SCOTT/DBTAB/ROW/B', then the XML
document will contain the binary in HEX form.
XDBUriType
XDBUriType is a newsubtype of UriType. It provides a way to expose documents
in the ORACLE XML DB Repository as URIs that can be embedded in any
UriType column in a table.
The URL part of the URI is the hierarchical name of the XML document it refers to.
The optional fragment part uses the XPath syntax, and is separated from the URL
part by '#'.
XDBUriType
Creating and Accessing Data Through URLs 12-21
The following are examples of ORACLE XML DB URIs:
/home/scott/doc1.xml
/home/scott/doc1.xml#/purchaseOrder/lineItem
where:
I /home/scott is a folder in Oracle XML DB Repository
I doc1.xml is an XML document in this folder
I The XPath expression /purchaseOrder/lineItem refers to the line item in
this purchase order document.
Table 124 lists the XDBUriType methods. These methods do not take any
arguments.
How to Create an Instance of XDBUriType
XDBUriType is automatically registered with UriFactory so that an
XDBUriType instance can be generated by providing the URI to the getURI
method.
Table 124 XDBUriType Methods
Method Description
getClob() Returns the value pointed to by the URL as a Character Large Object (CLOB)
value. The character encoding is the same as the database character set.
get Blob() Returns the value pointed to by the URL as a Binary Large Object (BLOB) value.
getUrl() Returns the URL that is stored in the XDBUriType.
getExternalUrl() Similar to getUrl, except that it calls the escaping mechanism to escape the
characters in the URL as to conform to the URL specication. For example, spaces
are converted to the escaped value %20.
getXML() Returns the XMLType object corresponding to the contents of the resource that this
URI points to. This is provided so that an application that needs to perform
operations other than getClob/getBlob can use the XMLType methods to do those
operations.
getContentType() Returns the MIME information for the resource stored in the ORACLE XML DB
Repository.
XDBUriType() Constructor. Returns an XDBUriType for the given URI.
XDBUriType
12-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Currently, XDBUriType is the default UriType generated by the
UriFactory.getUri method, when the URI does not have any of the recognized
prexes, such as http://,/DBURI, or /ORADB.
All DBUriType URIs should have a prex of either /DBURI or /ORADB, case
insensitive.
Example 1210 Returning XDBUriType Instance
For example, the following statement returns an XDBUriType instance that refers
to /home/scott/doc1.xml:
SELECT sys.UriFactory.getUri(/home/scott/doc1.xml) FROM dual;
Example 1211 Creating XDBUriType, Inserting Values Into a Purchase Order Table
and Selecting All the PurchaseOrders
The following is an example of howXDBUriType is used:
CREATE TABLE uri_tab
(
poUrl SYS.UriType, -- Note that we have created an abstract type column
--so that any type of URI can be used
poName VARCHAR2(1000)
);
-- insert an absolute url into poUrl
-- the factory will create an XDBUriType since there's no prefix
INSERT INTO uri_tab VALUES
(UriFactory.getUri('/public/orders/po1.xml'), 'SomePurchaseOrder');
-- Now get all the purchase orders
SELECT e.poUrl.getClob(), poName FROM uri_tab e;
-- Using PL/SQL, you can access table uri_tab as follows:
declare
a UriType;
begin
-- Get the absolute URL for purchase order named like 'Some%'
SELECT poUrl into a from uri_tab WHERE poName like 'Some%';
printDataOut(a.getClob());
end;
/
Using UriType Objects
Creating and Accessing Data Through URLs 12-23
Example 1212 Retrieving Purchase Orders at a URL Using UriType, getXML() and
extractValue()
Since getXML() returns an XMLType, it can be used in the EXTRACT family of
operators. For example:
SELECT e.poUrl.getClob() FROM uri_tab e
WHERE extractValue(e.poUrl.getXML(),/User) = SCOTT;
This statement retrieves all Purchase Orders for user SCOTT.
Creating Oracle Text Indexes on UriType Columns
UriType columns can be indexed natively in Oracle9i database using Oracle Text.
No special datastore is needed.
Using UriType Objects
This section describes how to store pointers to documents and retrieve these
documents across the network, either from the database or a Web site.
Storing Pointers to Documents with UriType
As explained earlier, UriType is an abstract type containing a VARCHAR2 attribute
that species the URI. The object type has functions for traversing the reference and
extracting the data.
You can create columns using UriType to store these pointers in the database.
Typically, you declare the column using the UriType, and the objects that you store
use one or more of the derived types such as HttpUriType.
Table 124 lists some useful UriType methods.
See: Chapter 7, "Searching XML Data with Oracle
Text","XMLType Indexing" on page 7-34
Note: You can plug in any new protocol using the inheritance
mechanism. Oracle provides HttpUriType and DBUriType
types for handling HTTP protocol and for deciphering DBUri
references. For example, you can implement a subtype of UriType
to handle the gopher protocol.
Using UriType Objects
12-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 1213 Creating URL References to a List of Purchase Orders
You can create a list of all purchase orders with URL references to them as follows:
CREATE TABLE uri_tab
(
poUrl SYS.UriType, -- Note that we have created abstract type columns
-- if you know what kind of uri's you are going to store, you can
-- create the appropriate types.
poName VARCHAR2(200)
);
-- insert an absolute url into SYS.UriType..!
-- the Urifactory creates the correct instance (in this case a HttpUriType
INSERT INTO uri_tab VALUES
(sys.UriFactory.getUri('http://www.oracle.com/cust/po'),'AbsPo');
-- insert a URL by directly calling the SYS.HttpUriType constructor.
-- Note this is strongly discouraged. Note the absence of the
-- http:// prefix when creating SYS.HttpUriType instance through the default
-- constructor.
INSERT INTO uri_tab VALUES (sys.HttpUriType('proxy.us.oracle.com'),'RelPo');
-- Now extract all the purchase orders
SELECT e.poUrl.getClob(), poName FROM uri_tab e;
-- In PL/SQL
declare
a SYS.UriType;
begin
-- absolute URL
SELECT poUrl into a from uri_Tab WHERE poName like 'AbsPo%';
SELECT poUrl into a from uri_Tab WHERE poName like 'RelPo%';
-- here u need to supply a prefix before u can get at the data..!
printDataOut(a.getClob());
end;
/
See: "Creating Instances of UriType Objects with the UriFactory
Package" on page 12-26 for a description of how to use
UriFactory
Using UriType Objects
Creating and Accessing Data Through URLs 12-25
Using the Substitution Mechanism
You can create columns of the UriType directly and insert HttpUriTypes,
XDBUriTypes, and DBUriTypes into that column. You can also query the column
without knowing where the referenced document lies. For example, from the
previous example, you inserted DBUri references into the uri_tab table as follows:
INSERT INTO uri_tab VALUES
(UriFactory.getUri(
/SCOTT/PURCHASE_ORDER_TAB/ROW[PONO=1000]),ScottPo);
This insert assumes that there is a purchase order table in the SCOTT schema. Now,
the URL column in the table contains values that are pointing through HTTP to
documents globally as well as pointing to virtual documents inside the database.
A SELECT on the column using the getClob() method would retrieve the results
as a CLOB irrespective of where the document resides. This would retrieve values
from the global HTTP address stored in the rst row as well as the local DBUri
reference.:
SELECT e.poURL.getclob() FROM uri_tab e;
Using HttpUriType and DBUriType
HttpUriType and DBUriType are subtypes of UriType and implement the
functions for HTTP and DBUri references respectively.
Example 1214 DBUriType: Creating DBUri References
The following example creates a table with a column of type DBUriType and
assigns a value to it.
CREATE TABLE DBURiTab(DBUri DBUriType, dbDocName VARCHAR2(2000));
-- insert values into it..!
INSERT INTO DBUriTab VALUES
(sys.DBUriType.createUri(/ORADB/SCOTT/EMP/ROW[EMPNO=7369]),emp1);
INSERT INTO DBUriTab VALUES
(sys.DBUriType(/SCOTT/EMP/ROW[EMPNO=7369]/,null);
-- access the references
Note: HttpUriType cannot store relative HTTP references in this
release.
Creating Instances of UriType Objects with the UriFactory Package
12-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
SELECT e.DBUri.getCLOB() from DBUriTab e;
Creating Instances of UriType Objects with the UriFactory Package
The functions in the UriFactory package generate instances of the appropriate
UriType subtype (HttpUriType, DBUriType, and XDBUriType). This way,
you can avoid hardcoding the implementation in the programand handle whatever
kinds of URI strings are used as input. See Table 125.
The getUri method takes a string representing any of the supported kinds of URI
and returns the appropriate subtype instance. For example:
I If the prex starts with http://, getUri creates and returns an instance of a
SYS.HttpUriType object.
I If the string starts with either /oradb/ or /dburi/, getUri creates and
returns an instance of a SYS.DBUriType object.
I If the string does not start with one of the prexes noted in the preceding
bullets, getUri creates and returns an instance of a SYS.XDBUriType object.
.
Registering New UriType Subtypes with the UriFactory Package
The UriFactory package lets you register new UriType subtypes:
I Derive these types using the CREATE TYPE statement in SQL.
I Override the default methods to perform specialized processing when
retrieving data, or to transform the XML data before displaying it.
I Pick a new prex to identify URIs that use this specialized processing.
Note: The way UriFactory generates DBUriType instances has
changed since Oracle9i release 1 (9.0.1):
In Oracle9i release 1 (9.0.1), any URL which did not start with one
of the registered or standard prexes such as http://... was
mapped to a DBUriType by UriFactory.
In this release, you need to have a /oradb o r /dburi prex in
order for UriFactory to generate a DBUriType. Otherwise it
generates an XDBUriType.
Creating Instances of UriType Objects with the UriFactory Package
Creating and Accessing Data Through URLs 12-27
I Register the prex using UriFactory.registerURLHandler, so that the
UriFactory package can create an instance of your new subtype when it
receives a URI starting with the new prex you dened.
For example, you can invent a new protocol ecom:// and dene a subtype of
UriType to handle that protocol. Perhaps the subtype implements some special
logic for getCLOB, or does some changes to the XML tags or data within getXML.
When you register the ecom:// prex with UriFactory, any calls to
UriFactory.getUri generate the new subtype instance for URIs that begin with
the ecom:// prex.
Example 1215 UriFactory: Registering the ecom Protocol
Assume you are storing different kinds of URIs in a single table:
CREATE TABLE url_tab (urlcol varchar2(80));
-- Insert an HTTP URL
INSERT INTO url_tab VALUES (http://www.oracle.com/);
-- Insert a database URI
INSERT INTO url_tab VALUES (/oradb/SCOTT/EMPLOYEE/ROW[ENAME="Jack"]);
Table 125 UriFactory: Functions and Procedures
UriFactory Function Description
escapeUri()
MEMBER FUNCTION escapeUri() RETURN
varchar2
Escapes the URL string by replacing the non-URL characters as
specied in the Uri-ref specication by their equivalent escape
sequence.
unescapeUri()
FUNCTIONunescapeUri() RETURNvarchar2
Unescapes a given URL.
registerUrlHandler()
PROCEDURE registerUrlHandler(prex IN
varchar2, schemaName in varchar2,
typename in varchar2, ignoreCase in
boolean:= true, stripprex in boolean := true)
Registers a particular type name for handling a particular URL.
The type also implements the following static member function:
STATIC FUNCTION createUri(url IN varchar2) RETURN
<typename>;
This function is called by getUrl() to generate an instance of the type.
The stripprefix indicates that the prex must be stripped off before
calling the appropriate constructor for the type.
unRegisterUrlHandler()
PROCEDURE unregisterUrlHandler(prex in
varchar2)
Unregisters a URL handler.
Creating Instances of UriType Objects with the UriFactory Package
12-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
-- Create a new type to handle a new protocol called ecom://
CREATE TYPE EComUriType UNDER SYS.UriType
(
overriding member function getClob return clob,
overriding member function getBlob RETURN blob,
overriding member function getExternalUrl return varchar2,
overriding member function getUrl return varchar2,
-- Must have this for registering with the URL handler
static function createUri(url in varchar2) return EcomUriType
);
/
-- Register a new handler for the ecom:// prefix.
begin
-- register a new handler for ecom:// prefixes. The handler
-- type name is ECOMUriTYPE, schema is SCOTT
-- Ignore the prefix case, so that UriFactory creates the same subtype
-- for URIs beginning with ECOM://, ecom://, eCom://, and so on.
-- Strip the prefix before calling the createUri function
-- so that the string ecom:// is not stored inside the
-- ECOMUriTYPE object. (It is added back automatically when
-- you call ECOMUriTYPE.getURL.)
urifactory.registerURLHandler
(
prefix => ecom://,
schemaname => SCOTT,
typename => ECOMURITYPE,
ignoreprefixcase => true,
stripprefix => true
);
end;
/
-- Now the example inserts this new type of URI into the table.
insert into url_tab values (ECOM://company1/company2=22/comp);
-- Use the factory to generate an instance of the appropriate
-- subtype for each URI in the table.
select urifactory.getUri(urlcol) from url_tab;
-- would now generate
HttpUriType(www.oracle.com); -- a Http uri type instance
SYS_DBURIGEN() SQL Function
Creating and Accessing Data Through URLs 12-29
DBUriType(/oradb/SCOTT/EMPLOYEE/ROW[ENAME="Jack"],null); -- a DBUriType
EComUriType(company1/company2=22/comp); -- an EComUriType instance
Why Dene New Subtypes of UriType?
Deriving a new class for each protocol has these advantages:
I If you choose a subtype for representing a column, it provides an implicit
constraint on the column to contain only instances of that protocol type. This
might be useful for implementing specialized indexes on that column for
specic protocols. For example, for the DBUri you can implement some
specialized indexes that can directly go and fetch the data from the disk blocks
rather than executing SQL queries.
I Additionally, you can have different constraints on the columns based on the
type involved. For instance, for the HTTP case, you could potentially dene
proxy and rewall constraints on the column so that any access through the
HTTP would use the proxy server.
SYS_DBURIGEN() SQL Function
You can create an instance of DBUriType type by specifying the path expression to
the constructor or the UriFactory methods. However, you also need methods to
generate these objects dynamically, based on strings stored in table columns. You
do this with the SQL function SYS_DBURIGEN().
Example 1216 SYS_DBURIGEN(): Generating a URI of type DBUriType that points to
a Column
The following example uses SYS_DBURIGEN() to generate a URI of datatype
DBUriType pointing to the email column of the row in the sample table
hr.employees where the employee_id = 206:
SELECT SYS_DBURIGEN(employee_id, email)
FROM employees
WHERE employee_id = 206;
SYS_DBURIGEN(EMPLOYEE_ID,EMAIL)(URL, SPARE)
-------------------------------------------------------------------
DBURITYPE(/PUBLIC/EMPLOYEES/ROW[EMPLOYEE_ID = "206"]/EMAIL, NULL)
SYS_DBURIGEN() SQL Function
12-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
SYS_DBURIGEN() takes as its argument one or more columns or attributes, and
optionally a rowid, and generates a URI of datatype DBUriType to a particular
column or row object. You can use the URI to retrieve an XML document from the
database. The function takes an additional parameter to indicate if the text value of
the node is needed. See Figure 122.
Figure 122 SYS_DBURIGEN Syntax
All columns or attributes referenced must reside in the same table. They must
reference a unique value. If you specify multiple columns, the initial columns
identify the row in the database, and the last column identies the column within
the row.
By default, the URI points to a formatted XML document. To point only to the text
of the document, specify the optional text() keyword.
If you do not specify an XML schema, Oracle interprets the table or view name as a
public synonym.
Rules for Passing Columns or Object Attributes to SYS_DBURIGEN()
The column or attribute passed to the SYS_DBURIGEN() function must obey the
following rules:
I Unique mapping: The column or object attribute must be uniquely mappable
back to the table or view from which it comes. The only virtual columns
allowed are the VALUE and REF operators. The column may come from a
TABLE() subquery or an inline view, as long as the inline view does not
rename the columns.
I Key columns: Either the rowid or a set of key columns must be specied. The
list of key columns does not need to be declared as a unique or primary key, as
long as the columns uniquely identify a particular row in the result.
See Also: Oracle9i SQL Reference for SYS_DBURIGEN syntax
SYS_DBURIGEN (
column
attribute
rowid
,
, text ( )
)
SYS_DBURIGEN() SQL Function
Creating and Accessing Data Through URLs 12-31
I Same table: All columns referenced in the SYS_DBURIGEN() function must
come from the same table or view.
I PUBLIC element: If the table or view pointed by the rowid or key columns
does not have a database schema specied, then the PUBLIC keyword is used
instead of the schema. When the DBUri is accessed, the table name resolves to
the same table, synonym, or view that was visible by that name when the
DBUri was created.
I TEXT function: DBUri, by default, retrieves an XML document containing the
result. To retrieve only the text value, use the text() keyword as the nal
argument to the function.
For example:
select SYS_DBURIGEN(empno,ename,text()) from scott.emp,
WHERE empno=7369;
or you can just generates a URL of the form:
/SCOTT/EMP/ROW[EMPNO=7369]/ENAME/text()
I Single-column argument: If there is a single-column argument, the column is
used both as the key column to identify the row and as the referenced column.
Example 1217 Passing Columns With Single Arguments to SYS_DBURIGEN()
For example:
select SYS_DBURIGEN(empno) from emp
WHERE empno=7369;
uses the empno both as the key column and the referenced column, generating
a URL of the form:
/SCOTT/EMP/ROW[EMPNO=7369]/EMPNO,
for the row with empno=7369
SYS_DBURIGEN Examples
Example 1218 Inserting Database References Using SYS_DBURIGEN()
CREATE TABLE doc_list_tab(docno number primary key, doc_ref SYS.DBUriType);
-- inserts /SCOTT/EMP/ROW[rowid=xxx]/EMPNO
SYS_DBURIGEN() SQL Function
12-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
INSERT INTO doc_list_tab values(1001,
(select SYS_DBURIGEN(rowid,empno) from emp where empno = 100));
-- insert a Uri-ref to point to the ename column of emp!
INSERT INTO doc_list_tab values(1002,
(select SYS_DBURIGEN(empno, ename) from emp where empno = 7369));
-- result of the DBURIGEN looks like, /SCOTT/EMP/ROW[EMPNO=7369]/ENAME
Returning Partial Results
When selecting the results of a large column, you might want to retrieve only a
portion of the result and create a URL to the column instead. For example, consider
the case of a travel story Web site. If all the travel stories are stored in a table, and
users search for a set of relevant stories, you do not want to list each entire story in
the result page. Instead, you show the rst 100 characters or gist of the story and
then return a URL to the full story.This can be done as follows:
Example 1219 Returning a Portion of the Results By Creating a View and Using
SYS_DBURIGEN()
Assume that the travel story table is dened as follows:
CREATE TABLE travel_story
(
story_name varchar2(100),
story clob
);
-- insert some value..!
INSERT INTO travel_story values (Egypt,This is my story of how I spent my
time in Egypt, with the pyramids in full view from my hotel room);
Now, you create a function that returns only the rst 20 characters from the story:
create function charfunc(clobval IN clob ) return varchar2 is
res varchar2(20);
amount number := 20;
begin
dbms_lob.read(clobval,amount,1,res);
return res;
end;
/
SYS_DBURIGEN() SQL Function
Creating and Accessing Data Through URLs 12-33
Now, you create a view that selects out only the rst 100 characters from the story
and then returns a DBUri reference to the story column:
CREATE VIEW travel_view as select story_name, charfunc(story) short_story,
SYS_DBURIGEN(story_name,story,text()) story_link
FROM travel_story;
Now, a SELECT from the view returns the following:
SELECT * FROM travel_view;
STORY_NAME SHORT_STORY STORY_LINK
-----------------------------------------------------------------------------
Egypt This is my story of h
SYS.DBUriType(/PUBLIC/TRAVEL_STORY/ROW[STORY_NAME=Egypt]/STORY/text())
RETURNING Uri-Refs
You can use SYS_DBURIGEN() in the RETURNING clause of DML statements to
retrieve the URL of an object as it is inserted.
Example 1220 Using SYS_DBURIGEN in the RETURNING Clause to Retrieve the
URL of an Object
For example, consider the table CLOB_TAB:
CREATE TABLE clob_tab ( docid number, doc clob);
When you insert a document, you might want to store the URL of that document in
another table, URI_TAB.
CREATE TABLE uri_tab (docs sys.DBUriType);
You can specify the storage of the URL of that document as part of the insert into
CLOB_TAB, using the RETURNING clause and the EXECUTE IMMEDIATE syntax to
execute the SYS_DBURIGEN function inside PL/SQL as follows:
declare
ret sys.dburitype;
begin
-- exucute the insert and get the url
EXECUTE IMMEDIATE
insert into clob_tab values (1,TEMP CLOB TEST)
RETURNING SYS_DBURIGEN(docid, doc, text()) INTO :1
RETURNING INTO ret;
Turning a URL into a Database Query with DBUri Servlet
12-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
-- insert the url into uri_tab
insert into uri_tab values (ret);
end;
/
The URL created has the form:
/SCOTT/CLOB_TAB/ROW[DOCID="xxx"]/DOC/text()
Turning a URL into a Database Query with DBUri Servlet
You can make table data accessible from your browser or any Web client, using the
URI notation within a URL to specify the data to retrieve:
I Through DBUri servlet linked in with the database server.
I By writing your own servlet that runs on a servlet engine. The servlet can read
the URI string from the path of the invoking URL, create a DBUriType object
using that URI, call the UriType methods to retrieve the data, and return the
values in the form of a Web page or an XML document.
DBUri Servlet Mechanism
For the preceding methods, a servlet runs for accessing this information through
HTTP. This servlet takes in a path expression following the servlet name as the
DBUri reference and outputs the document pointed to by the DBUri to the output
stream.
The generated document can be a Web page, an XML document, plain text, and so
on. You can specify the MIME type so that the browser or other application knows
what kind of content to expect:
Note: The text() keyword is appended to the end indicating
that you want the URL to return just the CLOB value and not an
XML document enclosing the CLOB text.
Note: The Oracle servlet engine is being desupported.
Consequently the oracle.xml.dburi.OraDBUriServlet
supported in Oracle9i Release 1 (9.0.1), is also being desupported.
Use the DBUri C-servlet instead which uses the Oracle XML DB
servlet system. See also Chapter 20, "Writing Oracle XML DB
Applications in Java".
Turning a URL into a Database Query with DBUri Servlet
Creating and Accessing Data Through URLs 12-35
I By default, the servlet can produce MIME types of text/xml and
text/plain. If the URI ends in a text() function, then the text/plain
MIME type is used, else an XML document is generated with the MIME type of
text/xml.
I You can override the MIME type and set it to binary/x-jpeg or some other
value using the contenttype argument to the servlet.
Example 1221 URL for Overriding the MIME Type by Generating the contenttype
Argument, to Retrieve the empno Column of Table Employee
For example, to retrieve the empno column of the employee table, you can write a
URL such as one of the following:
-- Generates a contenttype of text/plain
http://machine.oracle.com:8080/oradb/SCOTT/EMP/ROW[EMPNO=7369]/ENAME/text()
-- Generates a contenttype of text/xml
http://machine.oracle.com:8080/oradb/SCOTT/EMP/ROW[EMPNO=7369/ENAME
where the machine machine.oracle.com is running the Oracle9i database, with
a Web service at port 8080 listening to requests. oradb is the virtual path that maps
to the servlet.
DBUri Servlet: Optional Arguments
Table 126 describes the three optional arguments you can pass to DBUri servlet to
customize the output.
Table 126 DBUri Servlet: Optional Arguments
Argument Description
rowsettag Changes the default root tag name for the XML document. For
example:
http://machine.oracle.com:8080/oradb/SCOTT/EMP
?rowsettag=Employee
contenttype Species the MIME type of the returned document. For
example:
http://machine.oracle.com:8080/oradb/SCOTT/EMP
?contenttype=text/plain
Turning a URL into a Database Query with DBUri Servlet
12-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Installing DBUri Servlet
DbUriServlet is built into the database, and the installation is handled by the
ORACLE XML DB conguration le. To customize the installation of the servlet,
you need to edit it. You can edit the cong le, xdbconfig.xml under the
ORACLE XML DB user, through WebDAV, FTP, fromOracle Enterprise Manager, or
in the database. To update the le using FTP or WebDAV, simply download the
document, edit it as necessary, and save it back in the database. There are several
things that can be customized using the conguration le.
transform This argument passes a URL to UriFactory, which in turn
retrieves the XSL stylehseet at that location. This stylesheet is
then applied to the XML document being returned by the
servlet. For example:
http://machine.oracle.com:8080/oradb/SCOTT/EMP
?transform=/oradb/SCOTT/XSLS/DOC/text()&conten
ttype=text/html
Note: When using XPath notation in the URL for this servlet, you
may have to escape certain characters such as square brackets. You
can use the getExternalUrl() functions in the UriType types
to get an escaped version of the URL.
Note: In HTTP access, special characters such as, ], [, &, | have to
be escaped using the %xx format, where xx is the hexadecimal
number of the ASCII code for that character. Use the
getExternalUrl() function in the UriType family to get an
escaped version of the URL.
See Also:
I Chapter 20, "Writing Oracle XML DB Applications in Java"
I Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
I Appendix A, "Installing and Conguring Oracle XML DB"
Table 126 DBUri Servlet: Optional Arguments (Cont.)
Argument Description
Turning a URL into a Database Query with DBUri Servlet
Creating and Accessing Data Through URLs 12-37
Notice that the servlet is installed at /oradb/* specied in the servlet-pattern tag.
The * is necessary to indicate that any path following oradb is to be mapped to the
same servlet. The oradb is published as the virtual path. Here, you can change the
path that will be used to access the servlet.
Example 1222 Installing DBUri Servlet Under /dburi/*
For example, to have the servlet installed under /dburi/*, you can run the
following PL/SQL:
declare
doc XMLType;
doc2 XMLType;
begin
doc := dbms_xdb.cfg_get();
select updateXML(doc,
/xdbconfig/sysconfig/protocolconfig/httpconfig/webappconfig/servletconfig/servl
et-mappings/servlet-mapping[servlet-name="DBUriServlet"]/servlet-pattern/text()
, /dburi/*) into doc2 from dual;
dbms_xdb.cfg_update(doc2);
commit;
end;
/
Security parameters, the servlet display-name, and the description can also be
customized in the xdbconfig.xml conguration le. See Appendix A, "Installing
and Conguring Oracle XML DB" and Chapter 20, "Writing Oracle XML DB
Applications in Java". The servlet can be removed by deleting the servlet-pattern for
this servlet. This can also be done using updateXML() to update the
servlet-mapping element to null.
DBUri Security
Servlet security is handled by Oracle9i database using roles. When users log in to
the servlet, they use their database username and password. The servlet will check
to make sure the user logging in belongs to one of the roles specied in the
conguration le. The roles allowed to access the servlet are specied in the
security-role-ref tag. By default, the servlet is available to the special role
authenticatedUser. Any user who logs into the servlet with any valid database
username and password belongs to this role.
This parameter can be changed to restrict access to any role(s) in the database. To
change from the default authenticated-user role to a role that you have created, say
servlet-users, run:
Turning a URL into a Database Query with DBUri Servlet
12-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
declare
doc XMLType;
doc2 XMLType;
doc3 XMLType;
begin
doc := dbms_xdb.cfg_get();
select updateXML(doc,
/xdbconfig/sysconfig/protocolconfig/httpconfig/webappconfig/servletconfig/servl
et-list/servlet[servlet-name="DBUriServlet"]/security-role-ref/role-name/text()
, servlet-users) into doc2 from dual;
select updateXML(doc2,
/xdbconfig/sysconfig/protocolconfig/httpconfig/webappconfig/servletconfig/servl
et-list/servlet[servlet-name="DBUriServlet"]/security-role-ref/role-link/text()
, servlet-users) into doc3 from dual;
dbms_xdb.cfg_update(doc3);
commit;
end;
/
Conguring the UriFactory Package to Handle DBUris
The UriFactory, as explained in "Creating Instances of UriType Objects with the
UriFactory Package" on page 12-26, takes a URL and generates the appropriate
subtypes of the UriType to handle the corresponding protocol. For HTTP URLs,
UriFactory creates instances of the HttpUriType. But when you have an HTTP
URL that represents a URI path, it is more efcient to store and process it as a
DBUriType instance in the database. The DBUriType processing involves fewer
layers of communication and potentially fewer character conversions.
After you install OraDBUriServlet, so that any URL such as
http://machine-name/servlets/oradb/ gets handled by that servlet, you
can congure the UriFactory to use that prex and create instances of the
DBUriType instead of HttpUriType:
begin
-- register a new handler for the dburi prefix..
urifactory.registerHandler(http://machine-name/servlets/oradb
,SYS,DBUriTYPE, true,true);
end;
/
After you execute this block in your session, any UriFactory.getUri() call in
that session automatically creates an instance of the DBUriType for those HTTP
URLs that have the prex.
Turning a URL into a Database Query with DBUri Servlet
Creating and Accessing Data Through URLs 12-39
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
for details of all functions in DBUriFactory package.
Turning a URL into a Database Query with DBUri Servlet
12-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Part V
Oracle XML DB Repository: Foldering,
Security, and Protocols
Part V of this manual describes Oracle XML DB Repository. It includes how to
version your data, implement and manage security, and how to use the associated
Oracle XML DB APIs to access and manipulate Repository data.
Part V contains the following chapters:
I Chapter 13, "Oracle XML DB Foldering"
I Chapter 14, "Oracle XML DB Versioning"
I Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
I Chapter 16, "Oracle XML DB Resource API for PL/SQL (DBMS_XDB)"
I Chapter 17, "Oracle XML DB Resource API for Java"
I Chapter 18, "Oracle XML DB Resource Security"
I Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
I Chapter 20, "Writing Oracle XML DB Applications in Java"
Oracle XML DB Foldering 13-1
13
Oracle XML DB Foldering
This chapter describes how to access data in Oracle XML DB Repository using
standard protocols such as FTP, HTTP/WebDAV and other Oracle XML DB
Resource APIs. It also introduces you to using RESOURCE_VIEW and PATH_VIEW as
the SQL mechanism for accessing and manipulating Repository data. It includes a
table for comparing Repository operations through the various Resource APIs.
This chapter contains the following sections:
I Introducing Oracle XML DB Foldering
I Oracle XML DB Repository
I Oracle XML DB Resources
I Accessing Oracle XML DB Repository Resources
I Navigational or Path Access
I Query-Based Access
I Accessing Repository Data Using Servlets
I Accessing Data Stored in Oracle XML DB Repository Resources
I Managing and Controlling Access to Resources
I Extending Resource Metadata Properties
I Frequently Asked Questions (FAQs): XML DB Repository
Introducing Oracle XML DB Foldering
13-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB Foldering
Using the foldering feature in Oracle XML DB you can store content in the database
in hierarchical structures, as opposed to traditional relational database structures.
Figure 131 is an example of a hierarchical structure that shows a typical tree of
folders and les in Oracle XML DB Repository. The top of the tree shows /, the
root folder.
Foldering allows applications to access hierarchically indexed content in the
database using the FTP, HTTP, and WebDAV protocol standards as if the database
content is stored in a le system.
This chapter provides an overview of how to access data in Oracle XML DB
Repository folders using the standard protocols. There are other APIs available in
this release, which allow you to access the Repository object hierarchy using Java,
SQL, and PL/SQL.
Introducing Oracle XML DB Foldering
Oracle XML DB Foldering 13-3
Figure 131 A Typical Folder Tree Showing Hierarchical Structures in Oracle XML
Repository
Caution: The directory /sys is used by Oracle XML DB to
maintain system-de ned XML schemas, ACLs, and so on. In
general:
I Do not store any data under the /sys directory.
I Do not modify any content in the /sys directory.
/ Root Node
/acls
/schemas
/home /sys
/log
/SCOTT /XDB
11_28_01.txt
/PUBLIC
all_all_acl.xml
all_owner_acl.xml
/acls /schemas
/po
/graphics /general
/acls
/schemas
/xmlns.oracle.com
/xdb
XDBSchema.xsd
banner.png
logo.gif
architecture.jpg
into.doc
maincode.jav
chapter1.xml
whatsnew.fm
readme.txt
Binary
files stored
as BLOBs
Graphics
or
binary.files
stored in
BLOBs
XML files
typically stored
object-relationally
can also store
in LOBS
Oracle
XML DB
folders
(containers)
po_Jan03.xml
po_Jan02.xml
po_101.xml
XML files
stored in your
XMLType
tables / views
Directories
(containers)
Files or Documents
(non-containers)
ACL files
are stored
in xdb.xdb$ACL
table
Oracle XML DB System Folders
Do not store your data in /sys
Oracle XML DB Repository
13-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Repository
Oracle XML DB Repository (Repository) is the set of database objects, across all
XML and database schemas, that are mapped to path names. It is a connected,
directed, acyclic graph of resources with a single root node (/). Each resource in the
graph has one or more associated path names.
The Repository can be thought of as a le system of objects rather than les.
Repository Terminology
The following lists describes terms used in Oracle XML DB Repository:
I Resource: A resource is any object or node in the hierarchy. Resources are
identied by URLs. See "Oracle XML DB Resources" on page 6.
I Folder: A folder is a node (or directory) in the hierarchy that can contain a
collection of resources. A folder is also a resource.
I Pathname: A hierarchical name composed of a root element (the rst /),
element separators /, and various subelements (or path elements). A path
element may be composed of any character in the database character set except
\ and /, which have special meanings in Oracle XML DB. The forward slash is
the default name separator in a path name, and the backward slash is used to
escape characters. The Oracle XML DB conguration le xdbconfig.xml also
contains a list of user-dened characters that may not appear within a path
name (<invalid-pathname-chars>).
I Resource or Link name: The name of a resource within its parent folder.
Resource names must be unique (case-sensitive in this release) within a folder.
Resource names are always in the UTF8 character set (NVARCHAR).
See Also:
I Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
I Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
I Chapter 17, "Oracle XML DB Resource API for Java"
I Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
Note: The Repository supports multiple links to a given resource.
Oracle XML DB Repository
Oracle XML DB Foldering 13-5
I Contents: The body of a resource, what you get when you treat the resource like
a le and ask for its contents. Contents is always an XMLType.
I XDBBinary: An XML element dened by the Oracle XML DB schema that
contains binary data. XDBBinary elements are stored in the Repository when
unstructured binary data is uploaded into Oracle XML DB.
I Access Control List (ACL): Restricts access to a resource or resources. Oracle
XML DB uses ACLs to restrict access to any Oracle XML DB resource (any
XMLType object that is mapped into the Oracle XML DB le system hierarchy).
Many terms used by Oracle XML DB have common synonyms used in other
contexts, as shown in Table 131.
See Also: Chapter 18, "Oracle XML DB Resource Security"
Table 131 Synonyms for Oracle XML DB Foldering Terms
Synonym
Oracle XML DB
Foldering Term Usage
Collection Folder WebDAV
Directory Folder Operating systems
Privilege Privilege Permission
Right Privilege Various
WebDAV Folder Folder Web Folder
Role Group Access control
Revision Version RCS, CVS
File system Repository Operating systems
Hierarchy Repository Various
File Resource Operating systems
Binding Link WebDAV
Oracle XML DB Resources
13-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Resources
Oracle XML DB resources conform to the xdbresource.xsl schema, which is
dened by Oracle XML DB. The elements in a resource include those needed to
persistently store WebDAV-dened properties, such as creation date, modication
date, WebDAV locks, owner, ACL, language, and character set.
Contents Element in Resource Index
A resource index has a special element called Contents which contains the
contents of the resource.
any Element
The XML schema for a resource also denes an any element, with maxoccurs
unbounded, which allowed to contain any element outside the Oracle XML DB
XML namespace. This way, arbitrary instance-dened properties can be associated
with the resource.
Where Exactly Is Repository Data Stored?
Oracle XML DB stores Repository data in a set of tables and indexes in the Oracle
XML DB database schema. These tables are accessible. If you register an XML
schema and request the tables be generated by Oracle XML DB, the tables are
created in your database schema. This means that you are able to see or modify
them. However, other users will not be able to see your tables unless you explicitly
grant them permission to do so.
Generated Table Names
The names of the generated tables are assigned by Oracle XML DB and can be
obtained by nding the xdb:defaultTable=XXX attribute in your XML schema
document (or the default XML schema document). When you register an XML
schema, you can also provide your own table name, and override the default
created by Oracle XML DB.
Defining Structured Storage for Resources
Applications that need to dene structured storage for resources can do so by
either:
See Also: "Guidelines for Using Registered XML Schemas" on
page 5-14 in Chapter 5, "Structured Mapping of XMLType"
Oracle XML DB Resources
Oracle XML DB Foldering 13-7
I Subclassing the Oracle XML DB resource type. Subclassing Oracle XML DB
resources requires privileges on the table XDB$RESOURCE.
I Storing data conforming to a visible, registered XML schema.
Pathname Resolution
The data relating a folder to its children is managed by the Oracle XML DB
hierarchical index. This provides a fast mechanism for evaluating path names,
similar to the directory mechanisms used by operating-system le systems.
Resources that are folders have the Container attribute set to TRUE.
To resolve a resource name in a folder, the current user must have the following
privileges:
I resolve privilege on the folder
I read-properties on the resource in that folder
If the user does not have these privileges, he receives an access denied error.
Folder listings and other queries will not return a row when the
read-properties privilege is denied on its resource.
Deleting Resources
Deletion of a link deletes the resource pointed to by the link if and only if that was
the last link to the resource and the resource is not versioned. Links in Oracle XML
DB Repository are analogous to Unix hard links.
See Also: Chapter 5, "Structured Mapping of XMLType".
Note: Error handling in path name resolution differentiates
between invalid resource names and resources that are not folders
for compatibility with le systems. Since Oracle XML DB resources
are accessible from outside the Repository (using SQL), denying
read access on a folder that contains a resource will not prevent
read access to that resource.
See Also: "Deleting Repository Resources: Examples" on
page 15-13
Accessing Oracle XML DB Repository Resources
13-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Accessing Oracle XML DB Repository Resources
Oracle XML DB provides two techniques for accessing resources:
I "Navigational or Path Access" on page 13-9. Navigational/path access to
content in Oracle XML DB is achieved using a hierarchical index of objects or
resources. Each resource has one or more unique path names that reect its
location in the hierarchy. You can use navigational access to reference any object
in the database without regard to its location in the tablespace.
I "Query-Based Access" on page 13-12. SQL access to the Repository is done
using a set of views that expose resource properties and path names and map
hierarchical access operators onto the Oracle XML DB schema.
Figure 132 illustrates Oracle XML DB data access options. A high level discussion
of which data access option to select is described in Chapter 2, "Getting Started with
Oracle XML DB", "Oracle XML DB Application Design: b. Access Models" on
page 13-4.
Figure 132 Oracle XML DB Repository Data Access Options
See Also: Table 133, "Accessing Oracle XML DB Repository: API
Options"
Oracle XML DB
Data Access Options
Use SQL Use Repository
JDBC / Java bean
PL/SQL
Available Languages
and APIs
SQL (RESOURCE_ / PATH_VIEW)
JNDI
FTP
HTTP / WebDav
Available Language
and XMLType APIs
Query-based
Access
Path-based
Access
Navigational or Path Access
Oracle XML DB Foldering 13-9
A UniformResource Locator (URL) is used to access an Oracle XML DB resource. A
URL includes the hostname, protocol information, path name, and resource name of
the object.
Navigational or Path Access
Oracle XML DB folders support the same protocol standards used by many
operating systems. This allows an Oracle XML DB folder to function just like a
native folder or directory in supported operating-system environments. For
example: you can:
I Use Windows Explorer to open and access Oracle XML DB folders and
resources the same way you access other directories or resources in the
Windows NT le system, as shown in Figure 133.
I Access Repository data using HTTP/WebDAV from an Internet Explorer
browser, such as when viewing Web Folders, as shown in Figure 134.
Figure 133 Oracle XML DB Folders in Windows Explorer
Navigational or Path Access
13-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 134 Accessing Repository Data Using HTTP/WebDAV and Navigational Access From IE
Browser: Viewing Web Folders
Accessing Oracle XML DB Resources Using Internet Protocols
Oracle Net Services provides one way of accessing database resources. Oracle XML
DB support for Internet protocols provides another way of accessing database
resources.
Where You Can Use Oracle XML DB Protocol Access
Oracle Net Services is optimized for record-oriented data. Internet protocols are
designed for stream-oriented data, such as binary les or XML text documents.
Oracle XML DB protocol access is a valuable alternative to Net Services in the
following scenarios:
I Direct database access from le-oriented applications using the database like a
le system
Navigational or Path Access
Oracle XML DB Foldering 13-11
I Heterogeneous application server environments that want a uniform data
access method (such as XML over HTTP, which is supported by most data
servers, including MS SQL Server, Exchange, Notes, many XML databases,
stock quote services and news feeds)
I Application server environments that want data as XML text
I Web applications using client-side XSL to format datagrams not needing much
application processing
I Web applications using Java servlets running inside the database
I Web access to XML-oriented stored procedures
Protocol Access Calling Sequence
Protocol access uses the following steps in Oracle XML DB:
1. A connection object is established, and the protocol may decide to read part of
the request.
2. The protocol decides if the user is already authenticated and wants to reuse an
existing session or if the connection must be reauthenticated (generally the
case).
3. An existing session is pulled from the session pool, or a new one is created.
4. If authentication has not been provided and the request is HTTP Get or Head,
the session is run as the ANONYMOUS user. If the session has already been
authenticated as the ANONYMOUS user, there is no cost to reuse the existing
session. If authentication has been provided, the database reauthentication
routines are used to authenticate the connection.
5. The request is parsed.
6. If the requested path name maps to a servlet (for HTTP only), the servlet is
invoked using the Java VM. The servlet code writes out the response to a
response stream or asks XMLType instances to do so.
Retrieving Oracle XML DB Resources
When the protocol indicates that a resource is to be retrieved, the path name to the
resource is resolved. Resources being fetched are always streamed out as XML, with
the exception of resources containing the XDBBinary element, an element dened
to be the XML binary data type, which have their contents streamed out in RAW
form.
Query-Based Access
13-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Storing Oracle XML DB Resources
When the protocol indicates that a resource must be stored, Oracle XML DB checks
the documents le name extension for .xml, .xsl, .xsd, and so on. If the document is
XML, a pre-parse step is done, where enough of the resource is read to determine
the XML schemaLocation and namespace of the root element in the document.
This location is used to look for a registered schema with that schemaLocation
URL. If a registered schema is located with a denition for the root element of the
current document, the default table specied for that element is used to store that
resource's contents.
Using Internet Protocols and XMLType: XMLType Direct Stream Write
Oracle XML DB supports Internet protocols at the XMLType level by using the
writeToStream() Java method on XMLType. This method is natively
implemented and writes XMLType data directly to the protocol request stream. This
avoids the overhead of converting database data through Java datatypes, creating
Java objects, and Java VM execution costs, resulting in signicantly higher
performance. This is especially the case if the Java code deals with XML element
trees only close to the root, without traversing too many of the leaf elements, hence
minimizing the number of Java objects created.
Query-Based Access
Oracle XML DB provides two Repository views to enable SQL access to Repository
data:
I PATH_VIEW
I RESOURCE_VIEW
Table 132 summarizes the differences between PATH_VIEW and RESOURCE_VIEW.
See Also: Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
Table 132 Differences Between PATH_VIEW and RESOURCE_VIEW
PATH_VIEW RESOURCE_VIEW
Contains link properties No link properties
Contains resource properties and path name Contains resource properties and path name
Has one row for each unique path in the
Repository
Has one row for each resource in the
Repository
Accessing Repository Data Using Servlets
Oracle XML DB Foldering 13-13
The single path in the RESOURCE_VIEW is arbitrarily chosen from among the many
possible paths that refer to a resource. Oracle XML DB provides operators like
UNDER_PATH that enable applications to search for resources contained
(recursively) within a particular folder, get the resource depth, and so on. Each row
in the views is of XMLType.
DML on the Oracle XML DB Repository views can be used to insert, rename, delete,
and update resource properties and contents. Programmatic APIs must be used for
other operations, such as creating links to existing resources.
Accessing Repository Data Using Servlets
Oracle XML DB implements the Java servlet API, version 2.2, with the following
exceptions:
I All servlets must be distributable. They must expect to run in different VMs.
I WAR and web.xml les are not supported. Oracle XML DB supports a subset
of the XML congurations in this le. An XSL stylesheet can be applied to the
web.xml to generate servlet denitions. An external tool must be used to create
database roles for those dened in the web.xml le.
I JSP (Java Server Pages) support can be installed as a servlet and congured
manually.
I HTTPSession and related classes are not supported.
I Only one servlet context (that is, one Web application) is supported.
Note: Each resource can have multiple paths.
See Also:
I Chapter 15, "RESOURCE_VIEW and PATH_VIEW" for details
on SQL Repository access
I Chapter 18, "Oracle XML DB Resource Security"
I Oracle9i XML API Reference - XDK and Oracle XML DB
See Also: Chapter 20, "Writing Oracle XML DB Applications in
Java"
Accessing Data Stored in Oracle XML DB Repository Resources
13-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Accessing Data Stored in Oracle XML DB Repository Resources
The three main ways you can access data stored in Oracle XML DB Repository
resources are through:
I Oracle XML DB Resource APIs for Java/JNDI
I A combination of Oracle XML DB Resource Views API and Oracle XML DB
Resource API for PL/SQL
I Internet protocols (HTTP/WebDAV and FTP) and Oracle XML DB Protocol
Server
Table 133 lists common Oracle XML DB Repository operations and describes how
these operations can be accomplished using each of the three methods. The table
shows functionality common to three methods. Note that not all the methods are
equally suited to a particular set of tasks.
See Also:
I Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
I Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
I Chapter 17, "Oracle XML DB Resource API for Java"
I Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
I Oracle9i XML API Reference - XDK and Oracle XML DB
Table 133 Accessing Oracle XML DB Repository: API Options
Data Access
Operation
Query-Based Access: RESOURCE_VIEW
API
Path-Based Access: Resource API for
PL/SQL
Path-Based
Access:
Protocols
Creating a resource INSERT INTO PATH_VIEW VALUES (path, res, linkprop)
See also DBMS_XDB.CreateResource.
HTTP PUT;
FTP PUT
Updating contents of
a resource using path
name
UPDATE RESOURCE_VIEW SET resource =
updateXML(res, '/Resource/Contents', lob) WHERE
EQUALS_PATH(res, :path) > 0
HTTP PUT;
FTP PUT
Accessing Data Stored in Oracle XML DB Repository Resources
Oracle XML DB Foldering 13-15
Updating properties
of a resource by path
name
UPDATE RESOURCE_VIEW SET resource =
updateXML(res, '/Resource/propname', newval,
'/Resource/propname2', newval2, ) WHERE
EQUALS_PATH(res, :path) > 0
HTTP PROPPATCH;
FTP N/A
Updating the ACL of
a resource
UPDATE RESOURCE_VIEW SET resource =
updateXML(res, '/ Resource/ACL', XMLType) WHERE
EQUALS_PATH(res, :path) > 0
N/A
Unlinking a resource,
deleting it if it is the
last link
DELETE FROM RESOURCE_VIEW WHERE
EQUALS_PATH(res, :path) > 0
HTTP DELETE; FTP
DELETE
Forcibly removing all
links to a resource
DELETE FROM PATH_VIEW WHERE
extractValue(res,display_name) = My resource;
N/A
FTP: quote
rm_rf<resource>
Moving a resource or
folder
UPDATE PATH_VIEW SET path = newpath WHERE
EQUALS_PATH(res, :path) > 0
WebDAV MOVE;
FTP RENAME
Copying a resource or
folder
INSERT INTO PATH_VIEW SELECT::newpath,
resource, link FROM PATH_VIEW WHERE
EQUALS_PATH(res,:oldpath)> 0
WebDav COPY;
FTP N/A
Creating a link to an
existing resource
Call dbms_xdb.Link(srcpath IN VARCHAR2, linkfolder IN
VARCHAR2, linkname IN VARCHAR2);
N/A
Getting binary/text
representation of
resource contents by
path name
SELECT GET_CONTENTS(resource) FROM
RESOURCE_VIEW p WHERE EQUALS_PATH(res,
:path) > 0
HTTP GET;
FTP GET
Getting XMLType
representation of
resource contents by
path name
SELECT extract(res, '/Resource/Contents/*') FROM
RESOURCE_VIEW p WHERE
EQUALS_PATH(Res, :path) > 0
N/A
Getting resource
properties by path
name
SELECT extractValue(res, '/Resource/XXX') FROM
RESOURCE_VIEW WHERE EQUALS_PATH(res,:path)
> 0
WebDAVPROPFIND
(depth = 0);
FTP N/A
Listing a directory SELECT * FROM PATH_VIEW WHERE
UNDER_PATH(res, :path, 1) > 0
WebDAV PROPFIND
(depth=1);
FTP LS
Table 133 Accessing Oracle XML DB Repository: API Options (Cont.)
Data Access
Operation
Query-Based Access: RESOURCE_VIEW
API
Path-Based Access: Resource API for
PL/SQL
Path-Based
Access:
Protocols
Managing and Controlling Access to Resources
13-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Managing and Controlling Access to Resources
You can set access control privileges on Oracle XML DB folders and resources.
Creating a folder ICall dbms_xdb.createFolder(VARCHAR2) WebDAVMKCOL;
FTP MKDIR
Unlinking a folder DELETE FROMPATH_VIEWWHERE
EQUALS_PATH(res, :path) > 0
HTTP DELETE;FTP
RMDIR
Forcibly deleting a
folder and all links to
it
Call dbms_xdb.deleteFolder(VARCHAR2) N/A
FTP: quote rm_rf
<folder>
Getting a resource
with a row lock
SELECT FROM RESOURCE_VIEW FOR UPDATE
;
N/A
Putting a WebDAV
lock on the resource
DBMS_XDB.lock(lock_type INTEGER); WebDAV LOCK;
FTP: QUOTE LOCK
Removing a WebDAV
lock
DBMS_XDB.unlock(path VARCHAR2); WebDAV UNLOCK;
QUOTE UNLOCK
Committing changes COMMIT; Automatically
commits at the end of
each request
Rollback changes ROLLBACK; N/A
See Also:
I Chapter 18, "Oracle XML DB Resource Security" for more detail
on using access control on Oracle XML DB folders
I Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
I Oracle9i XML API Reference - XDK and Oracle XML DB the
chapters on DBMS_XDB
Table 133 Accessing Oracle XML DB Repository: API Options (Cont.)
Data Access
Operation
Query-Based Access: RESOURCE_VIEW
API
Path-Based Access: Resource API for
PL/SQL
Path-Based
Access:
Protocols
Extending Resource Metadata Properties
Oracle XML DB Foldering 13-17
Extending Resource Metadata Properties
Oracle XML DB resources are described by XML schema, XDBResource.xsd. This
XML schema is described in Appendix G, "Example Setup scripts. Oracle XML DB -
Supplied XML Schemas". XDBResource.xsd declares a xed set of metadata
properties such as the Owner, CreationDate, and so on. You can specify values
for these metadata attributes while creating or updating resources.
You have two options for storing proprietary (custom) tags as extra metadata with
resources, that is metadata properties that are not dened by the Resource XML
schema:
I Option 1: Storing extra metadata as a CLOB (ResExtra element). The default
schema has a top-level any element (declared with maxOccurs=
"unbounded"), thus allowing any valid XML data as part of the resource
document, and gets stored in the RESEXTRA CLOB column:
<Resource xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"
<Owner>SCOTT</Owner>
... <!-- other system defined metadata -->
<!-- User Metadata (appearing within different namespace) -->
<ResExtra>
<myCustomAttrs xmlns="http://www.example.com/customattr">
<attr1>value1</attr1>
<attr2>value2</attr2>
</myCustomAttrs>
</ResExtra
<!-- contents of the resource>
<Contents>
...
</Contents>
</Resource>
Though this approach works well for ad-hoc extensions to the resource
metadata, the queryability and updatability of the user metadata is impacted
because the user metadata is stored in a CLOB.
I Option 2: Extending the Resource XML Schema. You can extend the resource
XML schema using the techniques specied by the XML schema specications,
that is, you can register a new XML schema that extends the ResourceType
Note: The XML representing user level metadata must be within a
namespace other than that XDBResource namespace.
Frequently Asked Questions (FAQs): XML DB Repository
13-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
complexType. This triggers the creation of object subtypes under the
XDB$RESOURCE_T object type, thereby adding new columns to the
XDB$RESOURCE table:
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xdbres="http://xmlns.oracle.com/xdb/XDBResource.xsd"
<complexType name="myCustomResourceType>
<complexContent>
<extension base="xdbres:ResourceType>
<element name="custom-attr1" type="string">
...
</extension>
</complexContent>
</complexType>
</schema>
Frequently Asked Questions (FAQs): XML DB Repository
Why Does XML Repository Hierarchical Index Not Work?
In XML DB Release 2 (9.2) the following query worked using the hierarchical index:
SELECT XDBURITYPE(ANY_PATH).GETXML()
FROM RESOURCE_VIEW
WHERE CONTAINS(RES,'MYXML') >0;
But this does not work with the latest release. I get the error column not indexed.
How should I use the hierarchical index to search the contents of documents in the
XML Repository? In one place the documentation describes a hierarchical index that
indexes path names but does not mention what type of index this is and when
mentioning the DBMS_XDBT package, it describes a ConText index on the Oracle
XML DB Repository hierarchy that sounds similar?
Answer: It appears that you have not created the Context index on the Repository.
Note that Contains() needs the Context index for its evaluation. You can create
the Context index on xdb$resource by:
a. Using DBMS_XDBT (dbmsxdbt.sql in rdbms/admin) package or
b. Create a Context index explicitly as follows:
CREATE INDEX xdb.ctxi ON xdb.xdb$resource x (value(x))
indextype is ctxsys.context;
Frequently Asked Questions (FAQs): XML DB Repository
Oracle XML DB Foldering 13-19
(a) is the preferred solution because it takes into account the binary contents in the
Repository and lters it appropriately. Solution (b) will only index the XML and text
content in the Repository.
There are two different indexes on the xdb$resource table:
I Hierarchical I ndex. This is always present. The rebuild hierarchical index
procedure is for rebuilding this index.
I Context index is an optional index, that is, your DBA can create this index if
needed. You will need this index to perform Contains() queries.
Frequently Asked Questions (FAQs): XML DB Repository
13-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Versioning 14-1
14
Oracle XML DB Versioning
This chapter describes how to create and manage versions of Oracle XML DB
resources. It contains the following sections:
I Introducing Oracle XML DB Versioning
I Creating a Version-Controlled Resource (VCR)
I Access Control and Security of VCR
I Frequently Asked Questions: Oracle XML DB Versioning
Introducing Oracle XML DB Versioning
14-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB Versioning
Oracle XML DB versioning provides a way to create and manage different versions
of a resource in Oracle XML DB. In previous releases of Oracle9i database, after a
resource (table, column,...) is updated, its previous contents and properties are lost.
Oracle XML DB versioning prevents this loss by storing a version of the resource in
the database to keep the old resource contents and properties when an update is
issued.
Oracle XML DB provides a PLSQL package, DBMS_XDB_VERSION to put a resource
under version-control and retrieve different versions of the resource.
Oracle XML DB Versioning Features
Oracle XML DB versioning helps keep track of all changes on version-controlled
Oracle XML DB resources (VCR). The following sections discuss these features in
detail. Oracle XML DB versioning features include the following:
I Version control on a resource. You have the option to turn on or off version
control on an Oracle XML DB resource. See "Creating a Version-Controlled
Resource (VCR)".
I Updating process of a version-controlled resource. When Oracle XML DB
updates a version-controlled resource, it also creates a new version of the
resource, and this version will not be deleted from the database when the
version-controlled resource is deleted by you. See "Updating a
Version-Controlled Resource (VCR)".
I Loading a version-controlled resource is similar to loading any other regular
resourcein Oracle XML DB using the path name. See "Creating a
Version-Controlled Resource (VCR)".
I Loadinga versionof theresource. To load a version of a resource, you must rst
nd the resource object id of the version and then load the version using that id.
The resource object id can be found from the resource version history or from
the version-controlled resource itself. See "Oracle XML DB Resource ID and
Path Name".
Note: In this release, Oracle XML DB versioning supports version
control for Oracle XML DB resources. It does not support version
control for user-dened tables or data in an Oracle9i database.
Introducing Oracle XML DB Versioning
Oracle XML DB Versioning 14-3
Oracle XML DB Versioning Terms Used in This Chapter
Table 141 lists the Oracle XML DB versioning terms used in this chapter.
Oracle XML DB Resource ID and Path Name
Oracle XML DB resource ID is a unique system-generated ID for an Oracle XML DB
resource. Here Resource ID helps identify resources that do not have path names.
For example, version resource is a system-generated resources and does not have a
path name. The function GetResourceByResId() can be used to retrieve
resources given the resource object ID.
Example 141 DBMS_XDB_VERSION. GetResourceByResId(): First version ID is
Returned When Resourcehome/index.html is makeversioned
declare
resid DBMS_XDB_VERSION.RESID_TYPE;
res XMLType;
begin
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Table 141 Oracle XML DB Versioning Terms
Oracle XML DB
Versioning Term Description
Version control When a record or history of all changes to an Oracle XML DB resource is stored
and managed, the resource is said to be put under version control.
Versionable resource Versionable resource is an Oracle XML DB resource that can be put under version
control.
Version-controlled
resource (VCR).
Version-controlled resource is an Oracle XML DB resource that is put under
version control. Here, a VCR is a reference to a version Oracle XML DB resource. It
is not physically stored in the database.
Version resource. Version resource is a version of the Oracle XML DB resource that is put under
version control. Version resource is a read-only Oracle XML DB resource. It cannot
be updated or deleted. However, the version resource will be removed from the
system when the version history is deleted from the system.
Checked-out resource. It is an Oracle XML DB resource created when version-controlled resource is
checked out.
Checkout, checkin, and
uncheckout.
These are operations for updating Oracle XML DB resources. Version-controlled
resources must be checked out before they are changed. Use the checkin operation
to make the change permanent. Use uncheckout to void the change.
Creating a Version-Controlled Resource (VCR)
14-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
resid := DBMS_XDB_VERSION.MakeVersioned(/home/SCOTT/versample.html);
-- Obtain the resource
res := DBMS_XDB_VERSION.GetResoureceByResId(resid);
Creating a Version-Controlled Resource (VCR)
Oracle XML DB does not automatically keep a history of updates since not all
Oracle XML DB resources need this. You must send a request to Oracle XML DB to
put an Oracle XML DB resource under version control. In this release, all Oracle
XML DB resources are versionable resources except for the following:
I Folders (directories or collections)
I ACL
When a Version-Controlled Resource (VCR) is created the rst version resource of
the VCR is created, and the VCR is a reference to the newly-created version.
See "Version Resource or VCR Version" on page 14-4.
Example 142 DBMS_XDB_VERSION.makeVersioned(): Creating a Version-Controlled
Resource (VCR)
Resource home/SCOTT/versample.html is turned into a version-controlled
resource.
declare
resid DBMS_XDB_VERSION.RESID_TYPE;
begin
resid := DBMS_XDB_VERSION.MakeVersioned(/home/SCOTT/versample.html);
end;
/
MakeVersioned() returns the resource ID of the very rst version of the
version-controlled resource. This version is represented by a resource ID, which is
discussed in "Resource ID of a New Version" on page 14-5.
MakeVersioned() is not an auto-commit SQL operation. You have to commit the
operation.
Version Resource or VCR Version
Oracle XML DB does not provide path names for version resources. However, it
does provide a version resource ID. Version resources are read-only resources.
The version ID is returned by a couple of methods in package
DBMS_XDB_VERSION, that are described in the following sections.
Creating a Version-Controlled Resource (VCR)
Oracle XML DB Versioning 14-5
Resource ID of a New Version
When a VCR is checked in, a new version resource is created, and its resource ID is
returned to the you. Because the VCR is just a reference to this new version
resource, the resource ID of the version can also be found by calling method
DBMS_XDB.getResourceID() whose input is the VCR path name.
Example 143 Retrieving the Resource ID of the New Version After Check In
The following example shows how to get the resource ID of the new version after
checking in /home/index.html:
-- Declare a variable for resource id
declare
resid DBMS_XDB_VERSION.RESID_TYPE;
res XMLType;
begin
-- Get the id as user checks in.
resid := DBMS_XDB_VERSION.checkin(/home/SCOTT/versample.html);
-- Obtain the resource
res := DBMS_XDB_VERSION.GetResourceByResId(resid);
end;
/
Example 144 Oracle XML DB: Creating and Updating a Version-Controlled Resource
(VCR)
-- Variable definitions.
declare
resid1 DBMS_XDB_VERSION.RESID_TYPE;
resid2 DBMS_XDB_VERSION.RESID_TYPE;
begin
-- Put a resource under version control.
resid1 := DBMS_XDB_VERSION.MakeVersioned(/home/SCOTT/versample.html);
-- Checkout to update contents of the VCR
DBMS_XDB_VERSION.Checkout(/home/SCOTT/versample.html);
-- Use resource_view to update versample.html
update resource_view
set res = sys.xmltype.createxml(
<Resource xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/XDBResource.xsd
Creating a Version-Controlled Resource (VCR)
14-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
http://xmlns.oracle.com/xdb/XDBResource.xsd">
<Author>Jane Doe</Author>
<DisplayName>versample</DisplayName>
<Comment>Has this got updated or not ?? </Comment>
<Language>en</Language>
<CharacterSet>ASCII</CharacterSet>
<ContentType>text/plain</ContentType>
</Resource>)
where any_path = /home/SCOTT/versample.html;
-- Checkin the change
resid2 := DBMS_XDB_VERSION.Checkin(/home/SCOTT/versample.html);
end;
/
-- At this point, you can download the first version with the resource object
ID,
-- resid1 and download the second version with resid2.
-- Checkout to delete the VCR
DBMS_XDB_VERSION.Checkout(/home/SCOTT/versample.html);
-- Delete the VCR
delete from resource_view where any_path = /home/SCOTT/versample.html;
-- Once the delete above is done, any reference
-- to the resource (that is, checkin, checkout,and so on, results in
-- ORA-31001: Invalid resource handle or path name "/home/SCOTT/versample.html"
Accessing a Version-Controlled Resource (VCR)
VCR also has a path name as any regular resource. Accessing a VCR is the same as
accessing any other resources in Oracle XML DB.
Updating a Version-Controlled Resource (VCR)
The operations on regular Oracle XML DB resources do not require the VCR to be
checked-out. Updating a VCR requires more steps than for a regular Oracle XML
DB resource:
Before updating the contents and properties of a VCR, check out the resource. The
resource must be checked in to make the update permanent. All of these operations
are not auto-commit SQL operations. You must explicitly commit the SQL
transaction. Here are the steps to update a VCR:
Creating a Version-Controlled Resource (VCR)
Oracle XML DB Versioning 14-7
1. Checkout a resource. To checkout a resource, the path name of the resource
must be passed to Oracle XML DB.
2. Update the resource. You can update either the contents or the properties of the
resource. These features are already supported by Oracle XML DB. A new
version of a resource is not created until the resource is checked in, so an update
or deletion is not permanent until after a checkin request for the resource is
done.
3. Checkin or uncheckout a resource. When a VCR is checked in, a new version is
created, and the VCR has the same contents and properties as the new version.
When a VCR is unchecked out, the VCR is unchanged. That is, it will have the
same contents and properties with the old version. To checkin or uncheckout a
resource, the path name of the resource must be passed to Oracle XML DB. If
the path name has been updated since checkout, the new path name must be
used. It is illegal to use the old path name.
Checkout
In Oracle9i Release 2 (9.2), the VCR checkout operation is executed by calling
DBMS_XDB_VERSION.CheckOut(). If you want to commit an update of a
resource, it is a good idea to commit after checkout. If you do not commit right after
checking out, you may have to rollback your transaction at a later point, and the
update is lost.
Example 145 VCR Checkout
For example:
-- Resource /home/SCOTT/versample.html is checked out.
DBMS_XDB_VERSION.CheckOut(/home/SCOTT/versample.html);
Checkin
InOracle9i Release 2 (9.2), the VCR checkin operation is executed by calling
DBMS_XDB_VERSION.CheckIn(). Checkin takes the path name of a resource. This
path name does not have to be the same as the path name that was passed to
checkout, but the checkin and checkout path names must be of the same resource.
Example 146 VCR Checkin
For example:
-- Resource /home/SCOTT/versample.html is checked in.
declare
Access Control and Security of VCR
14-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
resid DBMS_XDB_VERSION.RESID_TYPE;
begin
resid := DBMS_XDB_VERSION.CheckIn(/home/SCOTT/versample.html);
end;
/
Uncheckout
InOracle9i Release 2 (9.2), uncheckout is executed by calling
DBMS_XDB_VERSION.UncheckOut(). This path name does not have to be the
same as the path name that was passed to checkout, but the checkin and checkout
path names must be of the same resource.
Example 147 VCR Uncheckout
For example:
-- Resource /home/SCOTT/versample.html is unchecked out.
declare
resid DBMS_XDB_VERSION.RESID_TYPE;
begin
resid := DBMS_XDB_VERSION.UncheckOut(/home/SCOTT/versample.html);
end;
/
Update Contents and Properties
After checking out a VCR, all Oracle XML DB user interfaces for updating contents
and properties of a regular resource can be applied to a VCR.
Access Control and Security of VCR
Access control on VCR and version resource is the same as for a regular resource.
Whenever you request access to these resources, ACL is checked.
Version Resource
When a regular resource is makeversioned, the rst version resource is created,
and the ACL of this rst version is the same as the ACL of the original resource.
When a checked-out resource is checked in, a new version is created, and the ACL
See Also: Chapter 15, "RESOURCE_VIEW and PATH_VIEW" for
details on updating an Oracle XML DB resource.
See Also: Chapter 18, "Oracle XML DB Resource Security"
Access Control and Security of VCR
Oracle XML DB Versioning 14-9
of this new version is exactly the same as the ACL of the checked-out resource.
After version resource is created, its ACL cannot be changed and is used the same
way as the ACL of a regular resource.
VCRs ACL is the Same as the First Version
When a VCR is created by makeversioned, the ACL of the VCR is the same as the
ACL of the rst version of the resource. When a resource is checked in, a new
version is created, and the VCR will have the same contents and properties
including ACL property with this new version.
Table 142 describes the subprograms in DBMS_XDB_VERSION.
Access Control and Security of VCR
14-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Table 142 DBMS_XDB_VERSION Functions and Procedures
DBMS_XDB_VERSION
Function/Procedure Description
FUNCTION MakeVersioned
MakeVersioned(pathname
VARCHAR2) RETURN
dbms_xdb.resid_type;
Turns a regular resource whose path name is given into a version controlled
resource. If two or more path names are bound with the same resource, a copy
of the resource will be created, and the given path name will be bound with
the newly-created copy. This new resource is then put under version control.
All other path names continue to refer to the original resource.
pathname - the path name of the resource to be put under version control.
return - This function returns the resource ID of the rst version (root) of the
VCR. This is not an auto-commit SQL operation. It is legal to call
MakeVersioned for VCR, and neither exception nor warning is raised. It is
illegal to makeversioned for folder, version resource, and ACL. An exception is
raised if the resource doesnt exist.
PROCEDURE Checkout
Checkout(pathname
VARCHAR2);
Checks out a VCR before updating or deleting it.
pathname - the path name of the VCR to be checked out. This is not an
auto-commit SQL operation. Two users of the same workspace cannot checkout
the same VCR at the same time. If this happens, one user must rollback. As a
result, it is a good idea for you to commit the checkout operation before
updating a resource. That way, you do not loose the update when rolling back
the transaction. An exception is raised when:
I the given resource is not a VCR,
I the VCR is already checked out
I the resource doesnt exist
FUNCTION Checkin
Checkin(pathname
VARCHAR2) RETURN
dbms_xdb.resid_type;
Checks in a checked-out VCR.
pathname - the path name of the checked-out resource.
return - the resource id of the newly-created version.
This is not an auto-commit SQL operation. Checkin does not have to take the
same path name that was passed to checkout operation. However, the checkin
path name and the checkout path name must be of the same resource for the
operations to function correctly.
If the resource has been renamed, the new name must be used to checkin
because the old name is either invalid or bound with a different resource at the
time being. Exception is raised if the path name does not exist. If the path name
has been changed, the new path name must be used to checkin the resource.
Access Control and Security of VCR
Oracle XML DB Versioning 14-11
FUNCTION Uncheckout
Uncheckout(pathname
VARCHAR2) RETURN
dbms_xdb.resid_type;
Checks in a checked-out resource.
pathname - the path name of the checked-out resource.
return - the resource id of the version before the resource is checked out. This is
not an auto-commit SQL operation. UncheckOut does not have to take the same
path name that was passed to checkout operation. However, the uncheckout
path name and the checkout path name must be of the same resource for the
operations to function correctly. If the resource has been renamed, the new
name must be used to uncheckout because the old name is either invalid or
bound with a different resource at the time being. An exception is raised if the
path name does not exist. If the path name has been changed, the new path
name must be used to checkin the resource.
FUNCTION GetRoot
GetFirst(vh_id
dbms_xdb.resid_type)
RETURN
dbms_xdb.resid_type;
Given the version history, gets the root of all versions.
vh_id - the resid of the version history.
return - rst version resource id. An exception is raised if the vh_id is illegal.
FUNCTION GetPredecessors
GetPredecessors(pathname
VARCHAR2) RETURN
resid_list_type;
GetPredsByResId(resid
dbms_xdb.resid_type)
RETURN resid_list_type;
Given a version resource or a VCR, gets the predecessors of the resource by
pathname, the path name of the resource.
return - list of predecessors.
Getting predecessors by resid is more efcient than by pathname. An
exception is raised if the resid or pathname is illegal.
Given a version resource or a VCR, gets the predecessors of the resource by
resid (resource id)
Note: The list of predecessors only contains one element (immediate parent),
since Oracle does not support branching in this release. The following function
GetSuccessors also returns only one element
FUNCTION GetSuccessors
GetSuccessors(pathname
VARCHAR2) RETURN
resid_list_type;
GetSuccsByResId(resid
dbms_xdb.resid_type)
RETURN resid_list_type;
Given a version resource or a VCR, gets the successors of the resource by
pathname, the path name of the resource.
return - list of predecessors. Getting successors by resid is more efcient than by
path name. An exception is raised if the resid or pathname is illegal.
Given a version resource or a VCR, get the successors of the resource by resid
(resource id).
FUNCTION GetResourceByResId
GetResourceByResId(resid
dbms_xdb.resid_type)
RETURN XMLType;
Given a resource object ID, gets the resource as an XMLType.
resid - the resource object ID
return - the resource as an XMLType
Table 142 DBMS_XDB_VERSION Functions and Procedures (Cont.)
DBMS_XDB_VERSION
Function/Procedure Description
Frequently Asked Questions: Oracle XML DB Versioning
14-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Frequently Asked Questions: Oracle XML DB Versioning
Can I Switch a VCR to a Non-VCR?
Answer: No.
How Do I Access the Old Copy of a VCR After Updating It?
Answer: The old copy is the version resource of the last checked-in:
I If you have the version ID or path name, you can load it using that ID.
I If you dont have its ID, you can call getPredecessors() to get the ID.
Can We Use Version Control for Data Other Than Oracle XML DB Data?
Answer: Only Oracle XML DB resources can be put under version control in this
release.
RESOURCE_VIEW and PATH_VIEW 15-1
15
RESOURCE_VIEW and PATH_VIEW
This chapter describes the SQL-based mechanisms, RESOURCE_VIEW and
PATH_VIEW, used to access Oracle XML DB Repository data. It discusses the SQL
operators UNDER_PATH and EQUALS_PATH used to query resources based on their
path names and the SQL operators PATH and DEPTH that return the resource path
names and depth.
This chapter contains the following sections:
I Oracle XML DB RESOURCE_VIEW and PATH_VIEW
I Resource_View, Path_View API
I UNDER_PATH
I EQUALS_PATH
I PATH
I DEPTH
I Using the Resource View and Path View API
I Working with Multiple Oracle XML DB Resources Simultaneously
I Tuning XML DB to Obtain Faster Queries
I Searching for Resources Using Oracle Text
Oracle XML DB RESOURCE_VIEW and PATH_VIEW
15-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB RESOURCE_VIEW and PATH_VIEW
Figure 151 shows howOracle XML DB RESOURCE_VIEW and PATH_VIEW provide
a mechanism for using SQL to access data stored in Oracle XML DB Repository.
Data stored in Oracle XML DB Repository through protocols like FTP, WebDAV, or
programming API, can be accessed in SQL using RESOURCE_VIEWs and
PATH_VIEWs, and vice versa.
RESOURCE_VIEW and PATH_VIEW together, along with PL/SQL package,
DBMS_XDB, provide all query-based access to Oracle XML DB and DML
functionality that is available through the programming API.
The base table for RESOURCE_VIEW is XDB.XDB$RESOURCE and should only be
accessed through RESOURCE_VIEW or the DBMS_XDB API.
See Also: Chapter 26, "Oracle XML DB Basic Demo", "6.0 XML
DB Demo: Querying RESOURCE_VIEWS Using SQL" on
page 26-62.
Oracle XML DB RESOURCE_VIEW and PATH_VIEW
RESOURCE_VIEW and PATH_VIEW 15-3
Figure 151 Accessing Repository Resources Using RESOURCE_VIEW and
PATH_VIEW
RESOURCE_VIEW Denition and Structure
The RESOURCE_VIEW contains one row for each resource in the Repository. The
following describes its structure:
Column Datatype Description
------ -------- -------------------------------------------------------
RES XMLTYPE A resource in Oracle XML Repository
ANY_PATH VARCHAR2 A path that can be used to access the resource in the
Repository
See Also: Appendix G, "Example Setup scripts. Oracle XML DB -
Supplied XML Schemas"
Oracle XML DB
Resource Table
Content Properties
Repository
Access through:
JNDI
WebDav
FTP
DBMS_XDB
Oracle XML DB
RESOURCE
VIEW
PATH
VIEW
SQL
Queries
SQL
Queries
Path-based
Access
Query-based
Access
Oracle XML DB RESOURCE_VIEW and PATH_VIEW
15-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
PATH_VIEW Denition and Structure
The PATH_VIEW contains one row for each unique path to access a resource in the
Repository. The following describes its structure:
Column Datatype Description
------ -------- -----------------------------
PATH VARCHAR2 Path name of a resource
RES XMLTYPE The resource referred by PATH
LINK XMLTYPE Link property
Figure 152 illustrates the structure of Resource and PATH_VIEWs.
The path in the RESOURCE_VIEW is an arbitrary one and one of the accessible paths
that can be used to access that resource. Oracle XML DB provides operator
UNDER_PATH that enables applications to search for resources contained
(recursively) within a particular folder, get the resource depth, and so on. Each row
in the PATH_VIEW and RESOURCE_VIEW columns is of XMLType. DML on
Oracle XML DB Repository views can be used to insert, rename, delete, and update
resource properties and contents. Programmatic APIs must be used for some
operations, such as creating links to existing resources.
Figure 152 RESOURCE_VIEW and PATH_VIEW Structure
See Also: Appendix G, "Example Setup scripts. Oracle XML DB -
Supplied XML Schemas"
Note: Each resource may have multiple paths called links.
RESOURCE_VIEW Columns
Resource as
an XMLType
Path
PATH_VIEW Columns
Path Resource as
an XMLType
Link as
XMLType
Oracle XML DB RESOURCE_VIEW and PATH_VIEW
RESOURCE_VIEW and PATH_VIEW 15-5
Understanding the Difference Between RESOURCE_VIEW and PATH_VIEW
The major difference between the RESOURCE_VIEW and PATH_VIEW is:
I PATH_VIEW displays all the path names to a particular resource whereas
RESOURCE_VIEW displays one of the possible path names to the resource
I PATH_VIEW also displays the properties of the link
Figure 153 illustrates the difference between Resource and PATH_VIEW.
Since many internet applications only need one URL to access a resource,
RESOURCE_VIEW is widely applicable.
PATH_VIEW contains the link properties as well as resource properties, whereas the
RESOURCE_VIEW only contains resource properties.
The RESOURCE_VIEW benet is generally optimization, if the database knows that
only one path is needed, the index does not have to do as much work to determine
all the possible paths.
Note: When using the RESOURCE_VIEW, if you are specifying a
path with the UNDER_PATH or EQUALS_PATH operators, they will
nd the resource regardless of whether or not that path is the
arbitrary one chosen to normally display with that resource using
RESOURCE_VIEW.
Oracle XML DB RESOURCE_VIEW and PATH_VIEW
15-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 153 RESOURCE_VIEW and PATH_VIEW Explained
Operations You Can Perform Using UNDER_PATH and EQUALS_PATH
You can perform the following operations using UNDER_PATH and EQUALS_PATH:
I Given a path name:
Get a resource
List the directory given by the path name
Create a resource
Delete a resource
Update a resource
I Given a condition, containing UNDER_PATH operator or other SQL operators:
Update resources
Delete resources
Get resources
po_westcoast po_eastcoast
/role /corp
With PATH_VIEW, to acces the target
resource node;You can create a link.
This provides two access paths or
to the target node, for faster access.
R1 R2
In a typical tree the
RESOURCE_VIEW has only
one path
/home
R1
R2
Target Resource
RESOURCE_VIEW Example:
select path(1) from resource_view where under_path(res, '/sys',1);
displays one path to the resource:
/home/corp/po_westcoast
PATH_VIEW Example:
select path from path_view;
displays all pathnames to the resource:
/home/corp/po_westcoast
/home/role/po_eastcoast
UNDER_PATH
RESOURCE_VIEW and PATH_VIEW 15-7
See the "Using the Resource View and Path View API" and EQUALS_PATH.
Resource_View, Path_View API
This section describes the RESOURCE_VIEW and PATH_VIEW operators:
UNDER_PATH
The UNDER_PATH operator uses the Oracle XML DB Repository hierarchical index
to return the paths under a particular path. The hierarchical index is designed to
speed access walking down a path name (the normal usage).
If the other parts of the query predicate are very selective, however, a functional
implementation of UNDER_PATH can be chosen that walks back up the Repository.
This can be more efcient, since a much smaller number of links may need to be
traversed. Figure 154 shows the UNDER_PATH syntax.
Figure 154 UNDER_PATH Syntax
Table 151 describes the UNDER_PATH syntax.
Table 151 RESOURCE_VIEW and PATH_VIEW API Syntax: UNDER_PATH
Syntax Description
INTEGER UNDER_PATH(resource_column,
pathname);
Determines if a resource is under a specied path.
Parameters:
I resource_column - The column name or column alias of the
'resource' column in the path_view or resource_view.
I pathname - The path name to resolve.
UNDER_PATH ( column
, levels
, path_string
, correlation_integer
)
UNDER_PATH
15-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
INTEGER UNDER_PATH(resource_column,
depth,
pathname);
Determines if a resource is under a specied path, with a depth
argument to restrict the number of levels to search.
Parameters:
I resource_column - The column name or column alias of the
'resource' column in the path_view or resource_view.
I depth - The maximum depth to search; a depth of less than 0 is
treated as 0.
I pathname - The path name to resolve.
INTEGER UNDER_PATH(resource_column,
pathname,
correlation)
Determines if a resource is under a specied path, with a correlation
argument for ancillary operators.
Parameters:
I resource_column - The column name or column alias of the
'resource' column in the path_view or resource_view.
I pathname - The path name to resolve.
I correlation - An integer that can be used to correlate the
UNDER_PATH operator (a primary operator) with ancillary
operators (PATH and DEPTH).
INTEGER UNDER_PATH(resource_column,
depth,
pathname,
correlation)
Determines if a resource is under a specied path with a depth
argument to restrict the number of levels to search, and with a
correlation argument for ancillary operators.
Parameters:
I resource_column - The column name or column alias of the
'resource' column in the path_view or resource_view.
I depth - The maximum depth to search; a depth of less than 0 is
treated as 0.
I pathname - The path name to resolve.
I correlation - An integer that can be used to correlate the
UNDER_PATH operator (a primary operator) with ancillary
operators (PATH and DEPTH).
Note that only one of the accessible paths to the resource needs to be
under the path argument for a resource to be returned.
Table 151 RESOURCE_VIEW and PATH_VIEW API Syntax: UNDER_PATH (Cont.)
Syntax Description
PATH
RESOURCE_VIEW and PATH_VIEW 15-9
EQUALS_PATH
The EQUALS_PATH operator is used to nd the resource with the specied path
name. It is functionally equivalent to UNDER_PATH with a depth restriction of zero.
The EQUALS_PATH syntax is describe here and in Figure 155.
EQUALS_PATH INTEGER EQUALS_PATH( resource_column,pathname);
Figure 155 EQUALS_PATH Syntax
where:
I resource_column is the column name or column alias of the 'resource' column
in the path_view or resource_view.
I pathname is the path name to resolve.
PATH
PATH is an ancillary operator that returns the relative path name of the resource
under the specied pathname argument. Note that the path column in the
RESOURCE_VIEW always contains the absolute path of the resource. The PATH
syntax is:
PATH VARCHAR2 PATH( correlation);
where:
I correlation is an integer that can be used to correlate the UNDER_PATH
operator (a primary operator) with ancillary operators (PATH and DEPTH).
Here are some examples of a RESOURCE_VIEW that include resources specied by
paths:
'/a/b/c'
'/a/b/c/d'
Note: If a path is not under the specied pathname argument, a
NULL value is returned as the output of the current path.
EQUALS_PATH ( column , path_string
, correlation_integer
)
PATH
15-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
'/a/e/c'
'/a/e/c/d'
Example 151 Determining Paths Under the Specied Pathname Argument
SELECT path(1) FROM resource_view
WHERE UNDER_PATH(res, '/a/b', 1) = 1;
Returns the following:
PATH(1)
-------
c
c/d
2 rows returned
Example 152 Determining Paths Not Under the Specied Pathname Argument
SELECT path(1) FROM resource_view
WHERE UNDER_PATH(res, '/a/b', 1)!=1
Returns the following:
PATH(1)
-------
2 rows returned
Example 153 Determining Paths Using Multiple Correlations
SELECT ANY_PATH, path(1), path(2)
Note: For absolute paths use ANY_PATH as follows:
SELECT ANY_PATH
FROM resource_view
WHERE UNDER_PATH(res, '/a/b')=1;
This returns the following:
ANY_PATH
--------
/a/e/c
/a/e/c/d
2 rows returned
Using the Resource View and Path View API
RESOURCE_VIEW and PATH_VIEW 15-11
FROM resource_view
WHERE UNDER_PATH(res, '/a/b', 1) = 1 or UNDER_PATH(res, '/a/e', 2) = 1;
This returns the following:
ANY_PATH PATH(1) PATH(2)
----------------------------------------------------
/a/b/c c
/a/b/c/d c/d
/a/e/c c
/a/e/c/d c/d
4 rows returned
DEPTH
DEPTH is an ancillary operator that returns the folder depth of the resource under
the specied starting path.
DEPTH INTEGER DEPTH( correlation);
where:
correlation is an integer that can be used to correlate the UNDER_PATH operator
(a primary operator) with ancillary operators (PATH and DEPTH).
Using the Resource View and Path View API
The following RESOURCE_VIEW and PATH_VIEW examples use operators
UNDER_PATH, EQUALS_PATH, PATH, and DEPTH.
Accessing Paths and Repository Resources: Examples
The following examples illustrate how you can access paths, resources, and link
properties in the Repository:
Example 154 Using UNDER_PATH: Given a Path Name, List the Directory Given by
the Path Name from the RESOURCE_VIEW
select any_path from resource_view where any_path like /sys%;
Using the Resource View and Path View API
15-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 155 Using UNDER_PATH: Given a Path Name, Get a Resource From the
RESOURCE_VIEW
select any_path, extract(res, /display_name) from resource_view
where under_path(res, /sys) = 1;
Example 156 Using RESOURCE_VIEW: Given a Path, Get all Relative Path Names
for Resources up to Three Levels
select path(1) from resource_view
where under_path (res, 3, /sys,1)=1;
Example 157 Using UNDER_PATH: Given a Path Name, Get Path and Depth Under a
Specied Path from the PATH_VIEW
select path(1) PATH,depth(1) depth
from path_view
where under_path(RES, 3,'/sys',1)=1
Example 158 Given a Path Name, Get Paths and Link Properties from PATH_VIEW
select path, extract(link, '/LINK/Name/text()').getstringval(),
extract(link, '/LINK/ParentName/text()').getstringval(),
extract(link, '/LINK/ChildName/text()').getstringval(),
extract(res, '/Resource/DisplayName/text()').getstringval()
from path_view
where path LIKE /sys%;
Example 159 Using UNDER_PATH: Given a Path Name, Find all the Paths up to a
Certain Number of Levels, Including Links Under a Specied Path fromthe PATH_VIEW
select path(1) from path_view
where under_path(res, 3,/sys, 1) > 0 ;
Example 1510 Using EQUALS_PATH to Locate a Path
select any_path from resource_view
where equals_path(res, /sys) > 0;
Inserting Data into a Repository Resource: Examples
The following example illustrates how you can insert data into a resource:
Example 1511 Creating Resources: Inserting Data Into a Resource
insert into resource_view values(sys.xmltype.createxml('
Using the Resource View and Path View API
RESOURCE_VIEW and PATH_VIEW 15-13
<Resource xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/XDBResource.xsd
http://xmlns.oracle.com/xdb/XDBResource.xsd">
<Author>John Doe</Author>
<DisplayName>example</DisplayName>
<Comment>This resource was contrived for resource view demo</Comment>
<Language>en</Language>
<CharacterSet>ASCII</CharacterSet>
<ContentType>text/plain</ContentType>
</Resource>'), '/home/SCOTT');
Deleting Repository Resources: Examples
The following examples illustrate how you can delete resources or paths:
Example 1512 Deleting Resources
delete from resource_view where any_path = '/home/SCOTT/example
If only leaf resources are deleted, you can perform a delete using delete from
resource_view where....
Deleting Non-Empty Containers Recursively
If only leaf resources are deleted, you can delete them using "delete from
resource_view where...". For example, one way to delete leaf node
/public/test/doc.xml is as follows:
delete from resource_view where under_path(res, /public/test/doc.xml) = 1;
However, if you attempt to delete a non-empty container recursively, the following
rules apply:
I Delete on a non-empty container is not allowed
I The order of the paths returned from the where clause predicates is not
guaranteed
Therefore you should guarantee that a container is deleted only after its children
have been deleted.
Using the Resource View and Path View API
15-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example 1513 Recursively Deleting Paths
For example, to recursively delete paths under /public), you may want to try the
following:
delete from
(select 1 from resource_view
where UNDER_PATH(res, /public, 1) = 1
order by depth(1) desc);
Updating Repository Resources: Examples
The following examples illustrate how to update resources and paths:
Example 1514 Updating Resources
update resource_view set res = sys.xmltype.createxml('
<Resource xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/XDBResource.xsd
http://xmlns.oracle.com/xdb/XDBResource.xsd">
<Author>John Doe</Author>
<DisplayName>example</DisplayName>
<Comment>Has this got updated or not ? </Comment>
<Language>en</Language>
<CharacterSet>ASCII</CharacterSet>
<ContentType>text/plain</ContentType>
</Resource>')
where any_path = '/home/SCOTT/example';
Example 1515 Updating a Path in the PATH_VIEW
update path_view set path = '/home/XDB'
where path = '/home/SCOTT/example'
Working with Multiple Oracle XML DB Resources Simultaneously
RESOURCE_VIEW and PATH_VIEW 15-15
Working with Multiple Oracle XML DB Resources Simultaneously
Operations listed in Table 133, Chapter 13, "Oracle XML DB Foldering", typically
apply to only one resource at a time. To perform the same operation on multiple
Oracle XML DB resources, or to nd one or more Oracle XML DB resources that
meet a certain set of criteria, use RESOURCE_VIEW and PATH_VIEW in SQL.
For example, you can perform the following operations with these resource_view
and PATH_VIEW SQL clauses:
I Updating based on attributes
UPDATE RESOURCE_VIEW SET WHERE extractValue(resource, '/display_name') =
'My stuff'
I Finding recursively in a folder
SELECT FROM RESOURCE_VIEW WHERE UNDER_PATH(resource, '/sys')
I Copying a set of Oracle XML DB resources
INSERT INTO PATH_VIEW SELECT . FROM PATH_VIEW WHERE ...
Note: If you need to get all the resources under a directory, you
can use the LIKE operator, as shown in Example 154 on
page 15-11.
If you need to get the resources up to a certain number of levels, or
get the relative path, then use the UNDER_PATH operator, as shown
in Example 155 on page 15-12.
The query plan for Example 154 will be more optimal than that of
Example 155.
See Also: Chapter 13, "Oracle XML DB Foldering",Table 133,
"Accessing Oracle XML DB Repository: API Options" on page 13-14
for additional examples that use the RESOURCE_VIEW and
PATH_VIEW operators.
Tuning XML DB to Obtain Faster Queries
15-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Tuning XML DB to Obtain Faster Queries
XML DB uses the xdbconfig le for conguring the system and protocol
environment. In Release 2 (9.2.0.2) it includes an element
resource-view-cache-size parameter that denes the in-memory size of the
RESOURCE_VIEW cache. The default value is 1048576.
Some queries on RESOURCE_VIEW and PATH_VIEW can be sped up by tuning
resource-view-cache-size. In general, the bigger the cache size, the faster the
query. The default resource-view-cache-size is appropriate for most cases.
However you may want to enlarge your resource-view-cache-size element when
querying sizable RESOURCE_VIEWs.
Searching for Resources Using Oracle Text
The XDB$RESOURCE table in Oracle XML DB user schema stores in Oracle XML DB
the metadata and data corresponding to resources, such as les and folders. You can
search for resources containing a specic keyword by using the CONTAINS operator
in RESOURCE_VIEW or PATH_VIEW.
Example 1516 Find All Resources Containing Keywords "Oracle" and "Unix"
select path
from path_view
where contains(res, 'Oracle AND Unix') > 0;
Example 1517 Find All Resources Containing Keyword "Oracle" that are Also Under
a Specied Path.
select any_path
from resource_view
where contains(res, 'Oracle') > 0
and under_path(res, '/myDocuments') > 0;
To evaluate such queries, you must create a Context Index on the XDB$RESOURCE
table. Depending on the type of documents stored in Oracle XML DB, choose one of
the following options for creating your Context Index:
I I f Oracle XML DB contains only XML documents, that is, no binary data, a
regular Context Index can be created on the XDB$RESOURCE table.
See Also: Appendix A, "Installing and Conguring Oracle XML
DB"
Searching for Resources Using Oracle Text
RESOURCE_VIEW and PATH_VIEW 15-17
create index xdb$resource_ctx_i
on xdb.xdb$resource x (value(x))
indextype is ctxsys.context;
I I f OracleXML DB contains binary data, for example WORD documents, a user
lter is required to lter such documents prior to indexing. It is recommended
that you use the DBMS_XDBT package (dbmsxdbt.sql) to create and congure
the Context Index.
Rem Install the package - connected as SYS
SQL>@dbmsxdbt
Rem Create the preferences
SQL>exec dbms_xdbt.createPreferences;
Rem Create the index
SQL>exec dbms_xdbt.createIndex;
DBMS_XDBT package also includes procedures to sync and optimize the index. You
can use the configureAutoSync() procedure to congure automatic sync of the
index by using job queues.
See Also: Chapter 7, "Searching XML Data with Oracle Text",
"XMLType Indexing" on page 7-35.
See:
I Oracle9i XML API Reference - XDK and Oracle XML DB, the
chapter on DBMS_XDBT for information on installing and
using DBMS_XDBT.
I Appendix F, "Oracle XML DB XMLType API, PL/SQL and
Resource PL/SQL APIs: Quick Reference", DBMS_XDBT on
page F-27.
Searching for Resources Using Oracle Text
15-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Resource API for PL/SQL (DBMS_XDB) 16-1
16
Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)
This chapter describes the Oracle XML DB Resource API for PL/SQL (DBMS_XDB)
used for accessing and managing Oracle XML DB Repository resources and data
using PL/SQL. It includes methods for managing the resource security and Oracle
XML DB conguration.
It contains the following sections:
I Introducing Oracle XML DB Resource API for PL/SQL
I Overview of DBMS_XDB
I DBMS_XDB: Oracle XML DB Resource Management
I DBMS_XDB: Oracle XML DB ACL-Based Security Management
I DBMS_XDB: Oracle XML DB Conguration Management
I DBMS_XDB: Rebuilding Oracle XML DB Hierarchical Indexes
Introducing Oracle XML DB Resource API for PL/SQL
16-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB Resource API for PL/SQL
This chapter describes the Oracle XML DB Resource API for PL/SQL (PL/SQL
package DBMS_XDB). This is also known as the PL/SQL foldering API.
Oracle XML DB Repository is modeled on XML and provides a database le system
for any data. Oracle XML DB Repository maps path names (or URLs) onto database
objects of XMLType and provides management facilities for these objects.
DBMS_XDB package provides functions and procedures for accessing and managing
Oracle XML DB Repository using PL/SQL.
Overview of DBMS_XDB
The DBMS_XDB provides the PL/SQL application developer with an API that
manages:
I Oracle XML DB Resources
I Oracle XML DB ACL based Security
I Oracle XML DB Conguration
I Oracle XML DB Hierarchical Index Rebuild
DBMS_XDB: Oracle XML DB Resource Management
Table 161 lists the DBMS_XDB Oracle XML DB resource management methods.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Table 161 DBMS_XDB Resource Management Methods
DBMS_XDB Method Arguments, Return Values
Link Argument: (srcpath VARCHAR2, linkfolder VARCHAR2, linkname VARCHAR2)
Return value: N/A
LockResource Argument: (path IN VARCHAR2, depthzero IN BOOLEAN, shared IN boolean)
Return value: TRUE if successful.
GetLockToken Argument: (path IN VARCHAR2, locktoken OUT VARCHAR2)
Return value: N/A
UnlockResource Argument: (path IN VARCHAR2, deltoken IN VARCHAR2)
Return value: TRUE if successful.
DBMS_XDB: Oracle XML DB Resource Management
Oracle XML DB Resource API for PL/SQL (DBMS_XDB) 16-3
Using DBMS_XDB to Manage Resources, Calling Sequence
Figure 161 describes the calling sequence when using DBMS_XDB to manage
Repository resources:
1. When managing Repository resources the calling sequence diagram assumes
that the resources and folders already exist. If not, you need to create the
resources using createResource() or create folders using
createFolder()
createResource() takes resource data and the resource path as
parameters.
createFolder() takes the resource path as a parameter.
2. If the resource or folder does not need further processing or managing, they are
simply output.
3. If the resource or folder need further processing or managing you can apply
any or all of the following methods as listed in Table 161:
Link()
CreateResource FUNCTION CreateResource (path IN VARCHAR2, data IN VARCHAR2)
RETURN BOOLEAN; Creates a new resource with the given string as its contents.
FUNCTION CreateResource (path IN VARCHAR2, data IN SYS.XMLTYPE)
RETURN BOOLEAN; Creates a new resource with the given XMLType data as its
contents.
FUNCTION CreateResource (path IN VARCHAR2, datarow IN REF
SYS.XMLTYPE) RETURN BOOLEAN; Given a PREF to an existing XMLType row,
creates a resource whose contents point to that row. That row should not already
exist inside another resource.
FUNCTION CreateResource (path IN VARCHAR2, data IN CLOB) RETURN
BOOLEAN; Creates a resource with the given CLOB as its contents.
FUNCTION CreateResource (path IN VARCHAR2, data IN BFILE) RETURN
BOOLEAN; Creates a resource with the given BFILE as its contents.
CreateFolder Argument: (path IN VARCHAR2)
Return value: TRUE if successful.
DeleteResource Argument: (path IN VARCHAR2)
Return value: N/A
Table 161 DBMS_XDB Resource Management Methods (Cont.)
DBMS_XDB Method Arguments, Return Values
DBMS_XDB: Oracle XML DB Resource Management
16-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
LockResource()
GetLockToken()
UnlockResource()
DeleteResource()
See Example 161 for an examples of using DBMS_XDB to manage Repository
resources.
Figure 161 Using DBMS_XDB to Manage Resources: Calling Sequence
Example 161 Using DBMS_XDB to Manage Resources
DECLARE
retb boolean;
BEGIN
retb := dbms_xdb.createfolder(/public/mydocs);
commit;
END;
/
declare
bret boolean;
begin
bret :=
Available methods:
link()
lockResource()
getLockToken()
unlockResource()
deleteResource()
createResource() createFolder()
Resource Data Resource Path
DBMS_XDB: Oracle XML DB ACL-Based Security Management
Oracle XML DB Resource API for PL/SQL (DBMS_XDB) 16-5
dbms_xdb.createresource(/public/mydocs/emp_scott.xml,<emp_name>scott</emp_nam
e>);
commit;
end;
/
declare
bret boolean;
begin
bret :=
dbms_xdb.createresource(/public/mydocs/emp_david.xml,<emp_name>david</emp_nam
e>);
commit;
end;
/
call dbms_xdb.link(/public/mydocs/emp_scott.xml,/public/mydocs,
person_scott.xml);
call dbms_xdb.link(/public/mydocs/emp_david.xml,/public/mydocs,
person_david.xml);
commit;
call dbms_xdb.deleteresource(/public/mydocs/emp_scott.xml);
call dbms_xdb.deleteresource(/public/mydocs/person_scott.xml);
call dbms_xdb.deleteresource(/public/mydocs/emp_david.xml);
call dbms_xdb.deleteresource(/public/mydocs/person_david.xml);
call dbms_xdb.deleteresource(/public/mydocs);
commit;
DBMS_XDB: Oracle XML DB ACL-Based Security Management
Table 162 lists the DBMS_XDB Oracle XML DB ACL- based security management
methods. Because the arguments and return values for the methods are
self-explanatory, only a brief description of the methods is provided here.
Table 162 DBMS_XDB: Security Management Methods
DBMS_XDB Method Arguments, Return Values
getAclDocument Argument: (abspath VARCHAR2)
Return value: XMLType for the ACL document
DBMS_XDB: Oracle XML DB ACL-Based Security Management
16-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Using DBMS_XDB to Manage Security, Calling Sequence
Figure 162 describes the calling sequence when using DBMS_XDB to manage
security.
1. Each DBMS_XDB security management method take in a path (resource_path,
abspath, or acl_path).
2. You can then use any or all of the DBMS_XDB methods listed in Table 162 to
perform security management tasks:
getAclDocument()
ACLCheckPrivileges()
checkPrivileges()
getPrivileges()
changePrivileges()
setACL()
See Example 162 for an examples of using DBMS_XDB to manage Repository
resource security.
ACLCheckPrivileges Argument: (acl_path IN VARCHAR2, owner IN VARCHAR2,
privs IN XMLType)
Return value: Positive integer if privileges are granted.
checkPrivileges Argument: (res_path IN VARCHAR2, privs IN XMLType
Return value: Positive integer if privileges are granted.
getprivileges Argument: (res_path IN VARCHAR2)
Return value: XMLType instance of the <privilege> element.
changePrivileges Argument: (res_path IN VARCHAR2, ace IN XMLType)
Return value: Positive integer if ACL was successfully
modied.
setAcl Argument: (res_path IN VARCHAR2, acl_path IN
VARCHAR2). This sets the ACL of the resource at res_path to
the ACL located at acl_path.
Return value: N/A
Table 162 DBMS_XDB: Security Management Methods (Cont.)
DBMS_XDB Method Arguments, Return Values
DBMS_XDB: Oracle XML DB ACL-Based Security Management
Oracle XML DB Resource API for PL/SQL (DBMS_XDB) 16-7
Figure 162 Using DBMS_XDB to Manage Security: Calling Sequence
Example 162 Using DBMS_XDB to Manage ACL-Based Security
DECLARE
retb boolean;
BEGIN
retb := dbms_xdb.createfolder(/public/mydocs);
commit;
END;
/
declare
bret boolean;
begin
bret :=
dbms_xdb.createresource(/public/mydocs/emp_scott.xml,<emp_name>scott</emp_nam
e>);
commit;
end;
/
call dbms_xdb.setacl(/public/mydocs/emp_scott.xml,
/sys/acls/all_owner_acl.xml);
commit;
select dbms_xdb.getacldocument(/public/mydocs/emp_scott.xml) from
dual;
Available methods:
GetAclDocument()
ACLCheckPrivileges()
checkPrivileges()
changePrivileges()
setAcl()
Resource Path
XMLType instance
or positive integer
or N/A
DBMS_XDB: Oracle XML DB Configuration Management
16-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
declare
r pls_integer;
ace xmltype;
ace_data varchar2(2000);
begin
ace_data :=
<ace
xmlns="http://xmlns.oracle.com/xdb/acl.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/acl.xsd
http://xmlns.oracle.com/xdb/acl.xsd
DAV:http://xmlns.oracle.com/xdb/dav.xsd">
<principal>SCOTT</principal>
<grant>true</grant>
<privilege>
<all/>
</privilege>
</ace>;
ace := xmltype.createxml(ace_data);
r := dbms_xdb.changeprivileges(/public/mydocs/emp_scott.xml, ace);
dbms_output.put_line(retval = || r);
commit;
end;
/
select dbms_xdb.getacldocument(/public/mydocs/emp_scott.xml) from
dual;
select dbms_xdb.getprivileges(/public/mydocs/emp_scott.xml) from dual;
call dbms_xdb.deleteresource(/public/mydocs/emp_scott.xml);
call dbms_xdb.deleteresource(/public/mydocs);
commit;
DBMS_XDB: Oracle XML DB Conguration Management
Table 163 lists the DBMS_XDB Oracle XML DB Conguration Management
Methods. Because the arguments and return values for the methods are
self-explanatory, only a brief description of the methods is provided here.
DBMS_XDB: Oracle XML DB Configuration Management
Oracle XML DB Resource API for PL/SQL (DBMS_XDB) 16-9
Using DBMS_XDB for Conguration Management, Calling Sequence
Figure 163 shows the calling sequence when using DBMS_XDB for conguration
management.
The diagram shows the following sequence:
1. To manage the Oracle XML DB conguration you must rst retrieve the
conguration instance using cfg_get.
2. You can then optionally also modify the Oracle XML DB conguration xmltype
instance in order to update it, or simply output the Oracle XML DB
conguration.
3. To update the Oracle XML DB conguration resource use cfg_update. You need
to either input a new Oracle XML DB conguration xmltype instance or use a
modied version of the current conguration.
4. To refresh the Oracle XML DB conguration resource use cfg_refresh. You do
not need to input a conguration xmltype instance.
See Example 163 for an example of using DBMS_XDB for conguration
management of Repository resources.
Table 163 DBMS_XDB: Conguration Management Methods
DBMS_XDB Method Arguments, Return Value
CFG_get Argument: None
Return value: XMLType for session conguration information
CFG_refresh Argument: None
Return value: N/A
CFG_update Argument: (xdbcong INXMLType)
Return value: N/A
DBMS_XDB: Oracle XML DB Configuration Management
16-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 163 Using DBMS_XDB for Conguration Management: Calling Sequence
Example 163 Using DBMS_XDB for Conguration Management of Oracle XML DB
connect system/manager
select dbms_xdb.cfg_get() from dual;
declare
config xmltype;
begin
config := dbms_xdb.cfg_get();
-- Modify the xdb configuration using updatexml, etc ...
dbms_xdb.cfg_update(config);
end;
/
-- To pick up the latest XDB Configuration
-- In this example it is not needed as cfg_update(),
-- automatically does a cfg_refresh().
call dbms_xdb.cfg_refresh();
cfg_update
cfg_get
New Session
Configuration
Information
Modify the Oracle XML DB
Configuration XMLType
cfg_refresh
DBMS_XDB: Rebuilding Oracle XML DB Hierarchical Indexes
Oracle XML DB Resource API for PL/SQL (DBMS_XDB) 16-11
DBMS_XDB: Rebuilding Oracle XML DB Hierarchical Indexes
Table 164 lists the DBMS_XDB Oracle XML DB hierarchical index rebuild methods.
Because the arguments and return values for the methods are self-explanatory, only
a brief description of the methods is provided here.
Using DBMS_XDB to Rebuild Hierarchical Indexes, Calling Sequence
Figure 164 shows the calling sequence when using DBMS_XDB for rebuilding
hierarchical indexes. To rebuild the hierarchical indexes, rst delete the entries from
xdb.xdb$h_index and rebuild the hierarchical index by executing
DBMS_XDB.RebuildHierachicalIndex. Example 164 shows how to use
DBMS_XDB to rebuild the Repository hierarchical indexes.
Figure 164 Using DBMS_XDB to Rebuild Hierarchical Indexes: Calling Sequence
Example 164 Using DBMS_XDB for to Rebuild a Hierarchical index
connect system/manager
delete from xdb.xdb$h_index;
commit;
execute dbms_xdb.RebuildHierarchicalIndex;
Table 164 DBMS_XDB: Hierarchical Index Rebuild Method
DBMS_XDB Method Arguments, Return Values
RebuildHierarchicalIndex Argument: None
Return value: N/A
rebuild hierarchical index
using: dbms_xdb.rebuildHierarchicalIndex
Remove index
entries from
xdb.xdb$h_index
using: DELETE
DBMS_XDB: Rebuilding Oracle XML DB Hierarchical Indexes
16-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Resource API for Java 17-1
17
Oracle XML DB Resource API for Java
This chapter describes the Oracle XML DB Resource API for Java. It contains the
following sections:
I Introducing Oracle XML DB Resource API for Java
I Using Oracle XML DB Resource API for Java
I Parameters for Oracle XML DB Resource API for Java
I Oracle XML DB Resource API for Java: Examples
Introducing Oracle XML DB Resource API for Java
17-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB Resource API for Java
Using Oracle XML DB Resource API for Java
Oracle XML DB Resource API for Java operates as follows:
I JDBC can be used to access Oracle XML DB resource views to retrieve and
modify resources.
Additionally, you can perform these operations:
I Use the Java API for XMLType to access and modify parts of XMLType objects.
I Use the save() method to write changes to the database.
Oracle XML DB Resource API for Java includes a set of sub-interfaces that indicate
resource type Versioning information WebDAV.
The API includes interfaces for objects such as workspaces, branches, and baselines
(as dened by the WebDAV versioning specication).
Parameters for Oracle XML DB Resource API for Java
Table 171 lists the parameters supported by Oracle XML DB Resource API for Java.
See Also:
I Oracle9i XML API Reference - XDK and Oracle XML DB
I Chapter 9, "Java API for XMLType"
Table 171 Oracle XML DB Resource API for Java: Parameters
Parameter Name Description
PROVIDER_URL The start path from which objects are to be returned.
INITIAL_CONTEXT_FACTORY The context factory to be used to generating contexts always
oracle.xdb.spi.XDBContextFactory.
Oracle XML DB Resource API for Java: Examples
Oracle XML DB Resource API for Java 17-3
Oracle XML DB Resource API for Java: Examples
Example 171 Resource JDBC: Using SQL To Determine Purchase Order Properties
Here is an example using SQL, that provides the power of SQL SELECT potentially
using criteria other than path name to nd the XMLType object.
PreparedStatement pst = con.prepareStatement(
"SELECT r.RESOLVE_PATH('/companies/oracle') FROM XDB$RESOURCE r");
pst.executeQuery();
XMLType po = (XMLType)pst.getObject(1);
Document podoc = (Document) po.getDOM();
XDB_RESOURCE_TYPE Determines what data is returned to the application by default
when a path name is resolved:
I Resource: A resource class will be returned.
I XMLType: The contents of the resource will be
returned.
In this release, Oracle XML DB has implemented only the
javax.naming package. Oracle XML DB has an extension to
this package, an extension to the lookup() method. The
extension (an overload) also takes a Boolean (indicating that a
row lock should be grabbed) to indicate a lookup FOR
UPDATE and a String with an XPath to dene a fragment of
the document to load immediately (rather than relying on the
lazy manifest facility).
Table 171 Oracle XML DB Resource API for Java: Parameters (Cont.)
Parameter Name Description
Oracle XML DB Resource API for Java: Examples
17-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Resource Security 18-1
18
Oracle XML DB Resource Security
This chapter describes Access Control Lists (ACL) based security mechanism for
Oracle XML DB resources. It describes how to create ACLs, set and change ACls on
resources, and how ACL security interacts with other database security
mechanisms.
This chapter contains the following sections:
I Introducing Oracle XML DB Resource Security and ACLs
I Access Control List Terminology
I Oracle XML DB ACL Features
I Access Control: User and Group Access
I Oracle XML DB Supported Privileges
I ACL Evaluation Rules
I Using Oracle XML DB ACLs
I ACL and Resource Management
I Using DBMS_XDB to Check Privileges
Introducing Oracle XML DB Resource Security and ACLs
18-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB Resource Security and ACLs
Oracle XML DB maintains object-level security for any resource in Oracle XML DB
Repository hierarchy.
Oracle XML DB uses an access control list (ACL) mechanismto restrict access to any
Oracle XML DB resource or database object mapped to Oracle XML DB Repository.
The Oracle XML DB ACL security mechanism supports the WebDAV ACL
specication. ACLs are a standard security mechanism used in Java, Windows NT,
and other systems.
Oracle XML DB ACL security mechanism is designed to handle large volumes of
XML data stored in Oracle9i database. Privileges can be granted or denied to the
principal dav:owner, that represents the owner of the document, regardless of who
the owner is.
How the ACL-Based Security Mechanism Works
Before a user performs an operation or method on a resource, a check of privileges
for the user on the resource takes place. The set of privileges checked depends on
the operation or method performed. For example, to increase employee Scotts
salary by 10 percent, READ and WRITE privileges are needed for the
scott/salary.xml resource.
Access Control List Terminology
A few access control list (ACL) terms are described here:
I Principal. An entity that may be granted access control privileges to an Oracle
XML DB resource. Oracle XML DB supports as principals:
I Database users.
Note: XML objects not stored in Oracle XML DB Repository do
not have object-level access control.
See Also:
I Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
I Oracle9i XML API Reference - XDK and Oracle XML DB
Access Control List Terminology
Oracle XML DB Resource Security 18-3
I Database roles. A database role can be understood as a group, for example,
the DBA role represents the DBA group of all the users granted the DBA
role.
There is a special principal named dav:owner that corresponds to a separate
property on the object being secured. Use of the dav:owner principal allows
greater ACL sharing between users, since the owner of the document often has
special rights. See Also "Access Control: User and Group Access" on page 18-6.
I Privilege: This is a particular right that can be granted to a principal. Oracle
XML DB has a set of system-dened rights (such as READ, INSERT, or
UPDATE) that can be referenced in any ACL. Privileges can be one of the
following:
Aggregate (containing other privileges)
Atomic (which cannot be subdivided)
Aggregate privileges are a naming convenience to simplify usability when the
number of privileges becomes large, as well as to promote interoperability
between ACL clients. A set of privileges controls the ability to perform a given
operation or method on an Oracle XML DB resource. For example, if the
principal Scott wants to perform the read operation on a given resource, the
read privileges must be granted to Scott prior to the read operation.
Therefore, privileges control how users can operate on given resources.
I ACE (access control entry): Part of an ACL that grants or denies access to a
particular principal. An ACL consists of a list of ACEs where ordering is
irrelevant. There can be only one grant ACE and one deny ACE for a particular
principal in a single ACL.
An Oracle XML DB ACE element has the following attributes:
Operation: Either grant or deny
Principal: Either a User or a group/collection
Note: Users and roles imported from an LDAP server are also
supported as a part of the database's general authentication model.
Note: Many grant ACEs (or deny ACEs) may apply to a particular
user since a user may be granted many roles.
Access Control List Terminology
18-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Privileges Set: Particular set of privileges that are to be either granted or
denied for a particular principal
I Access control list (ACL): A list of access control entry elements, with the
element name ace, that denes access control to a resource. An ACE either
grants or denies privileges for a principal.
I Named ACLs: An ACL that is a resource itself, that is, it has its own path name.
Named ACLs can be shared by multiple resources, improving manageability,
ease of use, and performance. Named ACLs have a unique name and also have
an optional type restrictor, such as:
http://xmlns.oracle.com/xdb/XDBDemo.xsd#PurchaseOrder
that species that the ACL can only be applied to instances of that XML element
and elements in a substitution group with that element.
I Default ACL: When a resource is inserted into the Oracle XML DB Repository,
there are two ways to specify an ACL for this resource:
Using the default ACL (the ACL of the parent folder)
Specifying a particular ACL
I Bootstrap ACL: Every ACL is protected by the contents of another ACL except
the bootstrap ACL. The bootstrap ACL, stored in:
/sys/acls/bootstrap_acl.xml, is the only ACL protected by its own
contents. All of the default ACLs are protected by the bootstrap ACL, which
grants the xdb:readContents privilege to all users. The bootstrap ACL
grants FULL ACCESS to Oracle XML DB ADMIN and DBA groups. The
XDBADMIN role is particularly useful for users that must register global XML
schemas.
I Other ACLs supplied with Oracle XML DB:
all_all_acl.xml Grants all privileges to all users.
all_owner_acl.xml Grants all privileges to owner user.
ro_all_acl.xml Grants read privileges to all users.
Note: ACLs are stored as Oracle XML DB resources, so they also
need to be protected by Oracle XML DB ACLs. There is only one
ACL, the bootstrap ACL, that is self-protected; that is, it is
protected by its own contents.
Oracle XML DB ACL Features
Oracle XML DB Resource Security 18-5
I ACL le-naming conventions: Supplied ACLs use the following le-naming
conventions: privilege_users_acl.xml
where privilege represents the privilege granted and user represents the
users that are granted access to the resource.
Oracle XML DB ACL Features
Oracle XML DB supports the following ACL features:
ACL Interaction with Oracle XML DB Table/View Security
Users must have the appropriate privilege on the underlying table/view where the
XML object is stored, as well as permissions through the ACL for that individual
instance.
LDAP Integration and User IDs
LDAP is integrated with Oracle XML DB to allow external users access to Oracle
XML DB. External users can perform the same operations that a local database user
can.
Oracle XML DB Resource API for ACLs (PL/SQL)
The PL/SQL API for ACL security allows the PL/SQL developer access to the
security mechanisms, to check privileges given a particular ACL, and to list the set
of privileges the current user has for a particular ACL and object.
How Concurrency Issues Are Resolved with Oracle XML DB ACLs
Oracle XML DB ACLs are cached for very fast evaluation. When a transaction
modifying an ACL is committed, the modied ACL is picked up after the time-out
specied in the Oracle XML DB conguration le is up. The XPath for this
conguration parameter is /xdbconfig/sysconfig/acl-max-age.
Note: Some, but not all, objects in a particular table may be
mapped to Oracle XML DB resources. In that case, only those
objects mapped into the Oracle XML DB Repository hierarchy have
ACL checking done, although they will all have table-level security.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Access Control: User and Group Access
18-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Access Control: User and Group Access
The principal can be either an individual user or a group. A group is also
referred to as a collection. A user is granted access as a group principal if the user
has been granted a database role.
Access privileges for each principal are stored in access control entries (ACEs) in the
ACL.
Example 181 ACE Entries in an ACL for Controlling User and Group Access
The following example shows entries in an ACL:
<acl description="myacl"
xmlns="http://xmlns.oracle.com/xdb/acl.xsd"
xmlns:dav="DAV:"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/acl.xsd
http://xmlns.oracle.com/xdb/acl.xsd">
<ace>
<principal>OWNER</principal>
<grant>true</grant>
<privilege>
<all/>
</privilege>
</ace>
</acl>
ACE Elements Specify Access Privileges for Principals
The preceding ACL grants all privileges to the owner of the document. Access to an
Oracle XML DB resource is granted for each principal. Table 181 lists the access
control entry (ACE) elements. Each ACE element species access privileges for a
given principal using values set for the following elements.
Table 181 Access Control Entry (ACE) Elements
Element Description
<principal> Species the principal (user or group).
<grant> A boolean value that species whether the principal has been
granted access to the resource. A value of true species that
the access is granted. A value of false species that access is
denied.
<privilege> Species the privileges granted to the principal.
Oracle XML DB Supported Privileges
Oracle XML DB Resource Security 18-7
Oracle XML DB Supported Privileges
Oracle XML DB provides a set of privileges to control access to Oracle XML DB
resources. Access privileges in an ACE are stored in the privilege element.
Privileges can be:
I Aggregate, composed of other privileges
I Atomic, cannot be subdivided
When an ACL is stored in Oracle XML DB, the aggregate privileges retain their
identity, that is, they are not decomposed into the corresponding leaf privileges. In
WebDAV terms, these are non-abstract aggregate privileges, so they can be used in
ACEs.
Atomic Privileges:
> read-properties
> read-contents
> update
> link (applies only to containers)
> unlink (applies only to containers)
> read-acl
> write-acl-ref
> update-acl
> link-to
> unlink-from
> resolve
> dav:lock
> dav:unlock
>
> Aggregate Privileges:
> dav:read (read-properties, read-contents, resolve)
> dav:write (update, link, unlink, unlink-from)
Oracle XML DB Supported Privileges
18-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
> dav:read-acl (read-acl)
> dav:write-acl (write-acl-ref, update-acl)
> dav:all (dav:read, dav:write, dav:read-acl, dav:write-acl, dav:lock, dav:unlock)
Atomic Privileges
Table 182 lists the atomic privileges supported by Oracle XML DB.
Since you can directly access the XMLType storage for ACLs, the XML structure is
part of the client interface. Hence ACLs can be manipulated using XMLType APIs.
Table 182 Atomic Privileges
Privilege Name Description
Database
Counterpart
read-properties Read the properties of a resource SELECT
read-contents Read the contents of a resource SELECT
update Update the properties and contents of a resource UPDATE
link For containers only. Allows resources to be bound to the container. INSERT
unlink For containers only. Allows resources to be unbound from the container. DELETE
link-to Allows resources to be linked N/A
unlink-from Allows resources to be unlinked N/A
read-acl Read the resources ACL SELECT
write-acl-ref Changes the resources ID UPDATE
update-acl Change the contents of the resources ACL UPDATE
resolve For containers only: Allows the container to be traversed SELECT
dav:lock Lock a resource using WebDAV locks UPDATE
dav:unlock Unlock a resource locked using a WebDAV lock UPDATE
Note: Privilege names are XML element names. Privileges with a
dav: prex are part of the WebDAV namespace. Others privileges
are part of Oracle XML DB ACL namespace:
http://xmlns.oracle.com/xdb/acl.xsd
Oracle XML DB Supported Privileges
Oracle XML DB Resource Security 18-9
Aggregate Privileges
Table 183 lists the aggregate privileges dened by Oracle XML DB, along with the
atomic privileges of which they are composed.
Table 184 shows the privileges required for some common operations on resources
in Oracle XML DB Repository. The Privileges Required column assumes that you
already have resolve privilege on container C and all its parent containers, up to
the root of the hierarchy.
Table 183 Aggregate Privileges
Aggregate Privilege
Names Atomic Privileges
all All atomic privileges: dav:read, dav:write, dav:read-acl,
dav:write-acl, dav:lock, dav:unlock
dav:all All atomic privileges except linkto
dav:read read-properties, read-contents, resolve
dav:write update, link, unlink, unlink-from
dav:read-acl read-acl
dav:write-acl write-acl-ref, update-acl
Table 184 Privileges Needed for Operations on Oracle XML DB Resources
Operation Description Privileges Required
CREATE Create a new resource in container C update and link on C
DELETE Delete resource R from container C update and unlinkfrom on R, update and
unlink on C
UPDATE Update the contents/properties of resources
R
update on R
GET An FTP/HTTP GET of resource R read-properties, read-contents on R
SET_ACL Set the ACL of a resource R dav:write-acl on R
LIST List the resources in container C read-properties on C, read-properties on
resources in C. Only those resources on which
the user has read-properties privilege are
listed.
ACL Evaluation Rules
18-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
ACL Evaluation Rules
To evaluate an ACL, the database collects the list of ACEs applying to the user
logged into the current database session. The list of currently active roles for the
given user is maintained as a part of the session and is used to match ACEs with the
current users. To resolve conicts between ACEs, the following rule is used: if a
privilege is denied by any ACE, the privilege is denied for the entire ACL.
Entries in an ACL must observe the following rule:
I Each principal will have two individual ACEs at most, one for granting
privileges and one for denying privileges.
I Multiple grant ACEs are not allowed for any principal.
I Multiple deny ACEs are not allowed for any principal.
Using Oracle XML DB ACLs
Every resource in the Oracle XML DB Repository hierarchy has an associated ACL.
The ACL mechanism species a privilege-based access control for resources to
principals. Whenever a resource is accessed, a security check is performed. The
ACL determines which principals have which set of privileges to access the
resource. An Oracle XML DB principal can be either of the following:
I An individual principal, such as a database user
I A group principal, such as a group of database users that are granted a common
role
Each ACL has a list of ACEs. An ACE has the following elements:
I A boolean value indicating whether or not this ACE is granting or denying
privileges
I A principal (either a user or a role) indicating to whom the ACL applies
I A list of privileges that are being granted or denied
Named ACLs also have a name attribute and an optional type restrictor, for
example, http://xmlns.oracle.com/xdb/XDBDemo.xsd#PurchaseOrder,
that species that the ACL may only be applied to instances of that XML element
(and elements in a substitution group with that element). Note that a privilege that
is neither granted nor denied to a user is assumed to be denied.
To evaluate an ACL, the database collects the list of ACEs applying to the user
logged into the current database session. The list of currently active roles for the
Using Oracle XML DB ACLs
Oracle XML DB Resource Security 18-11
given user is maintained as a part of the session and is used to match ACEs along
with the current user.
To check if a user has a certain privilege, you need to know the ID of the ACL and
the owner of the object being secured. The Oracle XML DB hierarchy automatically
associates an ACL ID and owner with an object that is mapped into its le system
(they are stored in a table in the Oracle XML DB schema).
Updating the Default ACL on a Folder
Example 182 Updating the Default ACL on a Folder and the Owner of the Folder
This example creates two users, Oracle XML DB administrator, xdbadmin, and
Oracle XML DB user, xdbuser. The administrator creates the user's folder under
'/'. The default ACL on this folder, inherited from the parent container, allows:
I All permissions to the owner
I Only read permission to public
The owner of the folder is changed to the user, by updating the resource_view.
You can also make the user's folder completely private by changing the ACL to
another system ACL, such as, all_owner_acl.xml
connect system/manager
Rem Create an Oracle XML DB administrator user (has XDBADMIN role)
grant connect, resource, xdbadmin to xdbadmn identified by xdbadmn;
Rem Create Oracle XML DB user
grant connect, resource to xdbuser identified by xdbuser;
conn xdbadmn/xdbadmn
Rem create the user's folder
declare
retval boolean;
begin
retval := dbms_xdb.createfolder('/xdbuser');
end;
/
Rem update the OWNER of the user folder
update resource_view
set res = updatexml(res, '/Resource/Owner/text()', 'XDBUSER')
ACL and Resource Management
18-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
where any_path = '/xdbuser';
commit;
connect xdbuser/xdbuser
Rem XDBUSER has full permissions to operate on her folder
declare
retval boolean;
begin
retval := dbms_xdb.createfolder('/xdbuser/workdir');
end;
/
Rem All users can read /xdbuser folder at this time.
Rem change ACL to make folder completely private
call dbms_xdb.setacl('/xdbuser', '/sys/acls/all_owner_acl.xml');
ACL and Resource Management
The following subsections describe ACL and resource management in Oracle XML
DB Repository.
How to Set Resource Property ACLs
Any Oracle XML DB resource has an ACL as a resource property. To set the ACL
resource property, use any of the following methods:
I Perform a RESOURCE_VIEW update
I PL/SQL API: Use DBMS_XDB.setacl(res_path VARCHAR2,acl_path
VARCHAR2) to set the ACL property of the resource represented by res_path to
the ACL represented by acl_path.
I Quote command in FTP: Use quote sacl <res_path> <acl_path> to
set the ACL resource property of res_path to the ACLOID for acl_path
Default Assignment of ACLs
When a resource is inserted into the Oracle XML DB hierarchy, and the resource
does not specify an ACL, it shares the ACL of its parent container.
See Also: Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
Using DBMS_XDB to Check Privileges
Oracle XML DB Resource Security 18-13
Retrieving ACLs for a Resource
The following DBMS_XDB API can be used to get the ACL for a given resource:
DBMS_XDB.getAclDocument(res_path IN VARCHAR2)
It returns an XMLType instance of <acl> element representing the ACL for the
resource at res_path.
Changing Privileges on a Given Resource
The following DBMS_XDB API can be used to add an ACE to a resources ACL:
DBMS_XDB.changePrivileges(res_path IN VARCHAR2, ace IN XMLType)
Restrictions for Operations on ACLs
All named ACLs are XML schema-based resources in the Oracle XML DB
Repository hierarchy. Every method used for other resources in Oracle XML DB
Repository hierarchy can also be used for ACLs. For example, FTP commands,
PL/SQL DOM, and XMLType methods can operate on ACLs. However, because
ACLs are part of the access control security scheme and Oracle XML DB Repository
hierarchy, the following restrictions are enforced:
I ACL insertion: Can be at most one grant ACE and one deny ACE for a
particular principal in an ACL
I ACL deletion: If a resource is currently using the ACL, the ACL cannot be
deleted.
I ACL update (modify): If an ACL resource is updated with non-ACL content,
the same rules as for ACL deletion will apply.
Using DBMS_XDB to Check Privileges
You can enforce Oracle XML DB access control using the following DBMS_XDB
functions:
I CheckPrivileges, getAclDocument, and getPrivileges for Oracle XML
DB resources.
I AclCheckPrivileges for database objects. This function loads the ACL from
the cache, and performs the access request evaluation as described in the next
section.
Using DBMS_XDB to Check Privileges
18-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Row-Level Security for Access Control Security
ACL security in Oracle XML DB acts in conjunction with database security for XML
objects. The user must have the appropriate rights on the underlying table/view
where the XML object is stored as well as permissions in the ACL for that
individual instance. When an object from a particular table is rst stored in the
Oracle XML DB hierarchy (and mapped to a resource), a row-level security (RLS)
policy is added to that table that checks ACL-based permission only for those rows
in the table that are mapped to a resource. RLS is enforced for XMLType tables or
views that are part of the Oracle XML DB hierarchy.
Using FTP, HTTP, and WebDAV Protocols 19-1
19
Using FTP, HTTP, and WebDAV Protocols
This chapter describes how to access Oracle XML DB Repository using FTP,
HTTP/WebDAV protocols. It contains the following sections:
I Introducing Oracle XML DB Protocol Server
I Oracle XML DB Protocol Server Conguration Management
I Using FTP and Oracle XML DB Protocol Server
I Using HTTP and Oracle XML DB Protocol Server
I Using WebDAV and Oracle XML DB
Introducing Oracle XML DB Protocol Server
19-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB Protocol Server
As described in Chapter 2, "Getting Started with Oracle XML DB" and Chapter 13,
"Oracle XML DB Foldering", Oracle XML DB Repository provides a hierarchical
data repository in the database modeled on XML. Oracle XML DB Repository maps
path names (or URLs) onto database objects of XMLType and provides management
facilities for these objects.
Oracle XML DB also provides the Oracle XML DB Protocol Server. This supports
standard Internet protocols, FTP, WebDAV, and HTTP, for accessing its hierarchical
repository/ le system. Since XML documents reference each other using URLs,
typically HTTP URLs, Oracle XML DB Repository and its protocol support are
important Oracle XML DB components. These protocols can provide direct access to
Oracle XML DB to many users without having to install additional software.
Session Pooling
Oracle XML DB Protocol Server maintains a shared pool of sessions. Each protocol
connection is associated with one session from this pool. After a connection is
closed the session is put back into the shared pool and can be used to serve later
connections.
HTTP Performance is Improved
Session Pooling improves performance of HTTP by avoiding the cost of re-creating
session states, especially when using HTTP 1.0, which creates new connections for
each request. For example, a couple of small les can be retrieved by an existing
HTTP/1.1 connection in the time necessary to create a database session. You can
tune the number of sessions in the pool by setting session-pool-size in Oracle XML
DBs xdbconfig.xml le, or disable it by setting pool size to zero.
Java Servlets
Session pooling can affect users writing Java servlets, since other users can come
along and see session state initialized by another request for a different user. Hence,
servlet writers should only use session memory, such as, Java static variables, to
hold data for the entire application rather than for a particular user. Per user state
must be stored in the database or in a look-up table rather than assuming a session
will only exist for a single user.
See Also: "Accessing Oracle XML DB Resources Using Internet
Protocols" on page 13-10
Oracle XML DB Protocol Server Configuration Management
Using FTP, HTTP, and WebDAV Protocols 19-3
Figure 191 illustrates the Oracle XML DB Protocol Server components and how
they are used to access les in Oracle XML DB XML Repository and other data.
Only the relevant components of the Repository are shown
Figure 191 Oracle XML DB Architecture: Protocol Server
Oracle XML DB Protocol Server Conguration Management
Oracle XML DB Protocol Server uses conguration parameters stored in
/xdbconfig.xml to initialize its startup state and manage session level
conguration.The following section describes the protocol-specic conguration
parameters that you can congure in the Oracle XML DB conguration le.
See Also: Chapter 20, "Writing Oracle XML DB Applications in
Java"
See Also: Appendix A, "Installing and Conguring Oracle XML
DB".
HTTP
WebDAV
Client
FTP
Client
Network
Protocol
Server
HTTP /
WebDAV
Server
FTP
Server Foldering
Configuration
Management
ACL
Security
Oracle XML DB Repository
Oracle XML DB Protocol Server Configuration Management
19-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Conguring Protocol Server Parameters
Table 191 shows the parameters common to all protocols. All parameter names in
this table, except those starting with /xdbconfig, are relative to the following
XPath in the Oracle XML DB conguration schema:
/xdbconfig/sysconfig/protocolconfig/common
I FTP-speci c parameters. Table 192 shows the FTP-specic parameters. These
are relative to the following XPath in the Oracle XML DB conguration schema:
/xdbconfig/sysconfig/protocolconfig/ftpconfig
I HTTP/WebDAV speci c parameters except servlet-related parameters.
Table 193 shows the HTTP/WebDAV-specic parameters. These parameters
are relative to the following XPath in the Oracle XML DB conguration schema:
/xdbconfig/sysconfig/protocolconfig/httpconfig
For examples of the usage of these parameters, see the conguration le
/xdbconfig.xml, listed in Appendix A, "Installing and Conguring Oracle XML
DB" and Appendix G, "Example Setup scripts. Oracle XML DB - Supplied XML
Schemas", the section, "xdbcong.xsd: XML Schema for Conguring Oracle XML
DB".
Table 191 Common Protocol Conguration Parameters
Parameter Description
extension-mappings/mime-mappings Species the mapping of le extensions to mime
types. When a resource is stored in the Oracle XML
DB Repository, and its mime type is not specied,
this list of mappings is used to set its mime type.
extension-mappings/lang-mappings Species the mapping of le extensions to
languages. When a resource is stored in the Oracle
XML DB Repository, and its language is not
specied, this list of mappings is used to set its
language.
extension-mappings/encoding-mappings Species the mapping of le extensions to
encodings. When a resource is stored in the Oracle
XML DB Repository, and its encoding is not
specied, this list of mappings is used to set its
encoding.
Oracle XML DB Protocol Server Configuration Management
Using FTP, HTTP, and WebDAV Protocols 19-5
extension-mappings/charset-mappings Species the mapping of le extensions to character
sets. When a resource is stored in the Oracle XML
DB Repository, and its character set is not specied,
this list of mappings is used to set its character set.
session-pool-size Maximum number of sessions that are kept in the
protocol servers session pool
/xdbcong/syscong/call-timeout If a connection is idle for this time (in hundredths of
a second), the shared server serving the connection
is freed up to serve other connections.
session-timeout Time (in hundredths of a second) after which a
session (and consequently the corresponding
connection) will be terminated by the protocol
server if the connection has been idle for that time.
This parameter is used only if the specic protocols
session timeout is not present in the conguration
/xdbcong/syscong/default-lock-timeout Time after which a WebDAV lock on a resource
becomes invalid. This could be overridden by a
Timeout specied by the client that locks the
resource.
Table 192 Conguration Parameters Specic to FTP
Parameter Description
ftp-port Port on which FTP server listens. By default this is
2100
ftp-protocol Protocol over which the FTP server runs. By default
this is tcp
session-timeout Time (in hundredths of a second) after which an FTP
session (and consequently the corresponding
connection) will be terminated by the protocol
server if the connection has been idle for that time.
Table 193 Conguration Parameters Specic to HTTP/WebDAV (Except Servlet
Parameters)
Parameter Description
http-port Port on which HTTP/WebDAV server listens
Table 191 Common Protocol Conguration Parameters (Cont.)
Parameter Description
Oracle XML DB Protocol Server Configuration Management
19-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Interaction with Oracle XML DB Filesystem Resources
The protocol specications, RFC 959 (FTP), RFC 2616 (HTTP), and RFC 2518
(WebDAV) implicitly assume an abstract, hierarchical le system on the server side.
This is mapped to the Oracle XML DB hierarchical Repository. Oracle XML DB
Repository provides features such as:
I Name resolution
I ACL-based security
I The ability to store and retrieve any content. Oracle XML DB Repository can
store both binary data input through FTP and XML schema-based documents.
http-protocol Protocol over which the HTTP/WebDAV server
runs. By default this is tcp
session-timeout Time (in hundredths of a second) after which an
HTTP session (and consequently the corresponding
connection) will be terminated by the protocol
server if the connection has been idle for that time.
server-name The value of the Server header in an HTTP response
max-header-size Maximum size (in bytes) of an HTTP header
max-request-body Maximum size (in bytes) of an HTTP request body
webappcong/welcome-le-list List of lenames that are considered welcome
les. When an HTTP GET request for a container is
received, the server rst checks if theres a resource
in the container with any of these names. If so, the
contents of that le are sent, instead of a list of
resources in the container.
default-url-charset The character set in which an HTTP Protocol Server
assumes incoming URL is encoded when it is not
encoded in UTF-8 or the requests Content-Type
eld Charset parameter.
Table 193 Conguration Parameters Specic to HTTP/WebDAV (Except Servlet
Parameters) (Cont.)
Parameter Description
Using FTP and Oracle XML DB Protocol Server
Using FTP, HTTP, and WebDAV Protocols 19-7
Protocol Server Handles XML Schema-Based or Non-Schema-Based XML Documents
Oracle XML DB Protocol Server enhances the protocols by always checking if XML
documents being inserted are based on XML schemas registered in the Repository.
I If the incoming XML document species an XML schema, the Oracle XML DB
storage to use is decided by that XML schema. This functionality comes in
handy when you need to store XML documents object-relationally in the
database, using simple protocols like FTP or WebDAV instead of having to
write SQL statements.
I If the incoming XML document is not XML schema-based, it is stored as a
binary document.
Event-Based Logging
In certain cases, it may be useful to log the requests received and responses sent by
a protocol server. This can be achieved by setting event number 31098 to level 2. To
set this event, add the following line to init.ora and restart the database:
event=31098 trace name context forever, level 2
Using FTP and Oracle XML DB Protocol Server
The following sections describe FTP features supported by Oracle XML DB.
Oracle XML DB Protocol Server: FTP Features
File Transfer Protocol (FTP) is one of the oldest and most popular protocols on the
net. FTP is specied in RFC959 and provides access to heterogeneous le systems in
a uniform manner. FTP works by providing well dened commands for
communication between the client and the server. The transfer of commands and
the return status happens on a single connection. However, a new connection is
opened between the client and the server for data transfer. In HTTP, the transfer of
commands and data happens on a single connection.
See Also:
I http://rfc.sunsite.dk/rfc/rfc959.html
I http://256.com/gray/docs/rfc2616/
I http://www.faqs.org/rfcs/rfc2518.html
Using FTP and Oracle XML DB Protocol Server
19-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
FTP is implemented by both dedicated clients at the operating system level, le
system explorer clients, and browsers. FTP is typically session-oriented, in that a
user session is created through an explicit logon, a number of les / directories are
downloaded and browsed, and then the connection is closed.
Non-Supported FTP Features
Oracle XML DB implements FTP, as dened by RFC 959, with the exception of the
following optional features:
I Record-oriented les, for example, only the FILE structure of the STRU
command is supported. This is the most widely used structure for transfer of
les. It is also the default specied by the specication. Structure mount is not
supported.
I Append.
I Allocate. This pre-allocates space before le transfer.
I Account. This uses the insecure Telnet protocol.
I Abort.
Using FTP on Standard or Non-Standard Ports
It can be congured through the Oracle XML DB conguration le
/xdbconfig.xml, to listen on an arbitrary port. FTP ships listening on a
non-standard, non-protected port. To use FTP on the standard port (21), your DBA
has to chown the TNS listener to setuid ROOT rather than setuid ORACLE.
FTP Server Session Management
Protocol Server also provides session management for this protocol. After a short
wait for a new command, FTP returns to the protocol layer and the shared server is
freed up to serve other connections. The duration of this short wait is congurable
by changing the call-timeOut parameter in the Oracle XML DB conguration
le. For high trafc sites, the call-timeout should be shorter so that more
connections can be served. When new data arrives on the connection, the FTP
Server is re-invoked with fresh data. So, the long running nature of FTP does not
affect the number of connections which can be made to the Protocol Server.
See Also: RFC 959: FTP Protocol Specication
Using HTTP and Oracle XML DB Protocol Server
Using FTP, HTTP, and WebDAV Protocols 19-9
Using HTTP and Oracle XML DB Protocol Server
Oracle XML DB implements HyperText Transfer Protocol (HTTP), HTTP 1.1 as
dened in RFC2616 specication. In this release, Oracle XML DB Protocol Server
also supports the HTTP protocol extension, RFC 2109 HTTP State Management,
that is cookies.
Oracle XML DB Protocol Server: HTTP Features
The Oracle XML DB HTTP component in the Oracle XML DB Protocol Server
implements the RFC2616 specication with the exception of the following optional
features:
I gzip and compress transfer enco1dings
I byte-range headers
I The TRACE method (used for proxy error debugging)
I Cache-Control directives (requires you to specify expiration dates for content,
and are not generally used)
I TE, Trailer, Vary & Warning headers
I Weak entity tags
I Web common log format
I Multi-homed Web server
Non-Supported HTTP Features
Oracle XML DB does not implement the new Set-Cookie2 header specied in RFC
2965, as most of the Internet community is not yet using it. Digest Authentication
(RFC 2617) is not supported. In this release, Oracle XML DB supports Basic
Authentication, where a client sends the user name and password in clear text in
the Authorization header.
Using HTTP on Standard or Non-Standard Ports
HTTP ships listening on a non-standard, non-protected port (8080). To use HTTP on
the standard port (80), your DBA must chown the TNS listener to setuid ROOT
rather than setuid ORACLE, and congure the port number in the Oracle XML DB
conguration le /xdbconfig.xml.
See Also: RFC 2616: HTTP 1.1 Protocol Specication
Using HTTP and Oracle XML DB Protocol Server
19-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
HTTP Server and Java Servlets
Oracle XML DB supports Java servlets. To use a servlet, it must be registered with a
unique name in the Oracle XML DB conguration le, along with parameters to
customize its behavior. It should be compiled, and loaded into the database. Finally,
the servlet name must be associated with a pattern, which can be an extension such
as *.jsp or a path name such as /a/b/c or /sys/*, as described in Java servlet
API version 2.2.
While processing an HTTP request, the path name for the request is matched with
the registered patterns. If there is a match, the Protocol Server invokes the
corresponding servlet with the appropriate initialization parameters. For Java
servlets, the existing Java Virtual Machine (JVM) infrastructure is used. This starts
the JVM if need be, which in turn runs a Java method to initialize the servlet, create
response, and request objects, pass these on to the servlet, and run it.
Non-ASCII Characters in URLs
When a client sends multibyte data in a URL, RFC 2718 species that the client
should send the URL using the %HHformat where HHis the hexadecimal notation
of the byte value in UTF-8 encoding. The following are some URL examples that
can be sent to XML DB in either an HTTP or WebDAV context:
http://urltest/xyz%E3%81%82%E3%82%A2
http://%E3%81%82%E3%82%A2
http://%E3%81%82%E3%82%A2/abc%81%86%E3%83%8F.xml
XML DB processes the requested URL, any URLs within an IF header, any URLs
within the DESTINATION header, and any URLs in the REFERRED header that
contains multibyte data.
Some clients may either not encode the hexadecimal value in UTF-8, or completely
disregard the %HH notation and send straight multibyte data. XML DB handles
these non-conforming clients by following a specic algorithm. The URL is
processed as follows:
1. Attempts to decode the multibyte data in UTF-8. If this is not valid.
2. Uses the Content-Type charset header value. If the data is not encoded in that
encoding then.
3. If the default-url-charset conguration value is specied, It attempts to
decode the value using that character set.
See Also: Chapter 20, "Writing Oracle XML DB Applications in
Java"
Using WebDAV and Oracle XML DB
Using FTP, HTTP, and WebDAV Protocols 19-11
4. Finally, it assumes it is in the database character set.
Here are some examples of non-conforming URLs:
http://urltest/?,?????^
http://urltest/xyz%<shift-jis HH encoding>%<shift-jis HH encoding>
The default-url-charset must be an IANA name.
Using WebDAV and Oracle XML DB
Web Distributed Authoring and Versioning (WebDAV) is a standard protocol used
to provide users with a le system interface to Oracle XML Repository over the
Internet. The most popular way of accessing a WebDAV server folder is through
WebFolders on Microsoft Windows 2000 or Microsoft NT.
WebDAV is an extension to HTTP 1.1 protocol. It allows clients to perform remote
web content authoring through a coherent set of methods, headers, request body
formats and response body formats. WebDAV provides operations to store and
retrieve resources, create and list contents of resource collections, lock resources for
concurrent access in a coordinated manner, and to set and retrieve resource
properties.
Oracle XML DB WebDav Features
Oracle XML DB supports the following WebDAV features:
I Foldering, specied by RFC2518
I Access Control
WebDAV is a set of extensions to the HTTP protocol that allow you to edit or
manage your les on remote Web servers. WebDav can also be used, for example,
to:
I Share documents over the Internet
I Edit content over the Internet
Oracle XML DBs Non-Supported WebDAV Features
Oracle XML DB supports the contents of RFC2518, with the following exceptions:
See Also: RFC 2518: WebDAV Protocol Specication
Using WebDAV and Oracle XML DB
19-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Lock-NULL resources create actual zero-length resources in the le system, and
cannot be converted to folders.
I Implementing the WebDAV ACL protocol and binding protocol
I Depth-innity locks
I Only Basic Authentication is supported
Using Oracle XML DB and WebDAV: Creating a WebFolder in Windows 2000
To create a WebFolder in Windows 2000, follow these steps:
1. From your desktop, select My Network Places.
2. Double click Add Network Place.
3. Type the location of the folder, for example:
http://[Oracle server name]:<HTTP port number>
See Figure 192.
4. Click Next.
5. Enter any name to identify this WebFolder
6. Click Finish.
You can now access Oracle XML DB Repository just like you access any Windows
folder.
Using WebDAV and Oracle XML DB
Using FTP, HTTP, and WebDAV Protocols 19-13
Figure 192 Creating a WebFolder in Windows 2000
Using WebDAV and Oracle XML DB
19-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Writing Oracle XML DB Applications in Java 20-1
20
Writing Oracle XML DB Applications in Java
This chapter describes how to write Oracle XMl DB applications in Java. It includes
design guidelines for writing Java applications including servlets, and how to
congure the Oracle XML DB servlets.
It contains these sections:
I Introducing Oracle XML DB Java Applications
I Design Guidelines: Java Inside or Outside the Database?
I Writing Oracle XML DB HTTP Servlets in Java
I Conguring Oracle XML DB Servlets
I HTTP Request Processing for Oracle XML DB Servlets
I The Session Pool and XML DB Servlets
I Native XML Stream Support
I Oracle XML DB Servlet APIs
I Oracle XML DB Servlet Example
Introducing Oracle XML DB Java Applications
20-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB Java Applications
Oracle XML DB provides two main architectures for the Java programmer:
I In the database using the Java Virtual Machine (VM)
I In a client or application server, using the Thick JDBC driver
Because Java in the database runs in the context of the database server process, the
methods of deploying your Java code are restricted to one of the following ways:
I You can run Java code as a stored procedure invoked from SQL or PL/SQL or
I You can run a Java servlet.
Stored procedures are easier to integrate with SQL and PL/SQL code, and require
using Oracle Net Services as the protocol to access Oracle9i database.
Servlets work better as the top level entry point into Oracle9i database, and require
using HTTP as the protocol to access Oracle9i database.
Which Oracle XML DB APIs Are Available Inside and Outside the Database?
In this release, some of Oracle XML DB APIs are only available to applications
running in the server. Table 201 illustrates which Oracle XML DB APIs are
available in each architecture in this release. The NO elds will become YES in
a forthcoming release.
Oracle XML DB APIs AVailable Inside and Outside Oracle9i Database
Table 201 Oracle XML DB APIs Inside and Outside Oracle9i Database
Java Oracle XML DB
APIs Description
Inside the Database:Java
Servlets/Stored Procedures
Outside the Database: Using
Thick JDBC (OCI) Drivers
JDBC support for
XMLType
YES YES
XMLType class YES YES
Java DOM implementation YES YES
Design Guidelines: Java Inside or Outside the Database?
Writing Oracle XML DB Applications in Java 20-3
Design Guidelines: Java Inside or Outside the Database?
When choosing an architecture for writing Java Oracle XML DB applications,
consider the following guidelines:
HTTP: Accessing Java Servlets or Directly Accessing XMLType Resources
If the downstreamclient wants to deal with XML in its textual representation, using
HTTP to either access the Java servlets or directly access XMLType resources, will
perform the best, especially if the XML node tree is not being manipulated much by
the Java program.
The Java implementation in the server can natively move data from the database to
the network without converting character data through UCS-2 Unicode (which is
required by Java strings), and in many cases copies data directly from the database
buffer cache to the HTTP connection. There is no need to convert data from the
buffer cache into the SQL serialization format used by Oracle Net Services, move it
to the JDBC client, and then convert to XML. The load-on-demand and LRU cache
for XMLType are most effective inside the database server.
Accessing Many XMLType Object Elements: Use JDBC XMLType Support
If the downstream client is an application that will programmatically access many
or most of the elements of an XMLType object using Java, using JDBC XMLType
support will probably perform the best. It is often easier to debug Java programs
outside of the database server, as well.
Use the Servlets to Manipulate and Write Out Data Quickly as XML
Oracle XML DB servlets are intended for writing HTTP stored procedures in Java
that can be accessed using HTTP. They are not intended as a platform for
developing an entire Internet application. In that case, the application servlet
should be deployed in Oracle9iAS application server and access data in the
database either using JDBC, or by using the java.net.* or similar APIs to get XML
data through HTTP.
They are best used for applications that want to get into the database, manipulate
the data, and write it out quickly as XML, not to format HTML pages for end-users.
Writing Oracle XML DB HTTP Servlets in Java
20-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Writing Oracle XML DB HTTP Servlets in Java
Oracle XML DB provides a Protocol Server that supports FTP, HTTP 1.1, WebDAV,
and Java Servlets. The support for Java Servlets in this release is not complete, and
provides a subset designed for easy migration to full compliance in a following
release. Currently, Oracle XML DB supports Java Servlet version 2.2, with the
following exceptions:
I The Servlet WAR le (web.xml) is not supported in its entirety. Some web.xml
conguration parameters must be handled manually. For example, creating
roles must be done using the SQL CREATE ROLE command.
I RequestDispatcher and associated methods are not supported.
I HTTPServletRequest.getCookies() method is not supported.
I Only one ServletContext (and one web-app) is currently supported.
I Stateful servlets (and thus the HttpSession class methods) are not supported.
Servlets must maintain state in the database itself.
Conguring Oracle XML DB Servlets
Oracle XML DB servlets are congured using the /xdbconfig.xml le in the
Repository. Many of the XML elements in this le are the same as those dened by
the Java Servlet 2.2 specication portion of Java 2 Enterprise Edition (J2EE), and
have the same semantics. Table 202 lists the XML elements dened for the servlet
deployment descriptor by the Java Servlet specication, along with extension
elements supported by Oracle XML DB.
Table 202 XML Elements Dened for Servlet Deployment Descriptors
XML Element Name Dened By Supported? Description Comment
auth-method Java no Species an HTTP authentication
method required for access
--
charset Oracle yes Species a IANA character set
name
For example:
ISO8859, UTF8
charset-mapping Oracle yes Species a mapping between a
lename extension and a charset
--
context-param Java no Species a parameter for a web
application
Not yet supported
description Java yes A string for describing a servlet or
Web application
Supported for servlets
Configuring Oracle XML DB Servlets
Writing Oracle XML DB Applications in Java 20-5
display-name Java yes A string to display with a servlet or
web app
Supported for servlets
distributable Java no Indicates whether or not this servlet
can function if all instances are not
running in the same Java virtual
machine
All servlets running in
the Oracle9i database
MUST be
distributable.
errnum Oracle yes Oracle error number See Oracle9i Database
Error Messages
error-code Java yes HTTP error code Dened by RFC 2616
error-page Java yes Denes a URL to redirect to if an
error is encountered.
Can be specied
through an HTTP
error, an uncaught
Java exception, or
through an uncaught
Oracle error message
exception-type Java yes Classname of a Java exception
mapped to an error page
--
extension Java yes A lename extension used to
associate with MIME types,
character sets, and so on.
--
facility Oracle yes Oracle facility code for mapping
error pages
For example: ORA,
PLS, and so on.
form-error-page Java no Error page for form login attempts Not yet supported
form-login-cong Java no Cong spec for form-based login Not yet supported
form-login-page Java no URL for the form-based login page Not yet supported
icon Java Yes URL of icon to associate with a
servlet
Supported for servlets
init-param Java Yes Initialization parameter for a servlet --
jsp-le Java No Java Server Page le to use for a
servlet
Not supported
lang Oracle Yes IANA language name For example: en-US
lang-mapping Oracle Yes Species a mapping between a
lename extension and language
content
--
Table 202 XML Elements Dened for Servlet Deployment Descriptors (Cont.)
XML Element Name Dened By Supported? Description Comment
Configuring Oracle XML DB Servlets
20-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
large-icon Java Yes Large sized icon for icon display --
load-on-startup Java Yes Species if a servlet is to be loaded
on startup
--
location Java Yes Species the URL for an error page Can be a local path
name or HTTP URL
login-cong Java No Species a method for
authentication
Not yet supported
mime-mapping Java Yes Species a mapping between
lename extension and the MIME
type of the content
--
mime-type Java Yes MIME type name for resource
content
For example:
text/xml or
application/octet-str
eam
OracleError Oracle Yes Species an Oracle error to
associate with an error page
--
param-name Java Yes Name of a parameter for a Servlet
or ServletContext
Supported for servlets
param-value Java Yes Value of a parameter --
realm-name Java No HTTP realm used for authentication Not yet supported
role-link Java Yes Species a role a particular user
must have in order to access a
servlet
Refers to a database
role name. Make sure
to capitalize by
default!
role-name Java Yes A servlet name for a role Just another name to
call the database role.
Used by the Servlet
APIs
security-role Java No Denes a role for a servlet to use Not supported. You
must manually create
roles using the SQL
CREATE ROLE
security-role-ref Java Yes A reference between a servlet and a
role
--
servlet Java Yes Conguration information for a
servlet
--
Table 202 XML Elements Dened for Servlet Deployment Descriptors (Cont.)
XML Element Name Dened By Supported? Description Comment
Configuring Oracle XML DB Servlets
Writing Oracle XML DB Applications in Java 20-7
servlet-class Java Yes Species the classname for the Java
servlet
--
servlet-language Oracle Yes Species the programming
language in which the servlet is
written.
Either Java, C, or
PL/SQL. Currently,
only Java is supported
for customer-dened
servlets.
servlet-mapping Java Yes Species a lename pattern with
which to associate the servlet
All of the mappings
dened by Java are
supported
servlet-name Java Yes String name for a servlet Used by Servlet APIs
servlet-schema Oracle Yes The Oracle Schema in which the
Java class is loaded. If not specied,
the schema is searched using the
default resolver specication.
If this is not specied,
the servlet must be
loaded into the SYS
schema to ensure that
everyone can access it,
or the default Java
class resolver must be
altered. Note that the
servlet-schema is
capitalized unless the
value is quoted with
double-quotes.
session-cong Java No Conguration information for an
HTTPSession
HTTPSession is not
supported
session-timeout Java No Timeout for an HTTP session HTTPSession is not
supported
small-icon Java Yes Small icon to associate with a
servlet
--
taglib Java No JSP tag library JSPs currently not
supported
taglib-uri Java No URI for JSP tag library description
le relative to the web.xml le
JSPs currently not
supported
taglib-location Java No Pathname relative to the root of the
web application where the tag
library is stored
JSPs currently not
supported
url-pattern Java Yes URL pattern to associate with a
servlet
See Section 10 of Java
Servlet 2.2 spec
Table 202 XML Elements Dened for Servlet Deployment Descriptors (Cont.)
XML Element Name Dened By Supported? Description Comment
HTTP Request Processing for Oracle XML DB Servlets
20-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
HTTP Request Processing for Oracle XML DB Servlets
Oracle XML DB handles an HTTP request using the following steps:
1. If a connection has not yet been established, Oracle listener hands the
connection to a shared server dispatcher.
2. When a new HTTP request arrives, the dispatcher wakes up a shared server.
3. The HTTP headers are parsed into appropriate structures.
web-app Java No Conguration for a web application Only one web
application is
currently supported
welcome-le Java Yes Species a welcome-le name --
welcome-le-list Java Yes Denes a list of les to display
when a folder is referenced through
an HTTP GET
Example:
index.html
Note:
I Note 1: The following parameters dened for the web.xml le
by Java are usable only by J2EE-compliant Enterprise Java Bean
containers, and are not required for Java Servlet Containers that
do not support a full J2EE environment: env-entry,
env-entry-name, env-entry-value, env-entry-type, ejb-ref, ejb-ref-type,
home, remote, ejb-link, resource-ref, res-ref-name, res-type, res-auth
I Note 2: The following elements are used to dene access
control for resources: security-constraint, web-resource-collection,
web-resource-name, http-method, user-data-constraint,
transport-guarantee, auth-constrain. Oracle XML DB provides this
functionality through Access Control Lists (ACLs). A future
release will support using a web.xml le to generate ACLs
See Also: Appendix A, "Installing and Conguring Oracle XML
DB" for more information about conguring the /XDBconfig.xml
le.
Table 202 XML Elements Dened for Servlet Deployment Descriptors (Cont.)
XML Element Name Dened By Supported? Description Comment
Native XML Stream Support
Writing Oracle XML DB Applications in Java 20-9
4. The shared server attempts to allocate a database session from the XML DB
session pool, if available, but otherwise will create a new session.
5. A new database call is started, as well as a new database transaction.
6. If HTTP has included authentication headers, the session will be authenticated
as that database user (just as if they logged into SQL*Plus). If no authentication
information is included, and the request is GET or HEAD, Oracle XML DB
attempts to authenticate the session as the ANONYMOUS user. If that database
user account is locked, no unauthenticated access is allowed.
7. The URL in the HTTP request is matched against the servlets in the
xdbconfig.xml le, as specied by the Java Servlet 2.2 specication.
8. The XML DB Servlet Container is invoked in the Java VM inside Oracle. If the
specied servlet has not been initialized yet, the servlet is initialized.
9. The Servlet reads input from the ServletInputStream, and writes output to
the ServletOutputStream, and returns from the service() method.
10. If no uncaught Oracle error occurred, the session is put back into the session
pool.
The Session Pool and XML DB Servlets
The Oracle database keeps one Java VM for each database session. This means that
a session reused from the session pool will have any state in the Java VM (Java
static variables) from the last time the session was used.
This can be useful in caching Java state that is not user-specic, such as, metadata,
but DO NOT STORE SECURE USER DATA I N J AVA STATI C MEMORY! This
could turn into a security hole inadvertently introduced by your application if you
are not careful.
Native XML Stream Support
The DOM Node class has an Oracle-specic method called write(), which takes the
following arguments, returning void:
I java.io.OutputStream stream: A Java stream to write the XML text to
I String charEncoding: The character encoding to write the XML text in. If null,
the database character set is used
See Also: Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
Oracle XML DB Servlet APIs
20-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Short indent The number of characters to indent nested XML elements
This method has a shortcut implementation if the stream provided is the
ServletOutputStream provided inside the database. The contents of the Node
are written in XML in native code directly to the output socket. This bypasses any
conversions into and out of Java objects or Unicode (required for Java strings) and
provides very high performance.
Oracle XML DB Servlet APIs
The APIs supported by Oracle XML DB servlets are dened by the Java Servlet 2.2
specication, the Javadoc for which is available, as of the time of writing this,
online at:
http://java.sun.com/products/servlet/2.2/javadoc/index.html
Table 203 lists non-implemented Java Servlet 2.2 methods. In this release they
result in runtime exceptions.
Oracle XML DB Servlet Example
The following is a simple servlet example that reads a parameter specied in a URL
as a path name, and writes out the content of that XML document to the output
stream.
Example 201 Writing an Oracle XML DB Servlet
The servlet code looks like:
/* test.java */
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;
import java.io.*;
import javax.naming.*;
import oracle.xdb.dom.*;
Table 203 Non-Implemented Java 2.2 Methods
Interface Methods
HttpServletRequest getSession(), isRequestedSessionIdValid()
HttpSession ALL
HttpSessionBindingListener ALL
Oracle XML DB Servlet Example
Writing Oracle XML DB Applications in Java 20-11
public class test extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
OutputStream os = resp.getOutputStream();
Hashtable env = new Hashtable();
XDBDocument xt;
try
{
env.put(Context.INITIAL_CONTEXT_FACTORY,
"oracle.xdb.spi.XDBContextFactory");
Context ctx = new InitialContext(env);
String [] docarr = req.getParameterValues("doc");
String doc;
if (docarr == null || docarr.length == 0)
doc = "/foo.txt";
else
doc = docarr[0];
xt = (XDBDocument)ctx.lookup(doc);
resp.setContentType("text/xml");
xt.write(os, "ISO8859", (short)2);
}
catch (javax.naming.NamingException e)
{
resp.sendError(404, "Got exception: " + e);
}
finally
{
os.close();
}
}
}
Installing the Oracle XML DB Example Servlet
To install this servlet, compile it, and load it into Oracle9i database using
commands such as:
% loadjava grant public u scott/tiger r test.class
Oracle XML DB Servlet Example
20-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Conguring the Oracle XML DB Example Servlet
To congure Oracle XML DB servlet, update the /xdbconfig.xml le by inserting
the following XML element tree in the <servlet-list> element:
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-language>Java</servlet-language>
<display-name>XML DB Test Servlet</display-name>
<servlet-class>test</servlet-class>
<servlet-schema>scott</servlet-schema>
</servlet>
and update the /xdbconfig.xml le by inserting the following XML element tree
in the <servlet-mappings> element:
<servlet-mapping>
<servlet-pattern>/testserv</servlet-pattern>
<servlet-name>TestServlet</servlet-name>
</servlet-mapping>
You can edit the /xdbconfig.xml le with any WebDAV-capable text editor, or
by using the updateXML() SQL operator.
Testing the Example Servlet
To test the example servlet, load an arbitrary XML le at /foo.xml, and type the
following URL into your browser, replacing the hostname and port number as
appropriate:
http://hostname:8080/testserv?doc=/foo.xml
Note: You will not be allowed to actually delete the
/xdbconfig.xml le, even as SYS!
Part VI
Oracle Tools that Support Oracle XML DB
Part VI of this manual introduces you to Oracle SQL*Loaderand the Import-Export
Utility for loading XML data. It also describes how to use Oracle Enterprise
Manager for managing and administering your XML database applications.
Part VI contains the following chapters:
I Chapter 21, "Managing Oracle XML DB Using Oracle Enterprise Manager"
I Chapter 22, "Loading XML Data into Oracle XML DB"
I Chapter 23, "Importing and Exporting XMLType Tables"
Managing Oracle XML DB Using Oracle Enterprise Manager 21-1
21
Managing Oracle XML DB Using Oracle
Enterprise Manager
This chapter describes how Oracle Enterprise Manager can be used to manage
Oracle XML DB. Oracle Enterprise Manager can be used to congure, create and
manage Repository resources, and database objects such as XML schemas and
XMLType tables.
It contains the following sections:
I Introducing Oracle XML DB and Oracle Enterprise Manager
I Oracle Enterprise Manager Oracle XML DB Features
I The Enterprise Manager Console for Oracle XML DB
I Conguring Oracle XML DB with Enterprise Manager
I Creating and Managing Oracle XML DB Resources with Enterprise Manager
I Managing XML Schema and Related Database Objects
I Creating Structured Storage Infrastructure Based on XML Schema
Introducing Oracle XML DB and Oracle Enterprise Manager
21-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing Oracle XML DB and Oracle Enterprise Manager
This chapter describes how to use Oracle Enterprise Manager (Enterprise Manager)
to administer and manage Oracle XML DB.
Getting Started with Oracle Enterprise Manager and Oracle XML DB
Oracle Enterprise Manager is supplied with Oracle9i database software, both
Enterprise and Standard Editions. To run the Enterprise Manager version that
supports Oracle XML DB functionality, use Oracle9i Release 2 (9.2) or higher.
Enterprise Manager: Installing Oracle XML DB
Oracle XML DB is installed by default when the Database Conguration Assistant
(DBCA) is used to create a new database. The following actions take place during
Oracle XML DB installation:
I Oracle registers the conguration XML schema:
http://www.oracle.com/xdb/xdbconfig.xsd
I Oracle inserts a default conguration document. It creates resource
/sys/xdbconfig.xml conforming to the conguration XML schema. This
resource contains default values for all Oracle XML DB parameters.
You Must Register Your XML Schema with Oracle XML DB
Oracle XML DB is typically used for its faster retrieval and search capabilities,
access control, and versioning of XML documents. XML instance documents saved
in the database can conform to an XML Schema. XML Schema is a schema
denition language, also written in XML, that can be used to describe the structure
and various other semantics of a conforming XML instance document.
Oracle XML DB provides a mechanism to register XML Schemas with the database.
Assuming that your XML schema document(s) already exists, registering the XML
schema is your rst task. Before you register the XML schema, you must know the
following:
See Also:
I Chapter 2, "Getting Started with Oracle XML DB"
I Appendix A, "Installing and Conguring Oracle XML DB"
Oracle Enterprise Manager Oracle XML DB Features
Managing Oracle XML DB Using Oracle Enterprise Manager 21-3
1. Whether the data for the XML instance documents already exists in relational
tables. This would be the case for legacy applications. If so, Object Views for
XML must be created.
2. What is the storage model? Are you using LOB storage, object-relational
storage, or both? The answer to this question depends on which parts of the
document are queried the most often, and hence would need faster retrieval.
3. I s the XML Schema document annotated with comments to generate object
datatypes and object tables? If not, these objects will have to be created and
mapped manually to the database schema.
For most cases, it is assumed that you have XML schema annotated with
information to automatically generate object types and object tables. Hence the
Oracle9i database, as part of XML schema registration, automatically generates
these objects.
Oracle XML DB is now ready for you to insert conforming XML documents.
Oracle Enterprise Manager Oracle XML DB Features
With Enterprise Manager you can perform the following main Oracle XML DB
administrative tasks:
I Congure Oracle XML DB
I Create and Manage Resources
I Manage XML Schema and Related Database Objects
See Figure 211 and Figure 212.
See Also:
I Chapter 3, "Using Oracle XML DB"
I Chapter 5, "Structured Mapping of XMLType"
See Also: "Managing XML Schema and Related Database
Objects" on page 21-27.
Oracle Enterprise Manager Oracle XML DB Features
21-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 211 Managing Oracle XML DB with Enterprise Manager: Main Tasks
Congure Oracle XML DB
Oracle XML DB is managed through the conguration le, xdbconfig.xml.
Through Enterprise Manager, you can view or congure this les parameters. To
access the Oracle XML DB conguration options, fromthe Enterprise Manager right
hand window, select Congure XML Database. See "Conguring Oracle XML DB
with Enterprise Manager" on page 21-7.
Create and Manage Resources
To access the XML resource management options, select the XML Database object in
the Navigator and click Create a Resource in the detail view. See "Creating and
Managing Oracle XML DB Resources with Enterprise Manager" on page 21-12.
Manage XML Schema and Related Database Objects
To access the XML schema management options, select the XML Database object in
the Navigator and click Create Table and Views Based on XML Schema in the
detail view. See "Managing XML Schema and Related Database Objects" on
page 21-27.
You can register, delete, view, generate (that is, reverse engineer) an XML schema
and see its dependencies. You can also view an XML schemas contents and
perform actions on its constituent elements.
I Views. Create or alter an object view of XMLType, and look at the
corresponding indexes.
Oracle Enterprise Manager
Oracle XML DB Management
Configure
Oracle XML DB
- xdbconfig.xml
Create and
Manage
Resources
- including
resource
security
Manage
XML Schema
- Create tables and
views based on XML
Schema
- Create XMLType, tables
- Create tables with
XMLType columns
Oracle Enterprise Manager Oracle XML DB Features
Managing Oracle XML DB Using Oracle Enterprise Manager 21-5
I Tables. Create XML schema-based and non-XML schema-based XMLType tables
and columns, and look at the corresponding indexes. You can also specify LOB
storage attributes on these columns.
You can create XMLType tables in CLOB or object-relational form, and specify
constraints and LOB storage attributes on hidden XMLType columns.
I I ndexes. Create index on the hidden columns of XMLType.
I DML operations. You can also perform other DML operations such as inserting
and updating rows using XML instance documents.
I XML Schema Elements. You can viewelements in their XML formand the XML
instance data stored in the database corresponding to that element. You can also
view the XML schemas dependent objects, such as tables, views, indexes,
object types, array types, and table types.
Oracle Enterprise Manager Oracle XML DB Features
21-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 212 Enterprise Manager Console: XML Database Management Window
Configuring Oracle XML DB with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-7
The Enterprise Manager Console for Oracle XML DB
See Figure 212. From the Enterprise Manager console you can quickly browse and
manage Oracle XML DB objects.
XML Database Management Window: Right-Hand Dialog Windows
From the XML Database Management detail view you can access the XML DB
management functionality. From there you can select which task you need to
perform.
Hierarchical Navigation Tree: Navigator
Use the left-hand Navigator, to select the Oracle XML DB resources and database
objects you need to view or modify.
Conguring Oracle XML DB with Enterprise Manager
Oracle XML DB conguration is an integral part of Oracle XML DB. It is used by
protocols such as HTTP/WebDav or FTP, and any other components of Oracle XML
DB that can be customized, such as, in the ACL based security.
Oracle XML DB conguration is stored as an XML schema based XML resource,
xdbconfig.xml in the Oracle XML DB Repository. It conforms to the Oracle XML
DB conguration XML schema stored at:
http://www.oracle.com/xdb/xdbconfig.xsd
This conguration XML schema is registered when Oracle XML DB is installed. The
conguration property sheet has two tabs:
I For System Congurations. General parameters and FTP and HTTP protocol
specic parameters can be displayed on the System Congurations tab.
I For User Congurations. Custom parameters can be displayed on the User
Congurations tab.
To congure items in Oracle XML DB, select the Con guration node under XML
Database in the Navigator. See Figure 213 and See Figure 214.
The XML Database Parameters page displays a list of conguration parameters for
the current XML database. You can also access this page from the XML Database
Management main window > Congure XML Database.
Configuring Oracle XML DB with Enterprise Manager
21-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
When you click the Con guration node for the XML database in the Enterprise
Manager Navigator, the XML DB Parameters page appears in the main panel to the
right. The XML DB Parameters window lists the following information:
I Parameter Name -- Lists the name of the parameter.
I Value -- Displays the current value of the parameter. This is an editable eld.
I Default -- Indicates whether the value is a default value. A check mark indicates
a default value.
I Dynamic -- Indicates whether or not the value is dynamic. A check mark
indicates dynamic.
I Category -- Displays the category of the parameter. Category can be HTTP, FTP,
or Generic.
You can change the value of a parameter by clicking the Value eld for the
parameter and making the change. Click the Apply button to apply any changes
you make. You can access a description of a parameter by clicking on the parameter
in the list and then clicking the Description button at the bottom of the page. A text
Description text box displays that describes in greater detail the parameter you
selected. You can close the Description box by clicking again on the Description
button.
Configuring Oracle XML DB with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-9
Figure 213 Enterprise Manager Console: Conguring Oracle XML DB
Configuring Oracle XML DB with Enterprise Manager
21-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Since Oracle XML DB provides support for standard Internet protocols (FTP and
WebDAV/HTTP) as a means of accessing the Repository, Enterprise Manager
provides you with related information:
I Oracle XML DB FTP Port: displays the port number the FTP protocol will be
listening to. FTP by default listens on a non-standard, non-protected port.
I Oracle XML DB HTTP Port: displays the port number the HTTP protocol will
be listening to. HTTP will be managed as a Shared Server presentation, and can
be congured through the TNS listener to listen on arbitrary ports. HTTP listens
on a non-standard, non-protected port.
Configuring Oracle XML DB with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-11
Figure 214 Enterprise Manager Console: Oracle XML DB Conguration Parameters
Dialog
Viewing or Editing Oracle XML DB Conguration Parameters
With Enterprise Manager you can view and edit partial Oracle XML DB
conguration parameters, in the following categories:
Category: Generic
I case-sensitive
Creating and Managing Oracle XML DB Resources with Enterprise Manager
21-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Category: FTP
I ftp-port: Enterprise Manager manages FTP as a Shared Server presentation. It
can be congured using TNS listeners to listen on arbitrary ports.
I ftp-logle-path: The le path of the FTP Server log le.
I ftp-log-level: The level of logging for FTP error and warning conditions.
Category: HTTP
I http-port: Enterprise Manager manages HTTP as a Shared Server presentation.
It can be congured using TNS listeners to listen on arbitrary ports.
I session-timeout: The maximum time the server will wait for client responses
before it breaks a connection.
I server-name: Hostname to use by default in HTTP redirects and servlet API.
I http-logle-path: The le path of the HTTP server log le.
I http-log-level: The level of logging for HTTP error and warning conditions.
I welcome-le-list: The list of welcome les used by the server.
Creating and Managing Oracle XML DB Resources with Enterprise
Manager
The Resources folder in the Enterprise Manager navigation tree is under the XML
Database folder. It contains all the resources in the database regardless of the owner.
Figure 215 shows a typical Resources tree.
When the Resources folder is selected in the Navigator, the right-hand side of the
screen displays all the top level Oracle XML DB resources under root, their names,
and their creation and modication dates. See Figure 216.
Note: Oracle XML DB always preserves case.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-13
Figure 215 Enterprise Manager: Oracle XML DB Resources Tree Showing Resources
Folder Selected
Creating and Managing Oracle XML DB Resources with Enterprise Manager
21-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 216 Enterprise Manager: Top Level Resources Under Root
Creating and Managing Oracle XML DB Resources with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-15
Administering Individual Resources
Once you select a resource sub-folder under the main Resources folder in the
Navigator, you can see the resources General Page in the detail view, as shown in
Figure 217.
Figure 217 Enterprise Manager: Individual Resources - General Page
Creating and Managing Oracle XML DB Resources with Enterprise Manager
21-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
General Resources Page
The Oracle XML DB Resources General page (also called the XML Resources Page)
displays overview information about the resource container or resource le. When
you select one of the Oracle XML DB resource containers or les in the Navigator,
Enterprise Manager displays the Oracle XML DB Resources General page. This is a
read-only page. It displays the following information:
I Name - name of the resource le or container
I Creator - the user or role that created the resource
I Last Modier - the name of the user who last modied the resource
I Created - the date and time the resource was created
I Modied - the date and time that the resource was last changed
I Language - the resource language, such as, US English
I Type - File or Container
Security Page
Oracle XML DB Resources Security page changes the ACL associated with the XML
DB resource container or le. Use the ACL les to restrict access to all XML DB
resources. When you change the ACL le for the resource, you change the access
privileges for the resource le. See Figure 218.
To specify a new ACL le:
1. Click the Specify a new ACL File option box and then choose a new ACL le
from the drop down list in the File Name eld.
2. Click the Apply button to apply the change.
3. Click the Revert button to abandon any changes you have made to the File
Name eld.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-17
Figure 218 Enterprise Manager: Individual Oracle XML DB Resource - Security Page
Individual Resource Content Menu
Figure 219 shows the context-sensitive menu displayed when you select and
right-click an individual Oracle XML DB resource object in the Navigator.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
21-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 219 Enterprise Manager: When You Right-Click an Individual Resource...
You can perform the following Oracle XML DB tasks from the Enterprise Manager
Content Menu:
Create Resource
Figure 2110 shows how you can use the Create XML DB Resource dialog box to
create an XML DB resource container or le. Fromthe XML DB Resource dialog you
can name the resource and then either create a new resource container or create a
new resource le, designating the location of the le as either a local le, a le at a
specied URL, or specifying the contents of the le.
1. Access the Create XML DB Resource dialog box by right clicking on the
Resources folder or any individual resource node and selecting Create from the
context menu. When you name the resource in the Name eld, you can change
the location by clicking on the Change Location button to the right of the
Location eld.
2. Specify whether the resource you are creating is a container or a le. If you
create a le by choosing Create a new resource le, you can select from one of
three le type location options:
Local File -- Select Use a le in the local le system to browse for a le
location on your network.
File at URL -- Select Use a le at the URL to enter the location of the le on
the internet or intranet.
File Contents -- Select Specify the resource contents here to enter the
contents of a le in the edit box located at the bottomof the Create XML DB
Resource dialog box.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-19
Figure 2110 Enterprise Manager: Create Oracle XML DB Resource Dialog Box
Grant Privileges On...
Figure 2111 shows the Grant Privileges On dialog box which assigns privileges on
an Oracle XML DB resource to users or roles. You can grant multiple privileges to
multiple users or roles. Grant Privileges On dialog box lists the available Oracle
XML DB resource privileges in the Grant section at the top of the panel.
1. To grant privileges, select the privileges you want to grant by clicking on a
privilege. You can select multiple privileges by holding down the Ctrl key while
selecting more than one privilege. You can select consecutive privileges by
clicking the rst privilege in a sequence and holding down the Shift key while
clicking the last privilege in the sequence.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
21-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
2. Select the user/ group in the To: box at the bottom of the dialog page. Use the
same procedure to select multiple users/roles to which to grant privileges.
Figure 2111 Enterprise Manager: Granting Privileges On Oracle XML DB Resources
Show Contents
Figure 2112 is an example of a Show Contents dialog box. It displays the contents
of the selected resource le.
See Also: "Enterprise Manager and Oracle XML DB: ACL
Security" on page 21-22.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-21
Figure 2112 Enterprise Manager: Show Contents Menus of Individual Oracle XML
DB Resource
Show Grantee
Figure 2111 shows the Show Grantee of XML DB Resource dialog box. It displays
a list of all granted privileges on a specied XML DB resource for the connected
Enterprise Manager user. Show Grantee dialog box lists the connected Enterprise
Manager user, privilege, and granted status of the privilege in tabular format.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
21-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2113 Enterprise Manager: Show Grantee of Oracle XML DB Resources
Enterprise Manager and Oracle XML DB: ACL Security
From Enterprise Manager you can restrict access to all XML DB resources by means
of ACLs. You can grant XML DB resource privileges to database user and database
role separately using the existing Security/Users/user and
Security/Roles/role interface, respectively.
You can access the Enterprise Manager security options in two main ways:
I To view or modify user (or role) security: In the Navigator, under the Oracle
XML DB database in question > Security >Users >user (or > Security > Roles >
role). In the detail view, select the XML tag. See Figure 2114. This user security
option is described in more detail in "Granting and Revoking User Privileges
with User > XML Tab" on page 21-23.
I To view or modify a resources security: Select the individual resource node
under the Resources folder in the left navigation panel. Select the Security tag
in the detail view. See Figure 2115.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-23
Granting and Revoking User Privileges with User > XML Tab
This section describes how to grant and revoke privileges for a user, The same
procedure applies when granting and revoking privileges for a role. To grant
privileges to a user follow these steps:
1. Select a particular user from the Enterprise Manager Navigator. The detail view
displays an additional tab, XML, in the existing property sheet.
2. To view and select resources on which you want to grant privileges to users or
roles, select the XML tab. Once you select a resource, all available privileges for
that resource are displayed in the Available Privileges list to the right of the
Resources list.
3. Select the privileges required from the Available Privileges list and move them
down to the Granted list that appears at the bottom of the window by clicking
on the down arrow.
Conversely, you can revoke privileges by selecting them in the Granted list and
clicking on the up arrow.
4. After setting the appropriate privileges, click the Apply button to save your
changes. Before you save your changes, you can click the Revert button to
abandon your changes.
Creating and Managing Oracle XML DB Resources with Enterprise Manager
21-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2114 Adding or Revoking Privileges with Users > user> XML
Creating and Managing Oracle XML DB Resources with Enterprise Manager
Managing Oracle XML DB Using Oracle Enterprise Manager 21-25
Resources List
The Resources list is a tree listing of resources located in Oracle XML DB
Repository. You can navigate through the folder hierarchy to locate the resource on
which you want to set privileges for the user or role you selected in Navigator.
When you select a resource in the tree listing, its privileges appear in the Available
Privileges list to the right.
Available Privileges List
The Available Privileges list displays all privileges available for a resource. Click a
privilege and then press the down arrow button to add the privilege to the Granted
list. You can select consecutive privileges by clicking on the rst privilege and then
holding the Shift key down to select the last in the list. Also, you can select
non-consecutive privileges by holding the Ctrl-key down while making selections.
Privileges can be either of the following:
I aggregate privileges. They contain other privileges.
I atomic privileges. They cannot be subdivided.
Granted List
The Granted list displays all privileges granted to the user or role for the resource
selected in the Resources list. You can revoke a privilege by highlighting it and
clicking the up arrow to remove it.
XML Database Resource Privileges
Privilege can be aggregate (contain other privileges) or atomic (cannot be
subdivided). The following system privileges are supported:
I Atomic Privileges
all
read-properties
read-contents
update
link (applies only to containers)
unlink (applies only to containers)
read-acl
Creating and Managing Oracle XML DB Resources with Enterprise Manager
21-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
write-acl-ref
update-acl
link-to
unlink-from
resolve
dav:lock
dav:unlock
I Aggregate Privileges
dav:read (read-properties, read-contents, resolve)
dav:write (update, link, unlink, unlink-from)
dav:read-acl (read-acl)
dav:write-acl (write-acl-ref, update-acl)
dav:all (dav:read, dav:write, dav:read-acl, dav:write-acl, dav:look,
dav:unlock)
Managing XML Schema and Related Database Objects
Managing Oracle XML DB Using Oracle Enterprise Manager 21-27
Figure 2115 Granting Privileges on a Resource
Managing XML Schema and Related Database Objects
From the XML Database Management detail view, when you select Create tables
and views based on XML Schema the XML Schema Based Objects page appears.
With this you can:
I Register an XML schema
I Create a structured storage based on XML schema
See Also: Chapter 18, "Oracle XML DB Resource Security" for a
list of supported system privileges.
Managing XML Schema and Related Database Objects
21-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Create an XMLType table
I Create a table with XMLType columns
I Create a view based on XML schema
I Create a function-based index based on XPath expressions
Navigating XML Schema in Enterprise Manager
Under the XML Schema folder, the tree lists all the XML schema owners. The
example here is owner XDB. See Figure 2116:
I Schema Owners. Under the individual XML schema owners, the tree lists the
XML schemas owned by the owner(s). Here you can see:
http://xmlns.oracle.com/xdb/XDBResource.xsd
http://xmlns.oracle.com/xdb/XDBSchema.xsd
http://xmlns.oracle.com/xdb/XDBStandard.xsd
I Top level elements. Under each XML schema, the tree lists the top level
elements. These elements are used to create the XMLType tables, tables with
XMLType columns, and views. For example, Figure 2116 shows top level
elements servlet and LINK. The number and names of these elements are
dictated by the relevant XML schema denition, which in this case is:
http://xmlns.oracle.com/XDBStandard.xsd.
I Dependent objects. Under each element, the tree lists the created dependent
objects, Tables, Views, and User Types respectively. In this example, you can see
that top level element servlet has dependent XMLType Tables, Views, and User
types.
I Dependent object owners. Under each dependent object type, the tree lists the
owner.
Tables. For example, under Tables, XDB is an owner, and XDB owns a
table called SERVLET.
* Table characteristics. Under each table name the tree lists any created
Indexes, Materialized View Logs (Snapshots), Partitions, and
Triggers.
Views. Not shown here but under Views you would see any view owners
and the name of views owned by these owners:
* View characteristics. These are not listed here.
Managing XML Schema and Related Database Objects
Managing Oracle XML DB Using Oracle Enterprise Manager 21-29
I User Types. The tree lists any user types associated with the top level
element servlet. These are listed according to the type:
* Object types. Under Object types the tree lists the object type owners.
* Array types. Under Array types the tree lists the array type owners.
* Table types. Under table types the tree lists the table type owners.
Managing XML Schema and Related Database Objects
21-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2116 Enterprise Manager Console: Navigating XML Schema
Managing XML Schema and Related Database Objects
Managing Oracle XML DB Using Oracle Enterprise Manager 21-31
Figure 2117 Enterprise Manager: Creating XML Schema-Based Objects
Registering an XML Schema
Registering an XML schema is one of the central, and often rst, tasks before the
you use Oracle XML DB. XML schema are registered using
DBMS_XMLSCHEMA.registerSchema().
Figure 2118 shows you how to register an XML schema.
See Also: Chapter 5, "Structured Mapping of XMLType"
Managing XML Schema and Related Database Objects
21-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
General Page
From the GENERAL page, input the XML schema URL and select the Owner of the
XML schema from the drop-down list.
Select either:
I Global, that is XML schema is visible to public
I Local, that is XML schema is visible only to the user creating it
You can obtain the XML schema in one of four ways:
I By specifying the location of the le in the local le system
I By specifying the XML Database (Repository) resource where the XML schema
is located
I By specifying the URL location
I By cutting and pasting the text form another screen
Options Page
From the Options page you can select the following options:
I Generate the object types based on this XML schema
I Generate tables based on this XML schema
I Generate Java beans based on this XML schema
I Register this XML schema regardless of any errors
See Figure 2119. Press Create fromeither the General Tab or Options Tab to register
this XML schema.
Managing XML Schema and Related Database Objects
Managing Oracle XML DB Using Oracle Enterprise Manager 21-33
Figure 2118 Enterprise Manager: Registering an XML Schema - General Page
Creating Structured Storage Infrastructure Based on XML Schema
21-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2119 Enterprise Manager: Creating XML Schema - Options Page
Creating Structured Storage Infrastructure Based on XML Schema
This section describes how to use Oracle Enterprise Manager to create XMLType
tables, views, and indexes.
Creating Tables
You have two main options when creating tables:
I "Creating an XMLType Table" on page 21-35
I "Creating Tables with XMLType Columns" on page 21-37
Creating Views
To create an XMLType view, see "Creating a View Based on XML Schema" on
page 21-39.
Creating Function-Based Indexes
To create function-based indexes see "Creating a Function-Based Index Based on
XPath Expressions" on page 21-42.
Creating Structured Storage Infrastructure Based on XML Schema
Managing Oracle XML DB Using Oracle Enterprise Manager 21-35
Creating an XMLType Table
From the Create Table property sheet, enter the desired name of the table you are
creating on the General page. Select the table owner from the drop-down list
Schema. Leave Tablespace at the default setting. Select XMLType table.
Under the lower Schema option, select the XML schema owner, from the
drop-down list.
Under XML Schema, select the actual XML schema from the drop-down list.
Under Element, select the required element to from the XMLType table, from the
drop-down list.
Specify the storage:
I Store as dened by the XML schema. When you select this option, hidden
columns are created based on the XML schema denition annotations. Any
SELECTs or UPDATEs on these columns are optimized.
I Store as CLOB. When you select CLOB the LOB Storage tab dialog appears.
Here you can customize the CLOB storage. See Figure 2121.
Creating Structured Storage Infrastructure Based on XML Schema
21-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2120 Enterprise Manager: Creating XMLType Tables-General Page
Creating Structured Storage Infrastructure Based on XML Schema
Managing Oracle XML DB Using Oracle Enterprise Manager 21-37
Figure 2121 Enterprise Manager: Creating XMLType Tables - Specifying LOB
Storage
Creating Tables with XMLType Columns
See Figure 2122 shows the Create Table General page. To create a table with
XMLType columns follow these steps:
1. From the Create Table property sheet, enter the desired name of the table you
are creating on the General page.
2. Select the table owner from the drop-down list Schema. Leave Tablespace at
the default setting.
3. Select Dene Columns.
4. Enter the Name. Enter the Datatype; select XMLType from the drop-down list.
The XMLType Options dialog window appears. See Figure 2123.
Creating Structured Storage Infrastructure Based on XML Schema
21-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2122 Enterprise Manager: Creating Tables With XMLType Column - General
Page
5. Fromthis screen you can specify for a particular XMLType column, whether it is
XML schema-based or non-schema-based.
I If it is XML schema-based:
* Under the Schema option, select the XML schema owner, from the
drop-down list.
* Under XML Schema, select the actual XML schema from the
drop-down list.
* Under Element, select the required element to form the XMLType
column, from the drop-down list.
* Specify the storage:
* Store as dened by the XML schema.
* Store as CLOB. When you select CLOB the LOB Storage tab dialog
appears. Here you can customize the CLOB storage.
I If it is non-schema-based you do not need to change the default settings.
Creating Structured Storage Infrastructure Based on XML Schema
Managing Oracle XML DB Using Oracle Enterprise Manager 21-39
Figure 2123 Enterprise Manager: Creating Tables With XMLType Column - XMLType
Options
Creating a View Based on XML Schema
Figure 2124 shows the Create View General page. To create a view based on an
XML schema, follow these steps:
1. Enter the desired view name. Under Schema, select the view owner from the
drop-down list.
2. Enter the SQL statement text in the Query Text window to create the view.
Select the Advanced tab. See Figure 2125.
From here you can select Force mode
3. Select the As Object option. The view can be set to Read Only or With Check
Option.
Creating Structured Storage Infrastructure Based on XML Schema
21-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
4. Because this is an XMLType view, select the As Object option. Select
XMLType not Object Type.
5. Under the Schema option, select the XML schema owner, from the
drop-down list.
6. Under XML Schema, select the actual XML schema from the drop-down list.
7. Under Element, select the required element to form the XMLType column,
from the drop-down list.
8. Specify the Object Identier (OID):
If your SQL statement to create the view is based on an object type table,
then select the Use default if your query is based on...
Otherwise, select Specify based on XPath expression on the structure of
the element. Enter your XPath expression. See Chapter 11, "XMLType
Views".
Creating Structured Storage Infrastructure Based on XML Schema
Managing Oracle XML DB Using Oracle Enterprise Manager 21-41
Figure 2124 Enterprise Manager: Creating an XMLType View - General Page
Creating Structured Storage Infrastructure Based on XML Schema
21-42 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2125 Enterprise Manager: Creating XMLType Views - Advanced Page
Creating a Function-Based Index Based on XPath Expressions
See Figure 2126 shows the Create Index General page. To create a function-based
index based on an XPath expression follow these steps:
1. Provide the owner and name of the index. Under Name enter the name of the
required index. Under Schema select the owner of the index from the
drop-down list.
2. Under Index On, select Table.
3. Under the lower Schema select the table owner from the drop-down list.
Creating Structured Storage Infrastructure Based on XML Schema
Managing Oracle XML DB Using Oracle Enterprise Manager 21-43
4. Under Table, select either the XMLType table or table with XMLType column
from the drop-down list.
You can also enter an alias for a column expression. You can specify this alias
inside your function-based index statement.
5. For tables withXMLType columns, rst click the lower left-hand + icon. This
creates a new row for you to enter your extract XPath expression under Table
Columns.
6. For XMLType tables, a new empty row is automatically created for you to
create your extract XPath expression under Table Columns.
7. Datatype defaults to Column Expression. You do not need to change this.
Creating Structured Storage Infrastructure Based on XML Schema
21-44 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2126 Enterprise Manager: Creating a Function-Based Index Based on XPath
Expressions
Loading XML Data into Oracle XML DB 22-1
22
Loading XML Data into Oracle XML DB
This chapter describes how XML data can be loaded into Oracle XML DB using
SQL*Loader.
It contains the following sections:
I Loading XMLType Data into Oracle9i Database
I Using SQL*Loader to Load XMLType Columns
Loading XMLType Data into Oracle9i Database
22-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Loading XMLType Data into Oracle9i Database
In Oracle9i Release 1 (9.0.1) and higher, both Export/Import utilities and
SQL*Loader support XMLType as a column type. In other words, if your table has a
column of type XMLType, it can be properly Exported and Imported from and to
Oracle9i database, and you can load XML data into that column using SQL*Loader.
Restoration
In the current release, Oracle XML DB Repository information is not exported when
user data is exported. This means that the resources and all information is not
exported.
Using SQL*Loader to Load XMLType Columns
XML columns are columns declared to be of type XMLType.
SQL*Loader treats XML columns as if they are CLOBs. All methods described in the
following sections for loading LOB data from the primary datale or from
LOBFILEs are applicable to loading XML columns.
Because LOBs can be quite large, SQL*Loader is able to load LOB data from either a
primary datale (in line with the rest of the data) or from LOBFILEs. This section
addresses the following topics:
I Loading LOB Data from a Primary Datale
I Loading LOB Data from an External LOBFILE (BFILE)
I Loading LOB Data from LOBFILEs
I Loading LOB Data from a Primary Datale
To load internal LOBs (BLOBs, CLOBs, and NCLOBs) or XML columns from a
primary datale, you can use the following standard SQL*Loader formats:
See Also: Oracle9i Database Utilities
See Also: Oracle9i Database Utilities
Note: You cannot specify an SQL string for LOB elds. This is true
even if you specify LOBFILE_spec.
Using SQL*Loader to Load XMLType Columns
Loading XML Data into Oracle XML DB 22-3
I Predetermined size elds
I Delimited elds
I Length-value pair elds
These formats is described in the following sections and in Oracle9i Database
Utilities.
LOB Data in Predetermined Size Fields
This is a very fast and conceptually simple format in which to load LOBs.
Note: Because the LOBs you are loading may not be of equal size, you can use
whitespace to pad the LOB data to make the LOBs all of equal length within a
particular data eld.
LOB Data in Delimited Fields
This format handles LOBs of different sizes within the same column (datale eld)
without problem. However, this added exibility can affect performance, because
SQL*Loader must scan through the data, looking for the delimiter string.
As with single-character delimiters, when you specify string delimiters, you should
consider the character set of the datale. When the character set of the datale is
different than that of the control le, you can specify the delimiters in hexadecimal
(that is, hexadecimal string). If the delimiters are specied in hexadecimal
notation, the specication must consist of characters that are valid in the character
set of the input datale. In contrast, if hexadecimal specication is not used, the
delimiter specication is considered to be in the clients (that is, the control les)
character set. In this case, the delimiter is converted into the datales character set
before SQL*Loader searches for the delimiter in the datale.
Loading LOB Data from LOBFILEs
LOB data can be lengthy enough so that it makes sense to load it from a LOBFILE
instead of from a primary datale. In LOBFILEs, LOB data instances are still
considered to be in elds (predetermined size, delimited, length-value), but these
elds are not organized into records (the concept of a record does not exist within
LOBFILEs). Therefore, the processing overhead of dealing with records is avoided.
This type of organization of data is ideal for LOB loading.
There is no requirement that a LOB from a LOBFILE t in memory. SQL*Loader
reads LOBFILEs in 64 KB chunks.
In LOBFILEs the data can be in any of the following types of elds:
Using SQL*Loader to Load XMLType Columns
22-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I A single LOB eld into which the entire contents of a le can be read
I Predetermined size elds (xed-length elds)
I Delimited elds (that is, TERMINATED BY or ENCLOSED BY)
I The clause PRESERVE BLANKS is not applicable to elds read from a
LOBFILE.
I Length-value pair elds (variable-length elds)--VARRAW, VARCHAR, or
VARCHARC loader datatypes--are used for loading from this type of eld.
All of the previously mentioned eld types can be used to load XML columns.
Dynamic Versus Static LOBFILE Specifications
You can specify LOBFILEs either statically (you specify the actual name of the le)
or dynamically (you use a FILLER eld as the source of the lename). In either case,
when the EOF of a LOBFILE is reached, the le is closed and further attempts to
read data from that le produce results equivalent to reading data from an empty
eld.
You should not specify the same LOBFILE as the source of two different elds. If
you do so, typically, the two elds will read the data independently.
Importing and Exporting XMLType Tables 23-1
23
Importing and Exporting XMLType Tables
This chapter describes howyou can import and export XMLType tables for use with
Oracle XML DB.
It contains the following sections:
I Overview of IMPORT/EXPORT Support in Oracle XML DB
I Non-XML Schema-Based XMLType Tables and Columns
I XML Schema-Based XMLType Tables
I IMPORT/EXPORT Syntax and Examples
I Metadata in Repository is Not Exported During a Full Database Export
I Importing and Exporting with Different Character Sets
Overview of IMPORT/EXPORT Support in Oracle XML DB
23-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Overview of IMPORT/EXPORT Support in Oracle XML DB
Oracle XML DB supports XMLType tables and columns that can store XML data and
be based on a registered XML schema. Tables storing XML schema-based or
non-schema-based data can be imported and exported.
Resource s and Foldering Do Not Fully Support IMPORT/EXPORT
Oracle XML DB also supports a foldering mechanism in the database that provides
a le-system like paradigm to database data. This model uses pathnames and URIs
to refer to data (referred to as resources) rather than table names, column names, and
so on. This release however does not support this paradigm using
IMPORT/EXPORT.
However for resources based on a registered XML schema, the actual XMLType
tables storing the data can be exported and imported. This implies that only the
XML data is exported while the relationship in the Oracle XML DB foldering
hierarchy would be lost.
Non-XML Schema-Based XMLType Tables and Columns
XMLType tables and columns can be created without any XML schema specication
in which case the XML data is stored in a CLOB.
Data from these tables can be exported and imported in a manner similar to LOB
columns. The export dump le stores the actual XML text.
XML Schema-Based XMLType Tables
Oracle supports the export and import of XML schema-based XMLType tables. An
XMLType table depends on the XML schema used to dene it. Similarly the XML
schema has dependencies on the SQL object types created or specied for it. Thus,
export of XMLType tables or a database with XMLType tables, consists of the
following steps:
1. Exporting SQL Types During XML Schema Registration. As a part of the XML
schema registration process, SQL types can be created. These SQL types are
exported as a part of CREATE TYPE statement along with their OIDs.
2. Exporting XML Schemas. After all the types are exported, XML schemas are
exported as XML text as part of the DBMS_XMLSCHEMA.REGISTERSCHEMA
statement. In this statement:
XML Schema-Based XMLType Tables
Importing and Exporting XMLType Tables 23-3
I FORCE ag is set to true. This is necessary for out-of-order registration of
schemas during import. Since the export process does not dump XML schemas
in any particular order, a schema that imports other schemas may not
necessarily occur after them. Also, cyclical references between XML schemas
require the FORCE ag to be true for successful registration.
I GENTYPES ag is set to false. The types have already been generated in step 1.
I GENTABLES ag is set to false. The tables will be created later (step 3) along
with their OIDs. It is not possible to specify OIDs in the registerSchema
statement.
I GENBEANS ag is set to false.
I Any attributes that refer to the owner are suppressed. For example, attributes
such as SchemaOwner and SQLSchema,... This is necessary to be able to import
data from a different user.
3. Exporting XML Tables. The next step is to export the tables. Export of each
table consists of two steps:
1. The table denition is exported as a part of the CREATE TABLE statement
along with the table OID.
2. The data in the table is exported as XML text. Note that data for out-of-line
tables is not explicitly exported. It is exported as a part of the data for the
parent table.
Guidelines for Exporting Hierarchy-Enabled Tables
The following describes guidelines for exporting hierarchy-enabled tables:
I The RLS policies and path-index triggers are not exported for hierarchy-enabled
tables. This implies that when these tables are imported, they are not
hierarchy-enabled.
I Hidden columns ACLOID and OWNERID are not exported for these tables. This
is because in an imported database, the values of these columns could be
different and hence should be re-initialized.
Note: OCTs and nested tables are not exported separately. They
are exported as parts of the parent table.
IMPORT/EXPORT Syntax and Examples
23-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
IMPORT/EXPORT Syntax and Examples
The IMPORT/EXPORT syntax and description are described in Oracle9i Database
Utilities. This chapter includes additional guidelines and examples for using
IMPORT/EXPORT with XMLType data.
IMPORT/EXPORT Example Assumptions
The examples here assume that you are using a database with the following
features:
I Two users U1 and U2
I U1 has a registered local XML schema SL1. This also created a default table TL1.
I U1 has a registered global XML schema SG1. This also created a default table
TG1.
I U2 has created table TG2 based on schema SG1.
User Level Import/Export
Example 231 Exporting XMLType Data
export sytem/manager file=file1 owner=U1
This exports the following:
I Any types that were generated during schema registration of schemas SL1 and
SG1.
I Schemas SL1 and SG1
I Tables TL1 and TG1 and any other tables that were generated during schema
registration of schemas SL1 and SG1.
I Any data in any of the preceding tables.
Example 232 Exporting XMLType Tables
export sytem/manager file=file2 owner=U2
This exports the following:
I Table TG2 and any other tables that were generated during creation of TG2.
I Any data in any of the preceding tables.
IMPORT/EXPORT Syntax and Examples
Importing and Exporting XMLType Tables 23-5
Example 233 Importing Data from a File
import system/manager file=file1 fromuser=U1 touser=newuser
This imports all the data in le1.dmp to schema newuser.
Table Mode Export
An XMLType table has a dependency on the XML schema that was used to dene it.
Similarly the XML schema has dependencies on the SQL object types created or
specied for it. Importing an XMLType table requires the existence of the XML
schema and the SQL object types. When a TABLE mode export is used, only the
table related metadata and data are exported. To be able to import this data
successfully, the user needs to ensure that both the XML schema and object types
have been created.
Example 234 Exporting XML Data in TABLE Mode
exp SYSTEM/MANAGER file=expdat.dmp owner=U1 tables=TG1
This exports:
I Table TG1 and any other tables that were generated during creation of TG1.
I Any data in any of the preceding tables.
Example 235 Importing XML Data in TABLE Mode
imp SYSTEM/MANAGER file=expdat.dmp fromuser=U1 touser=U2 tables=TG1
This creates table TG1 for user U2 since U2 already has access to the globals schema
SG1 and the types that it depends on.
Note: This does not export Schema SG1 or any types that were
created during the registration of schema SG1.
Note: This does not export schema SG1 or any types that were
created during the registration of schema SG1.
Metadata in Repository is Not Exported During a Full Database Export
23-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Metadata in Repository is Not Exported During a Full Database Export
Oracle XML DB stores the metadata (and the non-schema data) for the Repository
in the XML DB database user schema. Since Oracle does not support the Repository
structure to be exported, these metadata tables and structures will not be exported
when doing a full database export.
In fact the entire XML DB user schema will be skipped during a full database export
and any database objects owned by XML DB ("XDB") will not be exported.
Importing and Exporting with Different Character Sets
As with other database objects, XML data is exported in the character set of the
exporting server. During import, the data gets converted to the character set of the
importing server.
Part VII
XML Data Exchange Using Advanced
Queueing
Part VII of this manual describes XML data exchange using Oracle Advanced
Queueing (AQ) and the AQs XMLType support. Part VII contains the following
chapter:
I Chapter 24, "Exchanging XML Data Using Advanced Queueing (AQ) and
Oracle Streams"
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-1
24
Exchanging XML Data Using Advanced
Queueing (AQ) and Oracle Streams
This chapter describes how XML data can be exchanged using Oracle Advanced
Queueing. It contains the following sections:
I What Is AQ?
I How Do AQ and XML Complement Each Other?
I Oracle Streams and AQ
I XMLType Attributes in Object Types
I Internet Data Access Presentation (IDAP)
I IDAP Architecture
I Enqueue Using AQ XML Servlet
I Dequeue Using AQ XML Servlet
I IDAP and AQ XML Schemas
I Frequently Asked Questions (FAQs): XML and Advanced Queuing
What Is AQ?
24-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
What Is AQ?
Oracle Advanced Queuing (AQ) provides database integrated message queuing
functionality. AQ:
I Enables and manages asynchronous communication of two or more
applications using messages
I Supports point-to-point and publish/subscribe communication models
Integration of message queuing with Oracle9i database brings the integrity,
reliability, recoverability, scalability, performance, and security features of Oracle9i
to message queuing. Integration with Oracle9i also facilitates the extraction of
intelligence from message ows.
How Do AQ and XML Complement Each Other?
XML has emerged as a standard format for business communications. XML is being
used not only to represent data communicated between business applications, but
also, the business logic that is encapsulated in the XML.
In Oracle9i, AQ supports native XML messages and also allows AQ operations to
be dened in the XML-based Internet-Data-Access-Presentation (IDAP) format.
IDAP, an extensible message invocation protocol, is built on Internet standards,
using HTTP and email protocols as the transport mechanism, and XML as the
language for data presentation. Clients can access AQ using this.
AQ and XML Message Payloads
Figure 241 shows an Oracle9i database using AQ to communicate with three
applications, with XML as the message payload. The general tasks performed by
AQ in this scenario are:
I Message ow using subscription rules
I Message management
I Extracting business intelligence from messages
I Message transformation
This is an intra- and inter-business scenario where XML messages are passed
asynchronously among applications using AQ.
I Intra-business. Typical examples of this kind of scenario include sales order
fulllment and supply-chain management.
How Do AQ and XML Complement Each Other?
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-3
I Inter-business processes. Here multiple integration hubs can communicate over
the Internet backplane. Examples of inter-business scenarios include travel
reservations, coordination between manufacturers and suppliers, transferring of
funds between banks, and insurance claims settlements, among others.
Oracle uses this in its enterprise application integration products. XML
messages are sent from applications to an Oracle AQ hub. This serves as a
message server for any application that wants the message. Through this
hub-and-spoke architecture, XML messages can be communicated
asynchronously to multiple loosely coupled receiving applications.
Figure 241 shows XML payload messages transported using AQ in the following
ways:
I Web-based application that uses an AQ operation over an HTTP connection
using IDAP
I An application that uses AQ to propagate an XML message over a Net*
connection
I An application that uses AQ to propagate an internet/XML message directly to
the database over HTTP or SMTP
The gure also shows that AQ clients can access data using OCI, Java, or PL/SQL.
How Do AQ and XML Complement Each Other?
24-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 241 Advanced Queuing and XML Message Payloads
AQ Enables Hub-and-Spoke Architecture for Application Integration
A critical challenge facing enterprises today is application integration. Application
integration involves getting multiple departmental applications to cooperate,
coordinate, and synchronize in order to execute complex business transactions.
AQ enables hub-and-spoke architecture for application integration. It makes
integrated solution easy to manage, easy to congure, and easy to modify with
changing business needs.
Messages Can Be Retained for Auditing, Tracking, and Mining
Message management provided by AQ is not only used to manage the ow of
messages between different applications, but also, messages can be retained for
future auditing and tracking, and extracting business intelligence.
Internet Users
Advanced
queues
Internet Access
XML-Based Internet
Transport
(HTTP(s), SMTP)
Internet
Propagation
Internet
Propagation
(Oracle
Net)
OCI, PL/SQL,
Java clients
Global Agents,
Global Subscriptions,
Global Events
MQ Series
Rules and
Transformations
Advanced
queues
Rules and
Transformations
Advanced
queues
Rules and
Transformations
Oracle
Oracle Streams and AQ
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-5
Viewing Message Content with SQL Views
AQ also provides SQL views to look at the messages. These SQL views can be used
to analyze the past, current, and future trends in the system.
Advantages of Using AQ
AQ provides the exibility of con guring communication between different
applications.
Oracle Streams and AQ
Oracle Streams (Streams) enables you to share data and events in a stream. The
stream can propagate this information within a database or from one database to
another. The stream routes specied information to specied destinations. This
provides greater functionality and exibility than traditional solutions for capturing
and managing events, and sharing the events with other databases and
applications.
Streams enables you to break the cycle of trading off one solution for another. It
enable you to build and operate distributed enterprises and applications, data
warehouses, and high availability solutions. You can use all the capabilities of
Oracle Streams at the same time.
You can use Streams to:
I Capture changes at a database. You can congure a background capture
process to capture changes made to tables, database schemas, or the entire
database. A capture process captures changes from the redo log and formats
each captured change into a logical change record (LCR). The database where
changes are generated in the redo log is called the source database.
I Enqueue events into a queue. Two types of events may be staged in a Streams
queue: LCRs and user messages. A capture process enqueues LCR events into a
queue that you specify. The queue can then share the LCR events within the
same database or with other databases. You can also enqueue user events
explicitly with a user application. These explicitly enqueued events can be LCRs
or user messages.
I Propagate events from one queue to another. These queues may be in the same
database or in different databases.
I Dequeue events. A background apply process can dequeue events. You can also
dequeue events explicitly with a user application.
XMLType Attributes in Object Types
24-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Apply events at a database. You can congure an apply process to apply all of
the events in a queue or only the events that you specify. You can also congure
an apply process to call your own PL/SQL subprograms to process events.
The database where LCR events are applied and other types of events are
processed is called the destination database. In some congurations, the source
database and the destination database may be the same.
Streams Message Queuing
Streams allows user applications to:
I Enqueue messages of different types
I Propagate messages are ready for consumption
I Dequeue messages at the destination database
Streams introduces a new type of queue that stages messages of SYS.AnyData
type. Messages of almost any type can be wrapped in a SYS.AnyData wrapper and
staged in SYS.AnyData queues. Streams interoperates with Advanced Queuing
(AQ), which supports all the standard features of message queuing systems,
including multiconsumer queues, publishing and subscribing, content-based
routing, internet propagation, transformations, and gateways to other messaging
subsystems.
XMLType Attributes in Object Types
You can now create queues that use Oracle object types containing attributes of the
new, opaque type, XMLType. These queues can be used to transmit and store
messages that are XML documents. Using XMLType, you can do the following:
I Store any type of message in a queue
I Store documents internally as CLOBs
I Store more than one type of payload in a queue
I Query XMLType columns using the operators ExistsNode() and
SchemaMatch()
I Specify the operators in subscriber rules or dequeue selectors
See Also: Oracle9i Streams, and its Appendix, Appendix A, XML
Schema for LCRs.
IDAP Architecture
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-7
Internet Data Access Presentation (IDAP)
You can access AQ over the Internet by using Simple Object Access Protocol
(SOAP). Internet Data Access Presentation (IDAP) is the SOAP specication for AQ
operations. IDAP denes XML message structure for the body of the SOAP request.
An IDAP-structured message is transmitted over the Internet using transport
protocols such as HTTP or SMTP.
IDAP uses the text/xml content type to specify the body of the SOAP request.
XML provides the presentation for IDAP request and response messages as follows:
I All request and response tags are scoped in the SOAP namespace.
I AQ operations are scoped in the IDAP namespace.
I The sender includes namespaces in IDAP elements and attributes in the SOAP
body.
I The receiver processes IDAP messages that have correct namespaces; for the
requests with incorrect namespaces, the receiver returns an invalid request
error.
I The SOAP namespace has the value:
http://schemas.xmlsoap.org/soap/envelope/
I The IDAP namespace has the value:
http://ns.oracle.com/AQ/schemas/access
IDAP Architecture
Figure 242 shows the following components needed to send HTTP messages:
I A client program that sends XML messages, conforming to IDAP format, to the
AQ Servlet. This can be any HTTP client, such as, Web browsers.
I The Web server or ServletRunner which hosts the AQ servlet that can
interpret the incoming XML messages, for example, Apache/Jserv or Tomcat.
I Oracle9i Server/Database. The AQ servlet connects to Oracle9i database to
perform operations on your queues.
See Also: Oracle9i Application Developers Guide - Advanced
Queuing
IDAP Architecture
24-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 242 IDAP Architecture for Performing AQ Operations Using HTTP
XMLType Queue Payloads
You can create queues with payloads that contain XMLType attributes. These can be
used for transmitting and storing messages that contain XML documents. By
dening Oracle objects with XMLType attributes, you can do the following:
I Store more than one type of XML document in the same queue. The documents
are stored internally as CLOBs.
I Selectively dequeue messages with XMLType attributes using the operators
existsNode(), extract(), and so on.
I Dene transformations to convert Oracle objects to XMLType.
I Dene rule-based subscribers that query message content using XMLType
operators such as existsNode() and extract().
Example 241 Using AQ and XMLType Queue Payloads: Creating the OverSeas
Shipping Queue Table and Queue and Transforming the Representation
In the BooksOnline application, assume that the Overseas Shipping site represents
the order as SYS.XMLType. The Order Entry site represents the order as an Oracle
object, ORDER_TYP.
The Overseas queue table and queue are created as follows:
BEGIN
dbms_aqadm.create_queue_table(
queue_table => 'OS_orders_pr_mqtab',
comment => 'Overseas Shipping MultiConsumer Orders queue table',
multiple_consumers => TRUE,
queue_payload_type => 'SYS.XMLTtype',
AQ Client
Oracle9i
Server
AQ Queue
Web Server
AQ
Servlet
XML
Messages
over HTTP
IDAP Architecture
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-9
compatible => '8.1');
END;
BEGIN
dbms_aqadm.create_queue (
queue_name => 'OS_bookedorders_que',
queue_table => 'OS_orders_pr_mqtab');
END;
Since the representation of orders at the Overseas Shipping site is different from the
representation of orders at the Order Entry site, a transformation is applied before
messages are propagated from the Order Entry site to the Overseas Shipping site.
/* Add a rule-based subscriber (for Overseas Shipping) to the Booked orders
queues with Transformation. Overseas Shipping handles all non-US orders: */
DECLARE
subscriber aq$_agent;
BEGIN
subscriber := aq$_agent('Overseas_Shipping','OS.OS_bookedorders_que',null);
dbms_aqadm.add_subscriber(
queue_name => 'OE.OE_bookedorders_que',
subscriber => subscriber,
rule => 'tab.user_data.orderregion = ''INTERNATIONAL''',
transformation => 'OS.OE2XML');
END;
For more details on dening transformations that convert the type used by the
Order Entry application to the type used by Overseas shipping, see Oracle9i
Application Developers Guide - Advanced Queuing the section on Creating
Transformations in Chapter 8.
Example 242 Using AQ and XMLType Queue Payloads: Dequeuing Messages
Assume that an application processes orders for customers in Canada. This
application can dequeue messages using the following procedure:
/* Create procedures to enqueue into single-consumer queues: */
create or replace procedure get_canada_orders() as
deq_msgid RAW(16);
dopt dbms_aq.dequeue_options_t;
mprop dbms_aq.message_properties_t;
deq_order_data SYS.XMLTtype;
no_messages exception;
pragma exception_init (no_messages, -25228);
Enqueue Using AQ XML Servlet
24-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
new_orders BOOLEAN := TRUE;
begin
dopt.wait := 1;
/* Specify dequeue condition to select Orders for Canada */
dopt.deq_condition := 'tab.user_data.extract(
''/ORDER_TYP/CUSTOMER/COUNTRY/text()'').getStringVal()=''CANADA''';
dopt.consumer_name : = 'Overseas_Shipping';
WHILE (new_orders) LOOP
BEGIN
dbms_aq.dequeue(
queue_name => 'OS.OS_bookedorders_que',
dequeue_options => dopt,
message_properties => mprop,
payload => deq_order_data,
msgid => deq_msgid);
commit;
dbms_output.put_line(' Order for Canada - Order: ' ||
deq_order_data.getStringVal());
EXCEPTION
WHEN no_messages THEN
dbms_output.put_line (' ---- NO MORE ORDERS ---- ');
new_orders := FALSE;
END;
END LOOP;
end;
Enqueue Using AQ XML Servlet
You can perform enqueue requests over the Internet using IDAP.
Scenario
In the BooksOnLine application, the Order Entry system uses a priority queue to
store booked orders. Booked orders are propagated to the regional booked orders
See Also: Oracle9i Application Developers Guide - Advanced
Queuing for further information about sending AQ requests using
IDAP.
Enqueue Using AQ XML Servlet
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-11
queues. At each region, orders in these regional booked orders queues are
processed in the order of the shipping priorities.
Example 243 PL/SQL (DBMS_AQADM Package)
The following calls create the priority queues for the Order Entry application.
/* Create a priority queue table for OE: */
EXECUTE dbms_aqadm.create_queue_table( \
queue_table => 'OE_orders_pr_mqtab', \
sort_list =>'priority,enq_time', \
comment => 'Order Entry Priority \
MultiConsumer Orders queue table',\
multiple_consumers => TRUE, \
queue_payload_type => 'BOLADM.order_typ', \
compatible => '8.1', \
primary_instance => 2, \
secondary_instance => 1);
EXECUTE dbms_aqadm.create_queue ( \
queue_name => 'OE_bookedorders_que', \
queue_table => 'OE_orders_pr_mqtab');
Assume that a customer, John, wants to send an enqueue request using SOAP. The
XML message will have the following format.
<?xml version="1.0"?>
<Envelope xmlns= "http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<AQXmlSend xmlns = "http://ns.oracle.com/AQ/schemas/access">
<producer_options>
<destination>OE.OE_bookedorders_que</destination>
</producer_options>
<message_set>
<message_count>1</message_count>
<message>
<message_number>1</message_number>
<message_header>
<correlation>ORDER1</correlation>
<priority>1</priority>
<sender_id>
<agent_name>john</agent_name>
</sender_id>
Enqueue Using AQ XML Servlet
24-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</message_header>
<message_payload>
<ORDER_TYP>
<ORDERNO>100</ORDERNO>
<STATUS>NEW</STATUS>
<ORDERTYPE>URGENT</ORDERTYPE>
<ORDERREGION>EAST</ORDERREGION>
<CUSTOMER>
<CUSTNO>1001233</CUSTNO>
<CUSTID>JOHN</CUSTID>
<NAME>JOHN DASH</NAME>
<STREET>100 EXPRESS STREET</STREET>
<CITY>REDWOOD CITY</CITY>
<STATE>CA</STATE>
<ZIP>94065</ZIP>
<COUNTRY>USA</COUNTRY>
</CUSTOMER>
<PAYMENTMETHOD>CREDIT</PAYMENTMETHOD>
<ITEMS>
<ITEMS_ITEM>
<QUANTITY>10</QUANTITY>
<ITEM>
<TITLE>Perl handbook</TITLE>
<AUTHORS>Randal</AUTHORS>
<ISBN>345620200</ISBN>
<PRICE>19</PRICE>
</ITEM>
<SUBTOTAL>190</SUBTOTAL>
</ITEMS_ITEM>
<ITEMS_ITEM>
<QUANTITY>10</QUANTITY>
<ITEM>
<TITLE>JDBC guide</TITLE>
<AUTHORS>Taylor</AUTHORS>
<ISBN>123420212</ISBN>
<PRICE>59</PRICE>
</ITEM>
<SUBTOTAL>590</SUBTOTAL>
</ITEMS_ITEM>
</ITEMS>
<CCNUMBER>NUMBER01</CCNUMBER>
<ORDER_DATE>08/23/2000 12:45:00</ORDER_DATE>
</ORDER_TYP>
</message_payload>
Dequeue Using AQ XML Servlet
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-13
</message>
</message_set>
<AQXmlCommit/>
</AQXmlSend>
</Body>
</Envelope>
Dequeue Using AQ XML Servlet
You can perform dequeue requests over the Internet using SOAP.
In the BooksOnline scenario, assume that the East shipping application receives
AQ messages with a correlation identier 'RUSH' over the Internet.
Example 244 Receiving and Dequeuing AQ XML Messages
The dequeue request will have the following format:
<?xml version="1.0"?>
<Envelope xmlns= "http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<AQXmlReceive xmlns = "http://ns.oracle.com/AQ/schemas/access">
<consumer_options>
<destination>ES_ES_bookedorders_que</destination>
<consumer_name>East_Shipping</consumer_name>
<wait_time>0</wait_time>
<selector>
<correlation>RUSH</correlation>
</selector>
</consumer_options>
<AQXmlCommit/>
</AQXmlReceive>
</Body>
</Envelope>
See Also: Oracle9i Application Developers Guide - Advanced
Queuing for information about receiving AQ messages using SOAP.
IDAP and AQ XML Schemas
24-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
IDAP and AQ XML Schemas
IDAP exposes a SOAP and AQ XML schema to the client. All documents sent by the
parser are validated against these schemas:
I SOAP schema http://schemas/xmlsoap.org/soap/envelope/
I AQ XML schema http://ns.oracle.com/AQ/schemas/access
Frequently Asked Questions (FAQs): XML and Advanced Queuing
Can I Store AQ XML Messages with Many PDFs as One Record?
I am exchanging XML documents from one business area to another using Oracle
Advanced Queuing. Each message received or sent includes an XML header, XML
attachment (XML data stream), DTDs, and PDF les. I need to store all this
information, including some imagery les, in the database table, in this case, the
queuetable.
Can I enqueue this message into an Oracle queue table as one record or one piece?
Or do I have to enqueue this message as multiple records, such as one record for
XML data streams as CLOB type, one record for PDF les as RAW type? Then
somehow specify that these sets of records are correlated? Also, I want to ensure
that I dequeue this.
Answer: You can achieve this in the following ways:
I You can either dene an object type with (CLOB, RAW,...) attributes, and store it
as a single message
I You can use the AQ message grouping feature and store it in multiple
messages. But the message properties will be associated with a group. To use
the message grouping feature, all messages must be the same payload type.
See Also:
I Oracle9i Application Developers Guide - Advanced Queuing,
Chapter 8, for more detail on how to implement structured
message payloads applications using either DBMS_AQADM or
Java (JDBC)
I Oracle9i Supplied PL/SQL Packages and Types Reference for more
information about DBMS_TRANSFORM.
Frequently Asked Questions (FAQs): XML and Advanced Queuing
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-15
Do I Specify Payload Type as CLOB First, Then Enqueue and Store?
[Follow on question from preceding FAQ] Do I specify the payload type as CLOB
rst, then enqueue and store all the pieces, XML message data stream, DTDs, and
PDF,... as a single message payload in the Queue table? If so, howcan I separate this
single message into individual pieces when I dequeue this message?
Answer: No. You create an object type, for example:
CREATE TYPE mypayload_type as OBJECT (xmlDataStream CLOB, dtd CLOB, pdf BLOB);
Then store it as a single message.
Can I Add New Recipients After Messages Are Enqueued?
I want to use the queue table to support message assignments. For example, when
other business areas send messages to Oracle, they do not know who should be
assigned to process these messages, but they know the messages are for Human
Resources (HR). So all messages will go to the HR supervisor.
At this point, the message has been enqueued in the queue table. The HR
supervisor is the only recipient of this message, and the entire HR staff have been
pre-dened as subscribers for this queue). Can the HR supervisor add new
recipients, namely additional staff, to the message_properties.recipient_list on the
existing the message in the queue table?
I do not have multiple consumers (recipients) when the messages are enqueued, but
I want to replace the old recipient, or add new recipients after the message has
already been in the queue table. This new message will then be dequeued by the
new recipient. Is this workable? Or do I have to remove the message from old
recipient, then enqueue the same message contents to the new recipient?
Answer: You cannot change the recipient list after the message is enqueued. If you
do not specify a recipient list then subscribers can subscribe to the queue and
dequeue the message.
In your case, the new recipient should be a subscriber to the queue. Otherwise, you
will have to dequeue the message and enqueue it again with the new recipient.
How Does Oracle Enqueue and Dequeue and Process XML Messages?
In an OTN document, it says that an Oracle database can enqueue and dequeue
XML messages and process them. How does it do this?
Frequently Asked Questions (FAQs): XML and Advanced Queuing
24-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Do I have to use XML SQL Utility (XSU) in order to insert an XML le into a table
before processing it, or can I enqueue an XML le directly, parse it, and dispatch its
messages through the AQ process? Must I use XML SQL Utility every time I want
to INSERT or UPDATE XML data into Oracle9i Database?
Answer: AQ supports enqueing and dequeing objects. These objects can have an
attribute of type XMLType containing an XML Document, as well as other interested
factored out metadata attributes that might make sense to send along with the
message. Refer to the latest AQ document, Oracle9i Application Developers Guide -
Advanced Queuing to get specic details and see more examples.
How Can I Parse Messages with XML Content from AQ Queues?
I need a tool to parse messages with XML content, from an AQ queue and then
update tables and elds in an ODS (Operational Data Store). In short, I want to
retrieve and parse XML documents and map specic elds to database tables and
columns. Is Oracle9i Text a solution?
I can use XML SQL Utility (XSU) if I go with a custom solution. My main
concentration is supply-chain. I want to get metadata information such as, AQ
enqueue/dequeue times, JMS header information,.... based on queries on certain
XML tag values. Can I just store the XML in a CLOB and issue queries using
Oracle9i Text?
Answer: The easiest way to do this is using Oracle XML Parser for Java and Java
Stored Procedures in tandem with AQ inside Oracle9i.
Regarding the use of XSU:
I If you store XML as CLOBs then you can denitely search it using Oracle9i Text
(aka interMedia Text), but this only helps you nd a particular message that
matches a criteria.
I If you need to do aggregation operations over the metadata, view the metadata
from existing relational tools, or use normal SQL predicates on the metadata,
then having it only stored as XML in a CLOB is not going to be good enough.
You can combine Oracle9i Text XML searching with some amount of redundant
metadata storage as factored out columns and use SQL statements that combine
normal SQL predicates with the Oracle9i Text CONTAINS() clause to have the best
of both.
Frequently Asked Questions (FAQs): XML and Advanced Queuing
Exchanging XML Data Using Advanced Queueing (AQ) and Oracle Streams 24-17
Can I Prevent the Listener from Stopping Until the XML Document Is Processed?
I receive XML messages from clients as messages and need to process them as soon
as they come in. Each XML document takes about 15 seconds to process. I am using
PL/SQL. One PL/SQL procedure starts the listener and dequeues the message and
calls another procedure to process the XML document. The problem is that the
listener is held up until the XML document is processed. Meanwhile messages
accumulate in the queue.
What is the best way to handle this? Is there a way for the listener program to call
the XML processing procedure asynchronously and return to listening? Java is not
an option at this point.
Answer: After receiving the message, you can submit a job using the DBMS_JOB
package. The job will be invoked asynchronously in a different database session.
Oracle9i has added PL/SQL callbacks in the AQ notication framework. This
allows you register a PL/SQL callback which is invoked asynchronously when a
message shows up in a queue.
How Can I Use HTTPS with AQ?
I need to send XML messages to suppliers using HTTPS and get a response back.
Sending a message using HTTP does not appear to much of a problem using
something like java.net.URLConnection, however there does not seem to be
anything about making a HTTPS connection. Products like Portal and OC4J seemto
have an HTTP client in the source code does Oracle/anyone have one for HTTPS
connections which can be reused?
Answer: You can use Internet access functionality of Oracle9i AQ. Using this
functionality, you can enqueue and dequeue messages over HTTP(S) securely and
transactionally using XML. You can get more details on this functionality at:
http://otn.oracle.com/products/aq
What Are the Options for Storing XML in AQ Message Payloads?
When storing XML in AQ message payloads, is there any other way of natively
doing this other than having an ADT as the payload with sys.xmltype as part of the
ADT? For example, create or replace type object xml_data_typ AS object (xml_
See Also: Chapter 7, "Searching XML Data with Oracle Text".
Frequently Asked Questions (FAQs): XML and Advanced Queuing
24-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
data sys.XMLType); My understanding is that you can ONLY have either a
RAW or ADT as message payloads.
Answer: In Oracle9.0.1, this is the only way to store XMLTypes in queues. In
Oracle9i Release 2 (9.2), you can create queues with payload and attributes as
XMLType.
Can We Compare IDAP and SOAP?
Answer: IDAP is the SOAP specication for AQ operations. IDAP is the XML
specication for AQ operations. SOAP denes a generic mechanism to invoke a
service. IDAP denes these mechanisms to perform AQ operations.
IDAP in addition has the following key properties not dened by SOAP:
I Transactional behavior. You can perform AQ operations in a transactional
manner. You transaction can span multiple IDAP requests.
I Security. All the IDAP operations can be done only by authorized and
authenticated users.
PartVIII
Oracle XML DB Case Studies
Part VIII of this manual describes Oracle XML DB case studies and contains the
following chapters:
I Chapter 25, "Oracle XML DB Case Study: Web Services Retrieve and Display
XML Documents"
I Chapter 26, "Oracle XML DB Basic Demo"
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-1
25
Oracle XML DB Case Study: Web Services
Retrieve and Display XML Documents
This chapter describes how you can access XML documents stored in Oracle XML
DB Repository through Web Services. It contains the following sections:
I XML DB Web Services Case Study: Overview
I Running XML DB Web Services Case Study: Implementation Steps
I XML DB Web Services: Calling Sequence
I XDBServices.java
I getPOXMLServlet.java
XML DB Web Services Case Study: Overview
25-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XML DB Web Services Case Study: Overview
This case study illustrates how you can use Web Services to fetch XML purchase
order (PO) documents stored in XML DB. Based on the PO number you enter from
the Browser, the application uses a Java servlet to invoke a Web Service that in turn
accesses XML DB and invokes Java API for XMLType.SQL queries are processed
and the application retrieves XML documents from XML DB as Java strings for
displaying on a Browser.
What Happens When You Enter a PO Number?
This application is invoked when you enter a PO number from a Browser. See
Figure 251.
Figure 251 Entering a Purchase Order (PO) Number
Oracle XML Db Web Services: Main Components
Figure 252 shows the main components used in the XML DB Web Services
application:
I A Browser
I SOAP client
Note:
I This case study is intended to run on Internet Explorer 6.0 or
higher.
I See also Chapter 26, "Oracle XML DB Basic Demo" for further
examples of how PO XML documents can be stored, accessed,
and processed in Oracle XML DB.
Running XML DB Web Services Case Study: Implementation Steps
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-3
I Web Services Server
I Oracle XML DB on Oracle9i
Figure 252 XML DB Web Services Case Study: Main Components
Running XML DB Web Services Case Study: Implementation Steps
Follow these steps when running the XML DB Web Services case study.
Before You Run this Case Study Demo
Before you run this XML DB Web Services case study, carry out the following:
I Ensure that you have Internet Explorer 6.0 or higher installed.
Browser
Oracle9iAS or
other SOAP client
eg. Web Server
Oracle9iAS Web
Services (SOAP)
Server
User enters PO Number
PO is retrieved and displayed in XML
1
2
SOAP/HTTP
JDBC
Oracle
XML DB
Oracle9i
Running XML DB Web Services Case Study: Implementation Steps
25-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Use Oracle9i JDeveloper to generate the Web Services les you need.
Figure 253 shows Oracle9i JDeveloper Java Bean Wizard. Use this to generate
the following three les used to access Web Services:
I WSDL document, XDBServicesService.wsdl. See
"XDBServicesService.wsdl" on page 25-4.
I Deployment Description, XDBServicesDeploymentDescriptor.dd.
See "XDBServicesDeploymentDescriptor.dd" on page 25-6.
I Web Services client stub, XDBServicesStub.java. See
"XDBServicesStub.java" on page 25-6.
Listings of these three les are provided in the following paragraphs.
Figure 253 Using Oracle9i JDeveloper Java Bean Wizard
XDBServicesService.wsdl
<?xml version="1.0" ?>
- <!-- Generated by the Oracle9i JDeveloper Web Services WSDL Generator -->
- <!-- Date Created: Mon Jul 15 16:34:24 PDT 2002-->
- <definitions name="XDBServices"
targetNamespace="http://www.oracle.com/jdeveloper/generated/XDBServices"
xmlns="http://schemas.xmlsoap.org/wsdl/"
Running XML DB Web Services Case Study: Implementation Steps
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-5
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.oracle.com/jdeveloper/generated/XDBServices"
xmlns:ns1="http://www.oracle.com/jdeveloper/generated/XDBServices/schema">
- <types>
<schema
targetNamespace="http://www.oracle.com/jdeveloper/generated/XDBServices/schema"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" />
</types>
- <message name="getPOFromNumber0Request">
<part name="PONumber" type="xsd:string" />
</message>
- <message name="getPOFromNumber0Response">
<part name="return" type="xsd:string" />
</message>
- <message name="getPOXML1Request">
<part name="PONumber" type="xsd:string" />
</message>
- <message name="getPOXML1Response">
<part name="return" type="xsd:string" />
</message>
- <portType name="XDBServicesPortType">
- <operation name="getPOFromNumber">
<input name="getPOFromNumber0Request" message="tns:getPOFromNumber0Request" />
<output name="getPOFromNumber0Response" message="tns:getPOFromNumber0Response"
/>
</operation>
- <operation name="getPOXML">
<input name="getPOXML1Request" message="tns:getPOXML1Request" />
<output name="getPOXML1Response" message="tns:getPOXML1Response" />
</operation>
</portType>
- <binding name="XDBServicesBinding" type="tns:XDBServicesPortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
- <operation name="getPOFromNumber">
<soap:operation soapAction="" style="rpc" />
- <input name="getPOFromNumber0Request">
<soap:body use="encoded" namespace="urn:POFetcher"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
- <output name="getPOFromNumber0Response">
<soap:body use="encoded" namespace="urn:POFetcher"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
Running XML DB Web Services Case Study: Implementation Steps
25-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</operation>
- <operation name="getPOXML">
<soap:operation soapAction="" style="rpc" />
- <input name="getPOXML1Request">
<soap:body use="encoded" namespace="urn:POFetcher"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
- <output name="getPOXML1Response">
<soap:body use="encoded" namespace="urn:POFetcher"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
- <service name="XDBServices">
- <port name="XDBServicesPort" binding="tns:XDBServicesBinding">
<soap:address
location="http://dlsun653.us.oracle.com:7070/soap/servlet/rpcrouter" />
</port>
</service>
</definitions>
XDBServicesDeploymentDescriptor.dd
<?xml version="1.0" ?>
- <!-- Generated by the Oracle9i JDeveloper Web Services Deployment Descriptor
Generator -->
- <!-- This Deployment Descriptor file is for use with the Oracle9iAS Release 2
/ Apache 2.2 SOAP Server SOAP Server -->
- <!-- Date Created: Mon Jul 15 16:34:26 PDT 2002-->
- <isd:service id="urn:POFetcher"
xmlns:isd="http://xml.apache.org/xml-soap/deployment">
- <isd:provider type="java" methods="getPOFromNumber getPOXML"
scope="Request">
<isd:java class="XDBServices" static="false" />
</isd:provider>
<isd:faultListener>org.apache.soap.server.DOMFaultListener</isd:faultListener>
</isd:service>
XDBServicesStub.java
package mypackage;
import oracle.soap.transport.http.OracleSOAPHTTPConnection;
import java.net.URL;
import org.apache.soap.Constants;
import org.apache.soap.Fault;
Running XML DB Web Services Case Study: Implementation Steps
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-7
import org.apache.soap.SOAPException;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;
import java.util.Vector;
import java.util.Properties;
/**
* Generated by the Oracle9i JDeveloper Web Services Stub/Skeleton Generator.
* Date Created: Mon Jul 15 16:36:21 PDT 2002
*/
public class XDBServicesStub
{
public String endpoint = "http://localhost:7070/soap/servlet/rpcrouter";
private OracleSOAPHTTPConnection m_httpConnection = null;
public XDBServicesStub()
{
m_httpConnection = new OracleSOAPHTTPConnection();
}
public String getPOFromNumber(String PONumber) throws Exception
{
String returnVal = null;
URL endpointURL = new URL(endpoint);
Call call = new Call();
call.setSOAPTransport(m_httpConnection);
call.setTargetObjectURI("urn:POFetcher");
call.setMethodName("getPOFromNumber");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
Vector params = new Vector();
params.addElement(new Parameter("PONumber", String.class, PONumber, null));
call.setParams(params);
Response response = call.invoke(endpointURL, "");
if (!response.generatedFault())
{
Parameter result = response.getReturnValue();
returnVal = (String)result.getValue();
}
else
{
Fault fault = response.getFault();
Running XML DB Web Services Case Study: Implementation Steps
25-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
throw new SOAPException(fault.getFaultCode(), fault.getFaultString());
}
return returnVal;
}
public String getPOXML(String PONumber) throws Exception
{
String returnVal = null;
URL endpointURL = new URL(endpoint);
Call call = new Call();
call.setSOAPTransport(m_httpConnection);
call.setTargetObjectURI("urn:POFetcher");
call.setMethodName("getPOXML");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
Vector params = new Vector();
params.addElement(new Parameter("PONumber", String.class, PONumber, null));
call.setParams(params);
Response response = call.invoke(endpointURL, "");
if (!response.generatedFault())
{
Parameter result = response.getReturnValue();
returnVal = (String)result.getValue();
}
else
{
Fault fault = response.getFault();
throw new SOAPException(fault.getFaultCode(), fault.getFaultString());
}
return returnVal;
}
public void setMaintainSession(boolean maintainSession)
{
m_httpConnection.setMaintainSession(maintainSession);
}
public boolean getMaintainSession()
{
return m_httpConnection.getMaintainSession();
}
Running XML DB Web Services Case Study: Implementation Steps
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-9
public void setTransportProperties(Properties props)
{
m_httpConnection.setProperties(props);
}
public Properties getTransportProperties()
{
return m_httpConnection.getProperties();
}
}
Steps for Implementing the XML DB Web Services Case Study
Figure 254 lists the steps needed to implement this application.
Figure 254 Oracle XML DB Web Services Case Study: Implementation Steps
Implement XDBServices.java 1 This invokes Java DOM API for XMLType
Implement getPOXMLServlet.java 2 This calls XDBServicesStub.java
Deploy XDBServices class to the Oracle9iAS SOAP Server 3
Deploy displayPOXML.html, getServlet, and XDBServicesStub
to any client-side Web Server with a JSP/Servlet engine
4
From your Internet Explorer browser, displays the deployed HTML page
(displayPOXML.html). Enter a PO number and click Submit Query.
5
The requested PO is retrieved and displayed in XML on your browser 6
Running XML DB Web Services Case Study: Implementation Steps
25-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
1. Run XDBServices.java
XDBServices.java accesses XML DB using Java DOM API for XMLType. This
Java Bean also:
I Formats the XMLType query string
I Connects to XML DB using a JDBC thick driver
I Retrieves an XMLType instance
I Returns the required XML PO document as a Java string
XDBServices.java implements the following actions:
1. I mports the J ava DOM API for XMLType:
import oracle.xdb.XMLType;
Java DOM API for XMLType handles all kinds of valid XML documents. It
presents to the application a uniform view of the XML document regardless of
whether it is XML schema-based or non- schema-based, whatever the
underlying storage in Oracle XML DB. Java DOM API works on client and
server.
2. Formats the resulting query string:
static String qryXMLStr = "select value(x) from purchaseorder x where
existsNode(value(x),'/PurchaseOrder[Reference=\"PO_NUMBER\"]') = 1 ";
public String getPOXML(String PONumber) throws Exception
{
String res = null;
XMLType xt = null;
XMLType xt1 = null;
3. Connects to XML DB using J DBC thick driver:
System.out.println("Driver registering...");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
System.out.println("Driver registered");
System.out.println("Connecting...");
Connection conn = DriverManager.getConnection(conStr, user, pass);
Hashtable map = (Hashtable) ((OracleConnection)conn).getTypeMap ();
map.put ("SYS.XMLTYPE", Class.forName ("oracle.xdb.XMLTypeFactory"));
System.out.println("Connection obtained");
Running XML DB Web Services Case Study: Implementation Steps
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-11
4. Retrieves anXMLType instance:
//retrieve PurchaseOrder xml documnet from database
System.out.println("Generating XMLType object ...");
xt = (XMLType)orset.getObject(1);
res = xt.getStringVal();
System.out.println("Print out xt as String ...");
System.out.println(res);
System.out.println("##Results printed");
}
5. Returns the XML PO document as a J ava string:
return res;
2. Implement GetPOXMLServlet.java
GetPOXMLServlet.java performs the following tasks:
I Accepts the users PO number entered at the Browser
I Calls XDBServiceStub.java
I Fetches the PO by invoking Web Service through XDBServices.java
I Sends the PO to be displayed on the Browser
3. Deploy XDBServices Class to the Oracle9iAS/Web Services (SOAP) Server
To run this application you need to actually deploy the
XDBServicesDeploymentDescriptor.dd.
XDBServicesDeploymentDescriptor.dd
<?xml version="1.0" ?>
- <!-- Generated by the Oracle9i JDeveloper Web Services Deployment Descriptor
Generator -->
- <!-- This Deployment Descriptor file is for use with the Oracle9iAS Release 2
/ Apache 2.2 SOAP Server SOAP Server -->
- <!-- Date Created: Mon Jul 15 16:34:26 PDT 2002-->
- <isd:service id="urn:POFetcher"
See Also: "XDBServices.java" on page 25-15 for the detailed
listing of XDBServices.java.
See Also: "getPOXMLServlet.java" on page 25-19 for the detailed
listing of getPOXMLServlet.java.
Running XML DB Web Services Case Study: Implementation Steps
25-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
xmlns:isd="http://xml.apache.org/xml-soap/deployment">
- <isd:provider type="java" methods="getPOFromNumber getPOXML"
scope="Request">
<isd:java class="XDBServices" static="false" />
</isd:provider>
<isd:faultListener>org.apache.soap.server.DOMFaultListener</isd:faultListener>
</isd:service>
Web Services: Deployed Service Information for POFetcher Service
Table 251 lists the Web Services POFetcher properties. The application uses one
of POFetchers method getPOXML. It uses XDBServices class to access Oracle
XML DB.
4. Deploy displayPOXML.html to Display Results on Client-Side Web Server
Deploy displayPOXML.html and Java classes, GetPOXMLServlet and
XDBServicesStub, to any client-side web server with a JSP/Servlet engine. See
Figure 255.
See Also: Oracle9i Java Developers Guide for a detailed description on
how to deploy a Web Service.
Table 251 urn:POFetcher Service Deployment Descriptor
Property Details
ID urn:POFetcher
Scope Application
Provider Type java
Provider Class XDBServices
Use Static Class false
Methods getPOFromNumber, getPOXML
Running XML DB Web Services Case Study: Implementation Steps
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-13
Figure 255 Results of Deploying displayPOXML.html
5. Enter a PO Number and See the Retrieved PO Displayed
From your Internet Explorer Browser window, enter a PO number and click Submit
Query. Figure 256 shows the PO number entry eld.
XML DB Web Services: Calling Sequence
25-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 256 Entering a Purchase Order (PO) Number
The requested PO is retrieved through the POFetcher Web Service and displayed
in XML on your Internet Explorer Browser.
XML DB Web Services: Calling Sequence
Figure 257 illustrates schematically XML DB Web Service applications calling
sequence.
XDBServices.java
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-15
Figure 257 XML DB Web Services: Calling Sequence
XDBServices.java
Here is full code listing for XDBServices.java. Its calling sequence was
explained in the preceding paragraphs:
/*
XDBServices.java:
DESCRIPTION:
The server Java bean that provides the XML DB web services to fetch
a user-specified PO.
MODIFIED (MM/DD/YYYY)
Geoff Lee 07/15/2002 - Cleaned up for viewlet recording
getPOXMLServlet.java is
executed and calls
XDBServicesStub.java
POFetcher Web
Services Identifier
** Enter PO number at browser:
** Requested PO is displayed at the browser in XML
SOAP Client:
XDBServices.java invokes GetPOXML method
SOAP Server:
** XML results are retrieved from XML DB Repository:
SOAP Server:
SOAP Client:
** Results are returned from the SOAP Server
** Results are returned to the SOAP Server
XDBServices.java
25-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
*/
import java.sql.*;
import java.io.*;
import java.util.Hashtable;
import oracle.jdbc.driver.*;
import oracle.sql.*;
import oracle.xdb.XMLType;
public class XDBServices
{
static String conStr = "jdbc:oracle:oci8:@";
static String user = "scott";
static String pass = "tiger";
static String qryXMLStr = "select value(x) from purchaseorder x where
existsNode(value(x),'/PurchaseOrder[Reference=\"PO_NUMBER\"]') = 1 ";
static String qryStr = "select
x.transform(xdburitype('/public/SCOTT/xsl/po.xsl').getXML()) from purchaseorder
x where existsNode(value(x),'/PurchaseOrder[Reference=\"PO_NUMBER\"]') = 1 ";
public String getPOFromNumber (String PONumber) throws Exception
{
String res = null;
XMLType xt = null;
XMLType xt1 = null;
try{
// Replace the PO_NUMBER placeholder with the input
int po_start = qryStr.indexOf ("PO_NUMBER");
String poQryStr = new StringBuffer(qryStr).replace(po_start, po_start +
9, PONumber).toString();
System.out.println("poQryStr="+ poQryStr);
System.out.println("Driver registering...");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
System.out.println("Driver registered");
System.out.println("Connecting...");
Connection conn = DriverManager.getConnection(conStr, user, pass);
Hashtable map = (Hashtable) ((OracleConnection)conn).getTypeMap ();
XDBServices.java
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-17
map.put ("SYS.XMLTYPE", Class.forName ("oracle.xdb.XMLTypeFactory"));
System.out.println("Connection obtained");
System.out.println("Statement preparing...");
OraclePreparedStatement stmt =
(OraclePreparedStatement)conn.prepareStatement (poQryStr);
System.out.println("Statement prepared");
System.out.println("Query executing...");
ResultSet rset = stmt.executeQuery(poQryStr);
System.out.println("Query executed");
OracleResultSet orset = (OracleResultSet) rset;
System.out.println("ResultSet casted");
while (orset.next())
{
//retrieve PurchaseOrder xml documnet from database
System.out.println("Generating XMLType object ...");
xt = (XMLType)orset.getObject(1);
res = xt.getStringVal();
System.out.println("Print out xt as String ...");
System.out.println(res);
System.out.println("##Results printed");
}
//close the result set, statement, and the connection
rset.close();
stmt.close();
conn.close();
}
catch( Exception e )
{
e.printStackTrace(System.out);
}
return res;
}
//
// This method returns the PO in XML format
//
public String getPOXML (String PONumber) throws Exception
XDBServices.java
25-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
{
String res = null;
XMLType xt = null;
XMLType xt1 = null;
try{
// Replace the PO_NUMBER placeholder with the input
int po_start = qryXMLStr.indexOf ("PO_NUMBER");
String poQryStr = new StringBuffer(qryXMLStr).replace(po_start, po_start
+ 9, PONumber).toString();
System.out.println("poQryStr="+ poQryStr);
System.out.println("Driver registering...");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
System.out.println("Driver registered");
System.out.println("Connecting...");
Connection conn = DriverManager.getConnection(conStr, user, pass);
Hashtable map = (Hashtable) ((OracleConnection)conn).getTypeMap ();
map.put ("SYS.XMLTYPE", Class.forName ("oracle.xdb.XMLTypeFactory"));
System.out.println("Connection obtained");
System.out.println("Statement preparing...");
OraclePreparedStatement stmt =
(OraclePreparedStatement)conn.prepareStatement (poQryStr);
System.out.println("Statement prepared");
System.out.println("Query executing...");
ResultSet rset = stmt.executeQuery(poQryStr);
System.out.println("Query executed");
OracleResultSet orset = (OracleResultSet) rset;
System.out.println("ResultSet casted");
while (orset.next())
{
//retrieve PurchaseOrder xml documnet from database
System.out.println("Generating XMLType object ...");
xt = (XMLType)orset.getObject(1);
res = xt.getStringVal();
System.out.println("Print out xt as String ...");
System.out.println(res);
System.out.println("##Results printed");
}
getPOXMLServlet.java
Oracle XML DB Case Study: Web Services Retrieve and Display XML Documents 25-19
//close the result set, statement, and the connection
rset.close();
stmt.close();
conn.close();
}
catch( Exception e )
{
e.printStackTrace(System.out);
}
return res;
}
}
getPOXMLServlet.java
Here is the detailed listing of getPOXMLServlet.java:
/*
GetPOServlet.java:
DESCRIPTION:
The Java servlet that
1. Accepts a user-specified PO number
2. Calls the client Java bean of the web service
3. Display the PO fetched from the XML DB by the 'POFetched' web service
*/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import XDBServicesStub;
public class GetPOServlet extends HttpServlet
{
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
getPOXMLServlet.java
25-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
throws ServletException, IOException
{
String PONumber = "";
String poResult = "";
try
{
PONumber = request.getParameter("PONumberSelect");
XDBServicesStub poBean = new XDBServicesStub();
poResult = poBean.GetPO(PONumber);
}
catch(Exception e)
{
e.printStackTrace();
}
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println(poResult);
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String PONumber = "";
String poResult = "";
try
{
PONumber = request.getParameter("PONumberSelect");
XDBServicesStub poBean = new XDBServicesStub();
poResult = poBean.GetPO(PONumber);
}
catch(Exception e)
{
e.printStackTrace();
}
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println(poResult);
out.close();
}
}
Oracle XML DB Basic Demo 26-1
26
Oracle XML DB Basic Demo
This chapter describes how to install and use the Oracle XML DB Basic Demo. It
contains the following sections:
I Prerequisites for Running the XML DB Basic Demo
I Installing XML DB Basic Demo
I What is Oracle XML DB?
I Starting the XML DB Basic Demo
I 0.1 XML DB Demo: Initial Setup (Run Once)
I 0.2 XML DB Demo: Resetting the Demo
I 1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
I 2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
I 3.0 XML DB Demo: How XML Files Conform to the XML Schema
I 4.0 XML DB Demo: Simple XPath Queries Against XML Documents
I 5.0 XML DB Demo: Using HTTP to Access XML Content
I 6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
I 7.0 XML DB Demo: Using Views to Access XML from Relational Tools
I 8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming
Content Using XSL
I 9.0 XML DB Demo: OracleText Examples
Prerequisites for Running the XML DB Basic Demo
26-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Prerequisites for Running the XML DB Basic Demo
You can also view and run this XML DB demonstration (demo) from:
http://otn.oracle.com/tech/xml/content.html
Before you run the XML DB Basio demo ensure you have installed the following
software:
Non-Oracle Software
Before installing and running the XML DB Basic demo, it is recommended that you
install the following non-Oracle software:
I XMLSpy: XMLSpy is an XML Schema editor from Altova. If you do not have a
license for this product you can download an evaluation copy from
http://www.altova.com.
I WS_FTP: This is a graphical FTP client from Ipswitch Software. The
demonstration is based on the LE version of this product. This can be
downloaded fromhttp://www.ftpplanet.com/download.htm.
I Microsoft cscript interpreter version 5.6 or later. You can verify the version of
cscript installed on your machine by typing the command cscript at a DOS
command prompt. The cscript processor is used to create shortcuts used during
the demonstration and to copy les from the install directory structure to the
demonstration directory structure. You should be able to download the
software from:
http://msdn.microsoft.com/downloads/default.asp?URL=/downl
oads/sample.asp?url=/msdn-files/027/001/733/msdncomposited
oc.xml
I Microsoft DOM control and XMLParser for VBScript. This is used by the
installation script to process the conguration les. At the time of writing the
latest version of this software can be downloaded from:
http://msdn.microsoft.com/downloads/default.asp?url=/downl
oads/sample.asp?url=/msdn-files/027/001/766/msdncomposited
oc.xml
I Microsoft Internet Explorer 6.0 with the latest service packs is strongly
recommended. You cannot use any version of Netscape for this demonstration.
Internet Explorer 5.5 has a number of serious page caching issues which will
mean that some sections of the demonstration will not work as expected.
Prerequisites for Running the XML DB Basic Demo
Oracle XML DB Basic Demo 26-3
I Microsoft Ofce 2000 or Microsoft Ofce XP. The demonstration makes use of
Microsoft Word. Notepad or WordPad cannot be substituted as they are not
WebDAV enabled.
Oracle Software
Before installing and running the XML DB demo, it is recommended that you install
the following Oracle software:
I Oracle Client (SQL*PLUS and Oracle Net Services Oracle9i Release 2 (9.2.0.1.0)
or later. To run this with an Oracle9i Release 2 (9.2.0.2.0) database you must
have an Oracle9i Release 2 (9.2.0.2.0) SQL*PLUS client installed. This
demonstration can be run against a remote database, however SQL*PLUS and
Oracle Net Services must be installed on the client machine.
Database SQL*NET and XML DB Conguration
Before starting the installation verify that Oracle Net Services, FTP, and HTTP are
correctly congured using the following steps:
1. Open a Windows Command Prompt session, change directory to the
basicDemo directory, and use SQL*PLUS to connect to the target database as
SYS.
c:\...\BasicDemo>sqlplus "sys@ORCL92 as sysdba"
2. Verify that the SCOTT schema has been created and that EMP and DEPT tables
exist. If the SCOTT schema is not currently loaded it can be created using:
SQL> @?\rdbms\admin\utlsampl.sql
3. Conrm that Oracle XML DB is installed using:
SQL> set long 100000
SQL> set pagesize 0
SQL> select XDBUritype('/xdbconfig.xml').getXML()
2 from dual
3 /
Note: You will need to supply an appropriate TNSAlias in place
of ORCL92.
Prerequisites for Running the XML DB Basic Demo
26-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
If XML DB is correctly installed XML DB conguration documents will be
displayed.
4. Install the XDB_UTILITY package by running the following script:
C:\...\basicDemo>sqlplus "sys@ORCL92 as sysdba"
SQL*Plus: Release 9.2.0.1.0 - Production on Fri Aug 16 12:09:42 2002
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Enter password:
Connected to:
Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the
Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production
SQL> @SQL/xdbUtility
View created.
PL/SQL procedure successfully completed.
Package created.
No errors.
Package body created.
No errors.
Synonym created.
Grant succeeded.
SQL>
5. Grant your target user execute privileges on the XDB_PORTS package:
SQL> grant execute on XDB_UTILITY to SCOTT
2 /
6. Verify the current FTP and HTTP port settings on your systemby selecting from
the XDB_DATABASE_SUMMARY view:
SQL> set long 10000
SQL> select value(x) from XDB_DATABASE_SUMMARY (x)
2 /
Prerequisites for Running the XML DB Basic Demo
Oracle XML DB Basic Demo 26-5
This should generate the following output:
VALUE(X)
-----------------------------------------------------------------
<Database Name="ORCL92" HTTP="8080" FTP="2100">
<Services>
<ServiceName>ORCL92.xp.mark.drake.oracle.com</ServiceName>
</Services>
<Hosts>
<HostName>MDRAKE-LAP</HostName>
</Hosts>
</Database>
7. If the port numbers shown are not the required ports, you can use the following
procedure to recongure the ports:
I FTP:
SQL> call XDB_UTILITY.SET_FTP_PORT(nnnn);
I HTTP:
SQL> call XDB_UTILITY.SET_HTTP_PORT(nnnn);
In these preceding examples nnnn represents the target port number. The
chosen FTP and HTTP port numbers cannot:
I Be the same value
I Be in by any other service on the system
In general the selected port numbers should not be privileged port numbers
(0-1023). After resetting the port numbers validate the new numbers have been
accepted by repeating step 4.
8. Verify that there are no HTTP or FTP port conicts with other database
instances running on the same host. You can do this by checking the status of
the database Listener using the following command:
C:\TEMP>lsnrctl status
Note: The preceding example shows the default XML DB port
numbers set when XML DB is installed. These may not match the
values in your environment.
Prerequisites for Running the XML DB Basic Demo
26-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
If you are running against a remote database you should check the status froma
DOS Command Prompt session or Telnet session attached to the remote
machine.
9. Examine the output of the status command. Verify that the Listener is
monitoring HTTP and FTP requests on the port numbers identied in step 4.
The Status command should generate output similar to the following:
LSNRCTL for 32-bit Windows: Version 9.2.0.1.0 - Production on 05-AUG-2002
16:01:37
Copyright (c) 1991, 2002, Oracle Corporation. All rights reserved.
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC0)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for 32-bit Windows: Version 9.2.0.1.0 -
Production
Start Date 03-AUG-2002 21:45:08
Uptime 1 days 18 hr. 16 min. 28 sec
Trace Level off
Security OFF
SNMP OFF
Listener Parameter File C:\oracle\ora92\network\admin\listener.ora
Listener Log File C:\oracle\ora92\network\log\listener.log
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC0ipc)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=mdrake-lap)(PORT=1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=mdrake-lap)(PORT=8080))
(Presentation=HTTP)(Session=RAW))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=mdrake-lap)(PORT=2100))
(Presentation=FTP)(Session=RAW))
Services Summary...
Service "ORCL92.xp.mark.drake.oracle.com" has 2 instance(s).
Instance "ORCL92", status UNKNOWN, has 1 handler(s) for this service...
Instance "ORCL92", status READY, has 2 handler(s) for this service...
Service "ORCL92XDB.xp.mark.drake.oracle.com" has 1 instance(s).
Instance "ORCL92", status READY, has 1 handler(s) for this service...
Service "PLSExtProc" has 1 instance(s).
Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully
If the output from the Status command shows multiple entries for the HTTP
and FTP presentations, check that no port number appears more than once. If a
given port number appears more than once, it means that two or more database
Prerequisites for Running the XML DB Basic Demo
Oracle XML DB Basic Demo 26-7
instances are trying to service that port. This is not permitted. All of the
database instances running on a given host must be assigned unique FTP and
HTTP port numbers.
10. If multiple database instances have been congured to service the same port,
ensure that unique port numbers are assigned for each instance.
Connect to each instance in turn, and repeat steps 4, 5, 6, and 7, providing
appropriate values for the FTP and HTTP ports. You can stop a database from
servicing FTP and HTTP requests by setting the port number to 0. Once all of
the database instances have been recongured, use the Listener Status
command to check that each database instance has been recongured to service
unique FTP and HTTP port numbers.
Verify SQL*NET and XML DB Conguration
Verify that Oracle Net Services (NET*8), FTP, and HTTP protocols are congured as
expected using the following procedure. This example assumes that the TNSALIAS
ORCL92 can be used to establish a connection to the target database.
1. Verify the FTP conguration by connecting to the target database using FTP
with the following commands:
C:\temp >ftp -n
ftp> open localhost 2100
Connected to mdrake-lap.
220 mdrake-lap FTP Server (Oracle XML DB/Oracle9i Enterprise Edition Release
9.2.0.1.0 - Production) ready.
ftp> user scott tiger
331 pass required for SCOTT
230 SCOTT logged in
When connecting to the FTP Server ensure that you replace:
I localhost with the name of the server hosting the database instance
I 2100 with the value of the target FTP port.
2. Retrieve the contents of databaseSummary.xml le using the following
commands:
ftp> get /sys/databaseSummary.xml
200 PORT Command successful
150 ASCII Data Connection
<Database Name="ORCL92" HTTP="8080"
Installing XML DB Basic Demo
26-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
FTP="2100"><Services><ServiceName>ORCL92.xp.mark.drake.oracle.com</ServiceNa
me></Services><Hosts><HostName>MDRAKE-LAP</HostName></Hosts></Database>226
ASCII Transfer Complete
ftp: 183 bytes received in 0.01Seconds 18.30Kbytes/sec.
ftp>
3. Verify the HTTP conguration by launching Internet Explorer and entering the
URL contained in the HTTP tag into the address bar. For example:
http://MDRAKE-LAP:8080/sys/databaseSummary.xml
The Browser will prompt for a username and password. Enter the name and
password of the database user that will be used when running the XML DB
Basic Demo. If the HTTP conguration is correct the Browser should display the
contents of the le:
- <Database Name="ORCL92" HTTP="8080" FTP="2100">
- <Services>
<ServiceName>ORCL92.xp.mark.drake.oracle.com</ServiceName>
</Services>
- <Hosts>
<HostName>MDRAKE-LAP</HostName>
</Hosts>
</Database>
Installing XML DB Basic Demo
To install XML DB Basic Demo unzip the le XDBBasicDemo.zip into a folder of
your choice. When you unzip the installation le it creates folder basicDemo/.
This folder contains a sub-folder install/. which in turn contains le
install.vbs. install.vbs installs the XML DB Basic Demo.
Open a DOS Command Prompt session in the basicDemo/ directory. The
following information is required in order to install this XML DB demonstration:
I The correct path for the client side ORACLE_HOME.
I The name of a TNSALIAS that can be used to establish an Oracle Net Services
connection to the target database.
I The hostname and port numbers required to establish HTTP and FTP
connections to the target database.
I The username and password for a user who has been granted CONNECT and
RESOURCE privileges on the target database.
Installing XML DB Basic Demo
Oracle XML DB Basic Demo 26-9
I The correct path to the installed copy of WS_FTP.
I The correct path to the installed copy of Microsoft Word.
Editing installParameters.xml
install/ folder also contains le installParameters.xml that drives the
installation process. This le contains arguments used to tailor the installation.
1. Edit tinstallParameters.xml using a text or XML editor. The le is simple
enough that it can easily be edited in Notepad. The le has the following
format:
<demoConfig>
<oracleHome>c:\oracle\ora92</oracleHome>
<oracleUser>SCOTT</oracleUser>
<oraclePassword>TIGER</oraclePassword>
<oracleSID>ORCL92</oracleSID>
<sqlPort>1521</sqlPort>
<listenerName>LISTENER</listenerName>
<hostName>localhost</hostName>
<httpPort>8080</httpPort>
<ftpPort>2100</ftpPort>
<msWordPath>
c:\Program Files\Microsoft Office\Office\WINWORD.EXE
</msWordPath>
<ftpPath>c:\Program Files\WS_FTP\WS_FTP95.exe</ftpPath>
<shortCutFolderName>XML DB Basic Demo</shortCutFolderName>
</demoConfig>
2. Make any changes required. Pay special attention to the values for:
I <oracleHome>
I <oracleSID>
I <httpPort>
I <ftpPort>
3. Save the le. After editing installationParameters.xml le verify that
the le still contains well-formed XML by opening it in Internet Explorer.
Running the Installation Script
Carry out these steps to run the XML DB demo installation script:
Installing XML DB Basic Demo
26-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
1. Run the installation script by double-clicking the install.vbs script. See
Figure 261. The script prompts you for conrmation before starting the
conguration process:
Figure 261 Prompting You for Conrmation
2. Click OK to congure the demo.
At the end of the installation process the script will report installation complete.
Figure 262 Installation Complete
3. Click OK to complete installation of the demonstration.
Note: If it turns out that the values supplied using
installParameters.xml were not correct, they can be correct by
editing the le and then re-executing the install.vbs script.
What is Oracle XML DB?
Oracle XML DB Basic Demo 26-11
What is Oracle XML DB?
Oracle XML DB is the term for set of features in Oracle9i Release 2 (9.2) database
that deliver high-performance storage and retrieval of XML. These features allow
the database to absorb the W3C XML data model. The technology included with
Oracle9i Release 2 means that the database is now a native XML database in
addition to being the most complete relational database.
New Methods for Navigating and Querying XML
Oracle XML DB provides organization with a storage independent, content
independent, and programming language independent infrastructure to store and
manage XML data. It also provides new methods for navigating and querying XML
content stored inside the database. With Oracle XML DB, you get all the advantages
of relational database technology and XML technology at the same time.
Several Options for Storing XML in the Database
Oracle XML DB offers a number of options for managing howXML documents will
be stored in the database. Options include:
I Unstructured storage, where the document is simply stored as a CLOB
I Structured storage, where the XML document is shredded into a set of objects
Fully Supports XPath Access Methods
As anyone who has worked with XML quickly realizes, XML is closely tied to
hierarchical metaphors. The standard mechanism used to query or access content
contained in an XML Document is XPath. XPath is a W3C standard that denes a
language for addressing parts of an XML document. XPath uses a path-based
notation to navigate through the hierarchical structure of an XML document. When
an XML document needs to refer to another XML document, the standard way to
reference the target document is using a URL. Like XPath, URLs uses a path-based
notation to identify the document in question. Oracle XML DB provides full
support for these access methods.
Use XPath Expressions to Query and Update XML
A number of the features provided by Oracle XML DB allow you to use XPath
expressions to query and update content in XML Documents. Oracle XML DB also
includes a simple, light-weight, Repository that allows the relationships between
XML documents to be expressed using a URL. This Repository also makes it
Starting the XML DB Basic Demo
26-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
possible to access XML content using a URL. This means that you have the option
of accessing XML objects using both relational and hierarchical mechanisms.
Oracle XML DB Components
The major components of Oracle XML DB are:
I XMLType: Anative server data-type that allows the database to understand that
a column or table contains XML, in the same way that the DATE data-type
allows the database to understand that a column contains a date. XMLType also
provide methods that allow common operations such as XML schema
validation and XSL Transformation to be performed on XML content.
I XMLSchema: Oracle XML DB provides full support for the W3C XML Schema
Recommendation. Once an XML schema has been registered with Oracle XML
DB, any instance document can be validated against the XML schema. The XML
schema is also be used to dene how instance documents that conform to the
schema should be stored in the database.
I XML DB Repository: Oracle XML DB Repository makes it possible to use URLs
to dene the relationships between XML documents and to access the contents
of documents using a path based metaphor. This is important for those
applications that view XML content using a document-centric approach. Oracle
XML DB also adds native support for the HTTP, FTP, and WebDAV protocols
allowing standard clients, such as Windows Explorer and Microsoft Ofce to
directly access XML content stored in Oracle XML DB. The Repository also
provides support for basic versioning and access control based on the IETF
WebDAV standard.
I SQL/XML: Oracle XML DB also provides an implementation of many of the
operators that will incorporated into the forthcoming SQL/XML standard.
These operators fall into two categories:
I A set of operators that make it possible to query and access XML content as
part of normal SQL operation.
I A set of operators that provide an industry standard metaphor for
generating XML from the result of a SQL SELECT statement.
Starting the XML DB Basic Demo
To start the XML DBBasic Demo, open the folder XML DB Basic Demo. If the
demo has been installed correctly this folder will be located on your Desktop.
Figure 263 displays the icons you will see when you open the BasicDemo/ folder.
0.1 XML DB Demo: Initial Setup (Run Once)
Oracle XML DB Basic Demo 26-13
Figure 263 XML DB basic Demo Folder Icons
As you can see, the icons in this folder are numbered. The demonstration is given
by clicking on each of the icons in this folder in turn.
0.1 XML DB Demo: Initial Setup (Run Once)
Before giving the demonstration for the rst time you must run this script.
This script does not need to be run again unless the database is dropped and
re-created. The script does the following:
I Creates global database objects that are used elsewhere in the demonstration
0.2 XML DB Demo: Resetting the Demo
26-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Creates the /home folder,
I Sets the appropriate ACL on the folder
I Ensures that all necessary permission have been granted to the target user
Some of these operations may generate errors if the demo is run as user SCOTT. You
can ignore these.
0.2 XML DB Demo: Resetting the Demo
Prior to giving the demonstration it is necessary to run this script. This script will
remove all les under the chosen users home folder and ensure that the
environment is clean. Operations like deleteSchema() may generate errors.
These can be safely ignored.
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
This step demonstrates the native WebDAV support included as part of Oracle XML
DB. Click the 1.0 localhost icon to open a Web Folders (WebDAV) session to XML
DB Repository. You will be prompted for username and password. Enter the
appropriate database user and password and click OK. Figure 264 shows the
displayed window.
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
Oracle XML DB Basic Demo 26-15
Figure 264 XML DB on Localhost
Key Points:
I WebDAV is an IETF standard that denes a set of extensions to the HTTP
protocol that allow an HTTP Server to act as a le server for a DAV enabled
client.
I Windows Explorer can connect directly to the XML DB Repository using the
WebDAV protocol. No Oracle or Microsoft specic software has been installed
in order make this work. The location shown in the address path is an HTTP
based URL. Since Windows Explorer knows that is talking to a WebDAV server
it displays the content of the folder as a File System.
I The benet of providing WebDAV support as part of Oracle XML DB is that it
allows standard clients, which understand the WebDAV protocol, to access and
store XML content in Oracle XML DB with out requiring any special adaptors
or plugs-in technology
I From a database perspective there are no new moving pieces required. The
database and TNS listener support FTP, HTTP and WebDAV in just the same
manner as they support Oracle Net Services (NET*8). The listener receives FTP
or HTTP requests in the same way that it receives Oracle Net Services (NET*8)
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
26-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
requests and hands them off to a shared server process which services the
request.
This can be shown by opening a command window on the server machine and
issuing the command:
c:\temp> lsnrclt status
Open the home folder. This should contain a folder called SCOTT/, assuming
that SCOTT was the name of the demonstration user. Open the SCOTT/ folder.
The SCOTT/ folder should be empty. Create a new folder by using right mouse
button. Select New -> Folder.
Figure 265 Creating a New Folder
Give the new folder a clearly identiable name.
Key Points:
I End users can work with the Oracle XML DB Repository using the tools
and interfaces that they are already familiar with.
Do not close the window at this point.
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
Oracle XML DB Basic Demo 26-17
1.1 Using SQL to Make Directories
This step demonstrates that Oracle XML DB Repository can be accessed and
updated from SQL, as well as through protocols. It also shows that, when accessed
using SQL, Repository operations are transactional.
1. Execute the SQL script by clicking on the icon 1.1 Make Directories.
Figure 266 Making Directories
The script create a set of folders inside folder /home/SCOTT.
2. Do not close the SQL*PLUS session at this point.
Key Points:
I Oracle XML DB Repository SQL as well as standard protocols such as
WebDAV and FTP will be used to access and manipulate the Repository.
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
26-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I PL/SQL package DBMS_XDB can be used to perform operations on the
Repository from SQL. This means that any program that can call a PL/SQL
procedure can work with Oracle XML DB Repository.
3. Click the window containing the WebDAV view of /home/SCOTT. Click the
Refresh option. Note that the folders that were created by executing the
PL/SQL script are NOT visible, even after refreshing the display.
Key points:
I This is the expected behavior. PL/SQL operations are transactional, and the
transaction has not been committed. Consequently the changes made in the
PL/SQL session are not visible to other users.
4. Click the Window containing the SQL*PLUS session and commit the
transaction. Close the SQL*PLUS window.
5. Click the window containing the WebDAV view of /home/SCOTT. Click the
Refresh option. Note that the folders created by executing the PL/SQL script
are now visible.
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
Oracle XML DB Basic Demo 26-19
Figure 267 Executing the PL/SQL Script: Folders are Visible
6. Close the SQL*PLUS window by typing QUIT at the SQL> prompt. Close the
WebDav window.
1.2 Using FTP to Load Conguration Files
This shows how a standard FTP client can load documents into Oracle XML DB
Repository. This step assumes that you are using WS_FTP95 from Ipswitch
software. The reason this client was used is that it can be congured to make it easy
to run the demonstration. In practice any FTP client can be used. If you choose to
use WS_FTP ensure that you have a legal license.
1. Click the 1.2 Load Con guration Files icon to open the FTP Client and establish
an FTP connection to XML DB Repository.
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
26-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 268 Loading Conguration Files
2. Enter the database users password and click OK. The FTP Client will connect
to the database. The dialog in Figure 268 is displayed:
3. Enter the password for your user and click OK. After entering the password the
window in Figure 269 is displayed.
1.0 XML DB Demo: XML DB on localhost - WebDAV and FTP Support
Oracle XML DB Basic Demo 26-21
Figure 269 Displaying the FTP Client
4. Click the SCOTT folder in Local System pane, and then click the lower arrow to
transfer the SCOTT folder from the local hard drive to Oracle XML DB
Repository. If prompted to conrmthe operation do so. When the operation has
completed click Exit.
If you choose to use a different FTP tool then you need to ensure that all the
les and folders under local SCOTT folder are copied to the /home/SCOTT
folder in Oracle XML DB Repository. The local version of the SCOTT folder is
located in basicDemo\LOCAL\Configuration Files.
Key Points:
I A standard FTP Client, which has no knowledge of Oracle or the Oracle
XML DB has been used to upload a set of documents into Oracle XML DB
Repository.
I This procedure uploaded a directory tree containing an XML schema
document, an HTML page, and a couple of XSLT style sheets.
I The Oracle XML DB repository can be used to store non XML content, such
as HTML les, JPEG images, word documents etc, as well as Schema based
and non-Schema based XML content.
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
26-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
5. Close the FTP Client by clicking on the Exit button.
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
This step introduces the concept of XML Schema and Oracle XML DBs ability to
shred and store XML documents using structured storage based on SQL99 object
types. It uses XMLSpy from Altova.
Key Points:
I Oracle XML DB supports the W3C XML Schema Recommendation.
I The W3C XML Schema Recommendation provides a specication for an
XML language that can be used to dene the structure of a set of XML
documents. An XML schema denition is itself an XML document that is
compliant with a well known XMLSchema dened by the W3C, known as
the Schema for Schemas.
I XML Schema allows for strong typing of the elements and attributes in a
document. It denes 47 scalar data types. The base set of types dened by
XMLSchema can be extended using object-oriented techniques such as
inheritance and extension to dene more complex types.
I The most common usage of an XML schema is as a mechanism for
validating that a set of XML instance documents conform with the XML
Schema. Oracle XML DB can use XML schema in this manner.
I Oracle XML DB represents XML as instances of the XMLType data type. The
XMLType makes the database XML aware and provides a convenient
abstraction for storing, retrieving, querying and manipulating XML.
Oracle XML DB provides two options for storing XML in the database:
* The rst, referred to as Unstructured Storage, uses the CLOB data type to
persist the XML as a string of bytes in the database.
* The second, referred to as Structured Storage, involves shredding the
XML and then persisting the content as a set of SQL objects. These
objects are based on the SQL99 object standard.
Structured storage is only available when the XML conforms with an
XML schema. Oracle XML DB uses the XML schema to generate the set
of SQL objects required to persist the content of the instance
documents.
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
Oracle XML DB Basic Demo 26-23
Structured storage provides a number of advantages for managing
XML. These include optimized memory management, reduced storage
requirements, b-tree indexing over collections, and partial, in-place
updates. These advantages are at a cost of increased overhead during
ingestion and retrieval.
I Database administrators and Application developers can tune performance by
annotating the XML schema to control how collections are managed.
In this demo, one of the documents loaded into the database was an XML schema.
This step uses XMLSpy to demonstrate the key features of Oracle XML DBs
support for the W3C XML Schema Recommendation.
1. Click the icon to launch XMLSpy. Click the + sign next to the DTD/Schemas
entry in the Project Window. This branch should contain an item called
http://mdrake-lap:8080/home/SCOTT/xsd/purchaseOrder.xsd.
Double click this item to open it.
2. You will be prompted for the database password.
Enter the password and Click OK.
XMLSpy displays a graphical representation of the elements and types dened
by the PurchaseOrder XML schema.
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
26-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2610 XMLSpys Graphical Representation of Elements and Types Dened by
the XML Schema
3. Click the control button next to the PurchaseOrder element. Then click the +
sign next to the lineItems element, followed by the + sign next to the
lineItem element. Finally click the part element.
At this point XMLSpy displays a graphical representation of the PurchaseOrder
XML schema.
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
Oracle XML DB Basic Demo 26-25
Figure 2611 XMLSpy Displays the PurchaseOrder XML Schema
Key Points:
I XMLSpy supports both WebDAV and FTP protocols. This allows XMLSpy
to directly access content stored in Oracle XML DB.
I The global element PurchaseOrder is an instance of the complexType
PurchseOrderType. PurchaseOrderType denes a set of elements that
make up a PurchaseOrder document. One of these is LineItems which
contains a collection of LineItem elements.
I Each LineItem elements consists of two elements, Description and
Part.
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
26-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Part element has attributes Id, Quantity, and UnitPrice.
I The PurchaseOrder schema is a relatively simple XML schema that
demonstrates the key features of a typical XML document. What is being
viewed here is a graphical representation of the XML schema.
4. Click the control button on the Toolbar to switch to the textual view of the XML
schema. This displays the XML schema, in its native form. It is an XML
document that conforms to the Schema for Schema dened by the W3C XML
Schema committee.
Figure 2612 XML Schema Displayed in Native Form, an XML Document
Key Points:
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
Oracle XML DB Basic Demo 26-27
I This XML schema denes two namespaces:
* http://www.w3c.org/2001/XMLSchema, is the namespace
reserved by the W3C consortium for the Schema for Schemas. This
namespace is used to dene the structure of the XML document.
* http://xmlns.oracle.com/xdb is the namespace reserved by
Oracle for Oracle XML DB annotations schema annotations. This
namespace is used to add annotations to the schema that control how
the instance documents will be stored in the database.
The annotation mechanism is the W3C approved mechanism for adding
Vendor-specic information to a W3C XML Schema.
I Oracle XML DB can register a schema which contains no annotations. It
makes use a set of default assumptions to register the Schema. The
annotations provide the application developer or database administrator
with the ability to override these assumptions.
I Annotations can be used to override the following:
* The naming of Tables, SQL Objects and SQL Attributes.
* How collections are managed
* The mapping between XMLSchema data types and SQL data types.
I In this schema the following annotations are being used:
* The defaultTable annotation is used in the PurchaseOrder
element to dene that XML documents, compliant with this schema
will be stored in a table called PURCHASEORDER.
* The SQLType annotation is used to provide an explicit name for the
SQL Type that will be generated form the complexType
PurchaseOrderType.
5. Click the control button on the Toolbar to switch back to the graphical view of
the XML schema.
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
26-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2613 A Graphical View of XML Schema
Key Points:
I XMLSpy provides an Oracle tab that allows Oracle XML DB schema
annotations to be entered while working in graphical editing mode.
6. Click the icon next to the PurchaseOrderType complexType.
7. Do not close this window yet.
2.1 Registering XML Schema
This step demonstrates how to make Oracle XML DB aware of an XML schema. At
this point in the demonstration the XML schema has simply been stored in the
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
Oracle XML DB Basic Demo 26-29
Oracle XML DB Repository. The database is not aware of the existence of the XML
schema.
1. Execute the SQL script by clicking on the 2.1 Register XML Schema icon.
Figure 2614 Executing the dbms_xmlschema.registerSchema Script
Key Points:
I The XML schema is registered under a URL. The URL is the URL that an
XML instance document will use to identify itself as a member of the class
dened by the XML schema.
I The method for identifying an XML document as a member of the class of
documents dened by the XML schema is dened by the W3C XML
Schema Working Group.
See Also: Chapter 5, "Structured Mapping of XMLType"
2.0 XML DB Demo: XML Schema - How XML DB Shreds and Stores XML
26-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I The URL is simply a key used to associate the instance document with the
registered XML schema. Oracle XML DB does need to be able to access the
URL.
I The registerSchema() procedure is responsible for creating all of the
objects and type dened by the XML schema.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
2.2 Objects Are Created With XML Schema Registration
This step shows some of the objects created as a result of registering the XML
schema.
1. Execute the SQL script by clicking on the 2.1 Show Objects Icon.
Figure 2615 Using DESCRIBE to List Objects Created During XML Schema
Registration
3.0 XML DB Demo: How XML Files Conform to the XML Schema
Oracle XML DB Basic Demo 26-31
Key Points:
I The PurchaseOrder table is an Object table. Each row in the table is
represented by an Object. The Object in question is an XMLType.
I The table manages XML documents with a root node of PurchaseOrder.
The denition of a PurchaseOrder element is dened by the XML schema
registered under the URL
http://mdrake-lap:8080/home/SCOTT/xdb/purchaseOrder.xsd
I Scrolling the display to the right to show that each PurchaseOrder
document is stored object-relationally as an instance of the XDBPO_TYPE
object.
I The SQL attributes of the XDBPO_TYPE object are derived from the
elements and attributes dened by the complexType
PurchaseOrderType.
2. Click the XMLSpy window. Compare the SQL*PLUS description of the XDBPO_
TYPE with XMLSpys graphical representation of the complexType.
3. Close the SQL*PLUS window by typing QUIT at the SQL> prompt. Close
XMLSpy.
3.0 XML DB Demo: How XML Files Conform to the XML Schema
This step demonstrates that the sampleData folders on your local hard-drive
contain instance documents that conform with the registered XML schema.
1. Click the 3.0 Sample Files icon to open the sampleData folder. Open folder
1999. Open the folder Apr. Right click the document
ADAMS-20011127121040988PST.xml and select Open.
This should launch Internet Explorer and display the document. If the
document opens with some other application use the FolderOptions feature
of Windows Explorer to adjust the le association.
3.0 XML DB Demo: How XML Files Conform to the XML Schema
26-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2616 Displaying Document ADAMS-2011127121040988PST.xml
Key Points:
I The le is compliant with the XML schema.
I The noNamespaceSchemaLocation attribute is used to identify the
document as an instance of the class of documents dened by the XML
schema.
3.0 XML DB Demo: How XML Files Conform to the XML Schema
Oracle XML DB Basic Demo 26-33
2. Close Internet Explorer and the sampleData/1999/Apr window. Re-Open the
Demonstration Folder, located on your Windows Desktop.
3.1 Using FTP to Load Instance Documents
This step involves using FTP to copy the 1999 folder tree into Oracle XML DB
Repository. It demonstrates how Oracle XML DB recognizes the documents as
instances of the registered XML schema, and processes them accordingly.
1. Click this icon to open the FTP Client and establish an FTP connection to XML
DB Repository. Enter the database users password when prompted and click
OK. After entering the password the following window is displayed.
Figure 2617 Using FTP to Copy 1999 Structure to Oracle XML DB Repository
2. Click the 1999 folder in the Local System pane, and then click the lower arrow
to copy the 1999 folder, and all of its subfolders from the local hard drive to
the home/SCOTT/purchaseOrders folder in Oracle XML DB Repository.
When the operation has completed click Exit.
Key Points:
3.0 XML DB Demo: How XML Files Conform to the XML Schema
26-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I A standard FTP client has been used to load content directly into the Oracle
database. No additional moving parts or servers were required. This is
possible because Oracle XML DB supports FTP and HTTP/WebDAV, a set
of protocols understood by the database.
I Since the root node of each document included a
noNameSpaceSchemaLocation attribute that identied them as a
instance of the registered XML schema, the documents were shredded and
stored as a set of objects in the database.
3. Close the FTP client by clicking the EXIT button.
3.2 Using SQL to Add Constraints to XML Data
This step involves showing how you can leverage SQL functionality when storing
XML documents in Oracle XML DB. Adding constraints to the table constrains the
XML data. This step also enables full XML schema validation of the XML
documents.
Key Points:
I XML schema is powerful. This release of Oracle XML DB supports version 1.0
of the XML Schema Recommendation. However there are some fairly simple
concepts that cannot be expressed using XML schema. These include:
I Specifying that the value of an element or attribute has to be unique across
a collection of documents. In SQL terms, a simple UNIQUE constraint.
I Specifying that the value of some element or attribute must match a value
in another document, or even some non-XML schema-based data store such
as a relational table or LDAP directory.
I By using Oracle XML DB to manage XML you can leverage the power of SQL to
address these shortcomings. In SQL terms, a simple FOREIGN KEY constraint.
I Oracle XML DB does not automatically perform full schema-validation of
documents as they are inserted into the database. Full schema-validation is
optional.
I By default, Oracle XML DB performs a light weight validation of each
document. It checks that mandatory elements and attributes are
present, and that number of elements within a collection is compliant with
See Also: Chapter 4, "Using XMLType"
3.0 XML DB Demo: How XML Files Conform to the XML Schema
Oracle XML DB Basic Demo 26-35
the values dened in the XML schema, and that enumerations are
complied with.
I It does not check pattern matches, minimum lengths,... This is a
performance optimization. Schema-validation is a fairly CPU intensive
operation, and it was felt that many applications would choose to perform
full validation on the document before inserting it into the database, so it
would be sub-optimal for the database to immediately validate the
document again.
I Full XML schema-validation can be enabled on a schema by schema basis
using a CHECK CONSTRAINT or Trigger.
1. Execute the SQL script by clicking on the 3.2 Add Constraints icon.
3.0 XML DB Demo: How XML Files Conform to the XML Schema
26-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2618 Adding Constraints and Creating Triggers
Key Points:
I Currently SQL99 Object syntax has to be used when dening constraints. A
future release of Oracle XML DB will allow constraints to be dened using
more intuitive XPath expressions.
I The contents of a row in an XMLType table has to referred to as SYS_NC_
ROWINFO$ from within a Trigger.
3.0 XML DB Demo: How XML Files Conform to the XML Schema
Oracle XML DB Basic Demo 26-37
I Schema-validation is performed by invoking the schemaValidate()
method on the XMLType. Using a Trigger makes it possible to for the
validation to return meaningful error messages, and for you to catch these
errors and attempt corrective action where appropriate.
I The rst constraint ensures that the value of the element identied by the
XPath expression /PurchaseOrder/Reference is unique across all
PurchaseOrder documents stored in the PURCHASEORDER table.
I The second constraint ensures that the value of the element identied by
the XPath expression /PurchaseOrder/User can be found in the
ENAME column of the table SCOTT.EMP.
I The Trigger ensures that full XML schema-validation takes place on every
document loaded in table PURCHASEORDER.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
3.3 Using FTP to Upload XML Documents that Attempt to Violate the Constraints
This step involves using FTP to (attempt to) upload a set of documents that violate
constraints created in the previous step.
1. Click the 3.3 Violate Constraints icon to open the FTP Client and establish an
FTP connection to XML DB Repository.
2. Enter the database users password when prompted and click OK. After
entering the password the following window is displayed.
3.0 XML DB Demo: How XML Files Conform to the XML Schema
26-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2619 Opening the FTP Client to Establish an FTP Connection
3. Click the Duplicate ADA~ le in Local System pane, and then click the lower
arrow to copy the document copy to the purchaseOrders folder in Oracle
XML DB Repository:
3.0 XML DB Demo: How XML Files Conform to the XML Schema
Oracle XML DB Basic Demo 26-39
Figure 2620 FTP Error Caused From Violating the UNIQUE Constraint
When the document is uploaded the following error is displayed:
ORA-00604: error occurred at recursive SQL level 1
ORA-00001: unique constraint (SCOTT.REFERENCE_IS_UNIQUE) violated
Uploading this document resulted in a violation of the REFERENCE_IS_
UNIQUE constraint created in step 3.2. This is because the value of the node
PurchaseOrder/Reference/text() in this document is identical to the
value of the node in one of the documents that was loaded during step 3.1.
Consequently the operation fails.
4. Next, click the HACKER-200111~ le in Local System pane, and then click the
View button.
5. Click the lower arrow to copy the document copy to the purchaseOrders
folder in Oracle XML DB Repository.
Note: The value of the node /PurchaseOrder/User/text() is
HACKER.
3.0 XML DB Demo: How XML Files Conform to the XML Schema
26-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2621 FTP Error Caused From Violating the USER_IS_VALID Constraint
When the document is uploaded the following error is displayed
ORA-00604: error occurred at recursive SQL level 1
ORA-02291: integrity constraint (SCOTT.USER_IS_VALID) violated - parent key
not found
Uploading this document resulted in a violation of the USER_IS_VALID
constraint created in step 3.2. This is because the value of the node
PurchaseOrder/User/text() in this document is HACKER, and this
value was not found in the ENAME column in SCOTT.EMP. Consequently the
operation fails.
6. Next, click the Invalid Purch~ le in Local Systempane, and then click the View
button.
Note: The value of the node
/PurchaseOrder/Reference/text() is
ADAMS-20011127PST.
3.0 XML DB Demo: How XML Files Conform to the XML Schema
Oracle XML DB Basic Demo 26-41
7. Click the lower arrow to copy the document copy to the purchaseOrders
folder in Oracle XML DB Repository.
Figure 2622 FTP Error Caused From Firing the VALIDATE_PURCHASEORDER
Trigger
When the document is uploaded the following error is displayed
ORA-00604: error occurred at recursive SQL level 1
ORA-31154: invalid XML document
ORA-19202: Error occurred in XML processing
LSX-00221: "ADAMS-20011127PST" is too short (minimum length is 18)
ORA-06512: at "SYS.XMLTYPE", line 0
ORA-06512: at "SCOTT.VALIDATE_PURCHASEORDER", line 5
ORA-04088: error during execution of trigger 'SCOTT.VALIDATE_PURCHASEORDER'
Uploading this document resulted in the VALIDATE_PURCHASEORDER Trigger
being red. The XML schema=validation processing performed in the Trigger
detected that the value of the node /PurchaseOrder/Reference/text()
did not conform to the rules set out in the XML schema. The schema denes
that the minimum length of this node should be 18 characters. Since the
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
26-42 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
document is not a valid instance of the class of documents dened by the XML
schema, the operation fails.
Key Points:
I Can use constraints and triggers to enforce integrity of XML documents. By
using the database to manage XML you receive the power of SQL combined
with the exibility of XML.
I Constraints and triggers are enforced even when protocols are used to
upload content into the database.
I By storing XML documents in Oracle XML DB, organizations can bring the
Reliability, Availability, Scalability and Security of the Oracle database to
bear on XML content.
8. Close the FTP Client by clicking on the EXIT button.
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
This step demonstrates ways to execute simple XPath queries against XML
documents.
1. Execute the SQL script by clicking on the 4.0 Simple Queries icon.
See Also: Chapter 4, "Using XMLType"
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
Oracle XML DB Basic Demo 26-43
Figure 2623 Using existsNode() in the WHERE Clause to Restrict Which Documents
Are Returned
Key Points:
I Simple Queries can be stated using familiar SQL syntax.
I The existsNode() SQL/XML operator can be used in the WHERE clause
to restrict the set of documents returned by a query. existsNode()
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
26-44 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
applies an XPath expression to an XML document and returns true (1) or
false (0) depending on whether or not the document contains a node that
matches the XPath expression.
I XPath is a W3C standard for querying and accessing the content of an XML
document and is a familiar syntax to XML programmers and authors.
I The rst example shows how to nd the number of PurchaseOrder
documents by counting the number of rows in the PurchaseOrder table.
There will be one row in the table for each document.
I The second example shows how to use the existsNode() function and a
simple XPath expression to nd the number of PurchaseOrder
documents where the value of the node PurchaseOrder/User/text()
contains the value SMITH.
I The third example shows how to use the value() operator to display the
entire contents of a document stored as a row in an XMLType (object)
table. It also show how to use the existsNode() operator to restrict the
result tothe rowwhere the node /PurchaseOrder/Reference/text()
contains the value ADAMS-20011127121040988PST.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
4.1 More Complex XPath Queries on XML Documents
This example shows how to use the extractValue() clause to get the value of a
node in a document based on an XPath expression. It also shows that Oracle XML
DB is capable of evaluating complex XPath expressions that involve deep
navigation of an XML document.
1. Execute the SQL script by clicking on the 4.1 Simple Queries (2) icon.
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
Oracle XML DB Basic Demo 26-45
Figure 2624 Using extractValue() to Get a Node Value Based on an XPath
Expression
Key Points:
I The existsNode() function is used to restrict the set of documents
returned by the query to those that by that contain a lineItem element
that contains a part element with an Id attribute containing the value
037429139523.
The lineItem element occurs multiple times within each document.
I Since the XPath
/PurchaseOrder/LineItems/LineItem/Part[@Id="03742913952
3"] does not explicitly identify which occurrences to search, all instances
of the lineItem element are searched to see if they meet the specied
condition.
I The extractValue() function is used to return just the value of the node
identied by the XPath expression:
/PurchaseOrder/Reference/text()
I Oracle XML DB is able to efciently evaluate complex XPath expressions.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
26-46 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
4.2 EXPLAIN Plan of Queries on XML Tables
This step looks at the EXPLAIN plans generated by executing queries against tables
of XML documents.
1. Execute the SQL script by clicking on the 4.2 Explain Plan (1) icon.
Figure 2625 EXPLAIN Plan of Query to Retrieve XPath Node Documents
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
Oracle XML DB Basic Demo 26-47
Key Points:
I This EXPLAIN plan shows the query for retrieving documents that contain
a node identied by XPath:
/PurchaseOrder[Reference="ALLEN-2001101709512118PDT.
I The query is resolved using a UNIQUE index. The UNIQUE index was
created when the UNIQUE constraint was added to the table.
I Query Rewrite allows the XPath expression to be translated into an indexed
access. Since the XML schema for the document is known, and the storage
model derived from the XML schema is known, Oracle XML DB can
re-write the XPath expression into an object-relational SQL query against
the underlying object model.
I The Oracle Optimizer can then optimize that query and evaluate the
optimal plan for returning the result set.
Figure 2626 EXPLAIN Plan for Query Counting Number of Documents at Node
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
26-48 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Key Points:
I This EXPLAIN plan shows the query for counting the number of
documents which contain a node identied by the XPath expression
/PurchaseOrder[User="SMITH"].
I The query is resolved using a table scan. This is ne with 168 documents
that make up the sample data used in this demonstration, but not
acceptable in a real world scenario where the table could contain millions of
documents.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
4.3 Using extractValue() and an XPath Expression to Create XML Indexes
This step looks at how to use an XPath expression to create an index. You can
eliminate the table scan by building an index to support the second query in the
previous example.
1. Execute the SQL script by clicking on the 4.3 Create XML Indexes icon or
similar.
Figure 2627 Creating an Index Using extractValue() and XPath Notation
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
Oracle XML DB Basic Demo 26-49
Key Points:
I To eliminate the table scan build an index for resolving the query.
I The index is dened using the same XPath notation used to express the
query.
I The index is not a function-based index. Query Rewrite helps map the
XPath expression supplied in the CREATE INDEX statement on the
appropriate attribute(s) of the underlying object(s). A conventional B-Tree
index is then created on these attributes.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
4.4 Using EXPLAIN Plan to Determine if the Index is Being Used
This step demonstrates that the newly created index is used to resolve the query.
1. Execute the SQL script by clicking on the 4.4 Explain Plan (2) Icon.
4.0 XML DB Demo: Simple XPath Queries Against XML Documents
26-50 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2628 Running an EXPLAIN Plan to Determine if the New Index is Being Used
Key Points:
I The new index is used automatically. The application did not need
re-writing.
I For the database administrator nothing changes. The same skills are still
required. Create the indexes required to allow queries to execute efciently.
Monitor index usage. Drop indexes that are not contributing to query
performance.
5.0 XML DB Demo: Using HTTP to Access XML Content
Oracle XML DB Basic Demo 26-51
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
5.0 XML DB Demo: Using HTTP to Access XML Content
Previous steps have shown how FTP can be used to load XML content in Oracle
XML DB, and how the content can be accessed using the familiar SQL Table/Row
metaphor. This step shows how HTTP protocol can be used to access content stored
in Oracle XML DB using a Path-based (Folder/File) metaphor.
1. Click the 5.0 ADAMS-2001... icon to launch Internet Explorer and display the
target document. When prompted, enter the database username and password.
See Also: Chapter 4, "Using XMLType"
5.0 XML DB Demo: Using HTTP to Access XML Content
26-52 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2629 Using HTTP: Accessing XML Content
The PurchaseOrder document is displayed on the Browser. See Figure 2630.
5.0 XML DB Demo: Using HTTP to Access XML Content
Oracle XML DB Basic Demo 26-53
Figure 2630 PurchaseOrder XML Document is Displayed
Key Points:
I Oracle XML DB allows access to content using both the SQL-centric,
Table/Row metaphor the document-centric Folder/File metaphor.
I Content can be accessed direct from a Web Browser using a simple URL.
I Oracle XML DB provides native support for HTTP protocol. No Web
Servers, plug-in technology, adaptors or controls are required to enable this
functionality.
5.0 XML DB Demo: Using HTTP to Access XML Content
26-54 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Protocol support can be turned off if required
I Protocol support is based on the same architecture as SQL*NET shared
server mode, namely the Oracle Listener and Shared Server Mode server.
2. Do not close the Browser window at this point.
5.1 SQL Can Display the Retrieved XML Document Through XDBUriServlet
This step demonstrates that the File/Folder metaphor can be used to access content
even when working in SQL.
1. Execute the SQL script by clicking on the 5.1 Show Document(1) icon.
5.0 XML DB Demo: Using HTTP to Access XML Content
Oracle XML DB Basic Demo 26-55
Figure 2631 Accessing Content by Specifying Files/Folders
Key Points:
I Path-based access to content is also available from SQL. The XDBUriType
makes it possible to use a path-based metaphor to access content stored in
Oracle XML DB Repository.
I XDBUriType provides a set of methods that make it possible to access
different types of contents. Any path provided to XDBUriType is assumed
to originate from the root of Oracle XML DB Repository.
2. Do not close the SQL*PLUS window at this point
5.0 XML DB Demo: Using HTTP to Access XML Content
26-56 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
5.2 Editing XML Documents with WebDAV-Enabled Tools
This step illustrates Oracle XML DBs WebDAV support and how you can use
standard WebDAV-enabled tools to access and update content stored in the
Repository.
1. Click the 5.2 Edit Document icon to launch Microsoft Word and open the target
document. When prompted enter the required username and password. If
prompted for le conversion or character set conversion select the default
values recommended by Word. The document will display in Word.
Figure 2632 Using WebDAV Tools Such as Microsoft Word to Edit an XML Document
5.0 XML DB Demo: Using HTTP to Access XML Content
Oracle XML DB Basic Demo 26-57
Use Microsoft Word to edit the document. Update the value of the node
/PurchaseOrder/Actions[1]/Action/User/text() to VISHU. Be
very careful when typing the value VISHU, as later steps in the demonstration
depend on your making this change correctly. Save the changed document.
Key Points:
I Microsoft Word, or any other WebDAV-enabled product can be used to
access and update content stored in Oracle XML DB Repository. Since
Oracle and Microsoft have both chosen to support on open, industry
standard, the two products work with each other Out-of-the-Box.
I Other vendors such as Macromedia, Adobe, and Altova, have incorporated
support for the WebDAV protocol into their products. This means that all of
these products can work with content stored in Oracle XML DB Repository.
5.3 Displaying and Verifying Updates Made to XML Documents, Using SQL
This step shows that the changes made using Microsoft Word are visible from SQL.
1. If the windowfromstep 5.1 is still open simply type a / character to re-execute
the query. If the window from step 5.1 has been closed, click the 5.3 Show
Document (2) icon to execute the query.
Note: You cannot use Notepad or WordPad currently. You must
use a WebDAV aware editor such as Word/2000 or Word/XP.
5.0 XML DB Demo: Using HTTP to Access XML Content
26-58 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2633 Changes Made Using Microsoft Word Are Also Visible Using SQL!
Key Points:
I You were able to use Microsoft Word to edit content stored in Oracle XML
DB.
I Changes made using Microsoft Word are immediately visible from SQL.
Each operation performed using a DAV-based client is an independent
transaction.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
5.0 XML DB Demo: Using HTTP to Access XML Content
Oracle XML DB Basic Demo 26-59
5.4 Updating XML Documents Using SQL
This step shows how an XML Document can be updated using SQL. It shows the
use of the updateXML() function to update the contents of an XML document
stored as XMLType. It refers to the target node using an XPath expression.
1. Execute the SQL script by clicking on the 5.4 Update Document icon.
Figure 2634 Updating an XML Document Using updateXML() and an XPath
Expression in the WHERE Clause
Key Points:
I The updateXML() function can be used to update the contents of an XML
document stored as an XMLType.
See Also: Chapter 4, "Using XMLType"
Note: For this step to work correctly Step 5.2 must have been
successfully completed.
5.0 XML DB Demo: Using HTTP to Access XML Content
26-60 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I updateXML() uses an XPath expression to identify the element, attribute
or node that is to be updated.
I updateXML() works with both XML schema-based and non-schema based
content.
For XML schema-based content, Query Rewrite allows updateXML() to
perform in-place updates. If the XPath expression can be mapped onto an
attribute of one of the underlying SQL Objects the update is performed as
an SQL operation.
I updateXML() is a much more efcient way of updating XML
schema-based documents.
* When Microsoft Word updates a document, Oracle XML DB cannot tell
which parts of the document were altered. Consequently it is forced to
parse the entire document and update all of the database objects based
on the new document.
* When updateXML() updates a document, only the parts of the
document that change are updated.
* When updateXML() is used to update non-schema-based XML the
update is done by instantiating a DOM and performing the update on
the DOM. The DOMis then printed, and written back to the underlying
CLOB storage.
I Changes made with updateXML() are just like any other changes made
using SQL. They must be committed before they become visible to other
database users.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
5.5 Displaying Changes Made to an XML Document Using Both XML and SQL
This step shows the duality of the SQL and XML approaches.
1. If the windowfromstep 5.0 is still open use ctrl-refresh to reload the contents of
the Browser. If the window from step 5.1 has been closed, click the 5.5
ADAMS-200111... icon to open the Browser and display the document.
5.0 XML DB Demo: Using HTTP to Access XML Content
Oracle XML DB Basic Demo 26-61
Figure 2635 Interoperability of XML and SQL: Accessing XML Content Using SQL
Key Points:
I Both the changes made using Microsoft Word and the change made using
SQL are visible in the refreshed page.
I Oracle XML DB provide full XML/SQL duality and interoperability. XML
content can be accessed and updated using both a document-centric
le/folder metaphor, and a SQL-centric table/row metaphor.
I Changes made using one approach are available to the other approach as
soon as the transaction is committed.
2. Close the Browser Window.
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
26-62 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
This step provides more detail about Oracle XML DB Repository and shows how
SQL programmers can use RESOURCE_VIEW to query the Repository contents.
Key Points:
I Oracle XML DB repository is managed as a set of tables in the XML DB schema.
These tables contain the metadata for all documents stored in the Repository.
The XML DB Schema is a locked database account. The tables in this schema
should never be accessed directly.
I All non-XML documents, plus all non-XML schema- based XML, is stored
directly in Oracle XML DB Repository tables.
I XML schema-based XML is stored in the default tables specied when the XML
schema was registered. Typically these tables are located in the database
schema owned by the user registering the XML schema.
I The contents of the Oracle XML DB Repository are exposed to the SQL
programmer using two views: RESOURCE_VIEW and PATH_VIEW. Public
synonyms make these views available to all database users. Oracle XML DB
also provides a set of SQL functions that allow for efcient, path-based queries
against the contents of Oracle XML DB Repository.
I Oracle XML DB leverages the Oracle databases extensible indexing
capability to dene a new domain index, called the Hierarchical Index.
* This index is used to efciently resolve path-based queries against
Oracle XML DB Repository.
* The Hierarchical Index allows path-based queries to be resolved
without having to utilize expensive connect by operations.
I The default metadata maintained by Oracle XML DB is compliant with the IETF
WebDAV standard.
I WebDAV denes the set of metadata that a WebDAV compliant server must
maintain. It also denes that WebDAV client and WebDAV server will
use XML to exchange information. It does not dene howthe metadata will
be persisted by WebDAV server.
For XML DB the metadata is simply persisted as a set of XML documents
compliant with the Oracle XML DB XDBResource XML schema.
See Also: Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
Oracle XML DB Basic Demo 26-63
I There is one Resource document for each le or folder in Oracle XML DB
Repository.
I Documents stored in Oracle XML DB Repository are protected by an Access
Control Lists (ACL)- based security mechanism. To access a document a user
must be granted a minimum of READ access to the document.
I The current implementation of ACLs in Oracle XML DB is compliant with,
but not a complete implementation of the proposed WebDAV ACL
specication
I When the Repository is accessed using SQL, ACL-level security is enforced
using the database row-level security feature.
I XML DB Repository has very rudimentary versioning capabilities. A future
release of the Repository will implement DELTA-V, the WebDAV versioning
specication.
1. Execute the SQL script by clicking the 5.0 Resource_Views Query (1) icon.
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
26-64 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2636 Querying RESOURCE_VIEW Using EQUALS_PATH()
Key Points:
I The RESOURCE_VIEW provides the primary public view of Oracle XML DB
Repository. It contains 1 row for each document or folder in the Repository.
Each row contains 2 columns, RES and ANY_PATH:
* RES is an XML document containing the meta data about a document
stored in the Repository.
* ANY_PATH contains a valid path, from the root of the Repository that
the current user can use to access the document.
I RESOURCE_VIEW and PATH_VIEW can be accessed just like any other
views. For instance to count the document of documents in the
Repository simply count the number of rows in the RESOURCE_VIEW.
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
Oracle XML DB Basic Demo 26-65
* ACL-based security ensures that the query select count(*) from
RESOURCE_VIEW returns the number of documents that the user has
access to.
I Functions such as UNDER_PATH make it easy to efciently restrict a query to
a particular sub-tree of the Repository.
Figure 2637 Using EQUALS_PATH() to Retrieve Metadata About the purchaseOrder
Folder Through RESOURCE_VIEW
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
26-66 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Key Points:
I The RES column contains an XML document that conforms with the
XDBResource XML schema. This schema denes the set of metadata required
to implement the IETF WebDAV standard.
I The example uses the EQUALS_PATH() function to retrieve the metadata for
the users purchaseOrder folder.
I The available metadata includes items like DisplayName, Creator, Owner,
LastModifier, CreationDate, and ModificationDate.
I The resource can be accessed just like any other XML document stored in
Oracle XML DB. extractValue() and existsNode() can be used for
performing queries against the RESOURCE_VIEW.
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
Oracle XML DB Basic Demo 26-67
Figure 2638 Using extractValue() and UNDER_PATH() to Walk the Directory Tree
Starting at the purchaseOrder Folder
Key Points:
I extractValue() can be used to access the metadata. Operations that
involve updating the metadata, such as changing the owner of a document
can be performed using updateXML().
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
26-68 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Queries against the set of resources managed by a repository can be
performed using functions like existsNode(), UNDER_PATH() and
EQUALS_PATH().
This example uses extractValue() and UNDER_PATH() to walk the directory
tree starting from the users purchaseOrders/ folder.
1. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
6.1 XPath-Based Querying of RESOURCE_VIEWS Using Hierarchical Indexing
This demonstrates how you can query against XML DB Repository and use the
Hierarchical Index feature to efciently resolve path-based queries.
1. Execute the SQL script by clicking the 6.1 Resource View Queries (2) icon.
Figure 2639 Using Standard SQL Syntax to Search the Repository
6.0 XML DB Demo: Querying RESOURCE_VIEWS Using SQL
Oracle XML DB Basic Demo 26-69
Key Points:
I Standard SQL Syntax and operators can be used to search the Repository.
I The rst example shows the use of the SQL-like operator to search for all
XSL documents, for example, documents with a le extension of .xsl.
I The second example shows a slightly more complex WHERE clause that
searches for all documents starting with ADAMS but uses the UNDER_
PATH() function to restrict the result to those document under the users
purchaseOrders folder.
Figure 2640 Querying on RESOURCE_VIEW Joined with XML Tables to Retrieve
Metadata
Key Points:
I Oracle XML DB supports queries that involve operations on
system-maintained metadata values such as Owner or
ModificationDate, as well as XML content. This is achieved by joining
the RESOURCE_VIEW with the tables that contain the XML content.
I This example joins the PURCHASEORDER table with the RESOURCE_VIEW to
obtain a path to each row in returned by the query.
* This technique effectively generates a URL for each row in an XMLType
table returned by a query.
* Combining this approach with the Oracle XML DBs ability to service
HTTP requests greatly simplies the process of writing Web-based
applications.
7.0 XML DB Demo: Using Views to Access XML from Relational Tools
26-70 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
Figure 2641 EXPLAIN Plan Showing How Hierarchical Index Resolved Path-Based
Query Efciently
Key Points:
I The EXPLAIN plan output shows the Hierarchical Index is used to resolve
path-based queries in an efcient manner, without the use of connect-by
processing.
7.0 XML DB Demo: Using Views to Access XML from Relational Tools
This step demonstrates how tools and products that only understand the relational
view of data can access XML content managed by Oracle XML DB.
7.0 XML DB Demo: Using Views to Access XML from Relational Tools
Oracle XML DB Basic Demo 26-71
Key Points:
I There are many tools (and application developers) and products that can
access relational data, but which do not understand how data is stored in
an XML File.
I Oracle XML DB allows relational views to be dened over XML content,
making XML content available to these tools.
1. Execute the SQL script by clicking on the 7.0 Make Views icon.
Figure 2642 Creating a View Using CREATE VIEW and XPath Expressions
Key Points:
I The view is created using a simple CREATE VIEW statement that uses
XPath expressions to map text nodes or attribute values in the XML
document to columns declared in the CREATE VIEW statement.
7.0 XML DB Demo: Using Views to Access XML from Relational Tools
26-72 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I This example creates a PURCHASE_ORDER_MASTER_VIEW that contains one
row for each document in the PURCHASEORDER table.
Figure 2643 Creating Purchase_Order_Master_View with one Row for Each
Document in PurchaseOrders Table
Key Points:
I Relational views can also be used to expose the members of a collection of
elements as a set of rows.
I This example creates a view called PURCHASE_ORDER_DETAIL_VIEW that
exposes the contents of the lineitem elements as a set of rows. The view
will contain one row for each lineitem element in the PURCHASEORDER
table.
I The rst step uses the extractValue() function to generate an XML
Fragment from each document in the PURCHASEORDER table. An XML
Fragment is an XML document containing multiple root level nodes. In this
case the XML Fragment will consist of a set of lineitem nodes. The
fragment will contain one root level node for each member of the
lineitems collection.
I The next step uses the XMLSequence() function to create a separate row
from each of the root level nodes in the Fragment.
7.0 XML DB Demo: Using Views to Access XML from Relational Tools
Oracle XML DB Basic Demo 26-73
I The nal step is to use the SQL TABLE operator to turn the set of rows into
a table that can be used in the FROM clause of a SELECT statement.
I There is an implicit correlated join between the PURCHASEORDER table and
the set of rows generated by the TABLE operator.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
7.1 Relational Views of XML Act Like Other Views
This step demonstrates that relational views over XML look and behave like
relational views over other data.
1. Execute the SQL script by clicking on the 7.1 Query Views icon.
7.0 XML DB Demo: Using Views to Access XML from Relational Tools
26-74 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2644 Querying XMLType Views Using Standard SQL
Key Points:
I These are simple, basic SQL queries. The developer or end user does need
to know that content in these Views is coming from an XMLType table. The
tool or person creating the query does not need to understand the
XML-specic operators and syntax required to access XML content.
I Query Rewrite will ensure that the SQL queries are executed against the
underlying object store.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
7.0 XML DB Demo: Using Views to Access XML from Relational Tools
Oracle XML DB Basic Demo 26-75
7.2 Querying Using Rollup
This step demonstrates how using relational views over XML you can use any
SQL-based feature of the Oracle database against content managed by Oracle XML
DB.
1. Execute the SQL script by clicking the 7.2 Rollup Query icon.
Figure 2645 Applying Roll Up Queries to XML Content
Key Points:
I Oracle XML DB makes it possible to apply advanced SQL features, such as
roll-up queries to XML Content.
I The rollup feature itself is not XML aware, but the ability to create relational
views allows such features to be used for XML content.
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
26-76 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
8.0 XML DB Demo: Accessing Content Using DBUriServlet;
Transforming Content Using XSL
This step demonstrates both how you can use DBUriServlet to access content
using a Schema/Table metaphor. This also shows Oracle XML DBs ability to
perform XSL transformations.
1. Click the 8.0 DBUri and XSL Examples icon to launch Internet Explorer. If
prompted for a username and password enter the database users username
and password.
This launches Internet Explorer and uses a Repository-based URL to display the
contents of the document ADAMS-20011127121040988PST.xml. The URL
uses Oracle XML DBs HTTP Server to display the content based on a resource
in Oracle XML DB Repository.
2. Click Favorites, and then click XML DB Basic Demo
This displays a set of internet shortcuts used during the next phase of the
demonstration.
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
Oracle XML DB Basic Demo 26-77
Figure 2646 Launching Internet Explorer and a Repository-Based URL to Display
XML Content
Key Points:
I The content has been displayed based on a URL that uses a Folder/File
metaphor to identify the resource that points at the required content.
3. Do not close the Browser window at this point.
8.1 PurchaseOrder Raw XML
This step demonstrates Oracle XML DBs DBUriServlet.
1. Open the XML DB Basic Demo item in the Favorites menu and select item8.1
PurchaseOrder Raw XML. This displays the same Purchase Order document.
However this document is identied using a DBURI-based path similar to the
following:
See Also: Chapter 12, "Creating and Accessing Data Through
URLs"
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
26-78 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
http://mdrake-lap:8080/oradb/SCOTT/PURCHASEORDER/ROW
/PurchaseOrder[Reference="ADAMS-20011127121040988PST"]
?contenttype=text/xml
Figure 2647 Using DBUriServlet and DBUriType to Select Rows from an XML
Document, Based on a URL.
Key Points:
I The DBUriServlet leverages the DBUriType feature of Oracle XML DB.
The DBUriType allows a row in a table to be identied using a URL which
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
Oracle XML DB Basic Demo 26-79
consists of a Schema, Table, Row and Column. XPath like syntax allows the
URL to be extended to subset which rows in the target table match the URL.
* The DBUriType returns the selected row or rows as an XML document.
* The DBUriServlet leverages Oracle XML DBs native HTTP
capabilities to allow a Browser to use a DBUri to access any row in the
database.
I This example shows accessing a row in the PurchaseOrder XMLType
table using a DBUri. The URI consists of the following components:
* /oradb: The default mount point for the DBUriServlet
* /SCOTT: The database schema name
* /PURCHASEORDER: The table name
* /ROW: The default Row separator
* /PurchaseOrder: The root node of the document in question
* [Reference="ADAMS-20011127121040988PST"]: An XPath
expression that determines which row or rows should be returned.
* ?contenttype=text/xml: The contenttype parameter allows the
developer to specify the MIME type to be returned to the Browser.
I For an XMLType table or view, the DBUriServlet allows an XPath
expression to be used to determine which rows in the table are returned.
This is very similar in functionality to the W3C XPOINTER
Recommendation.
I For a Relational table or view the DBUriServlet allows an XPath-like
expression, based on the columns in the table, to determine which rows
should be included in the resulting document.
2. Do not close the Browser window at this point.
8.2 Using Standard XSL Style Sheets to Transform XML Documents to HTML
This step shows a Standard style sheet that can be used to transform the
PurchaseOrder document from XML to HTML.
1. Open the XML DB Basic Demo item in the Favorites menu and select item8.2
PurchaseOrder XSL Style sheet. This displays an XSL style sheet that can be
used with the Purchase Order XML documents.
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
26-80 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2648 Style Sheet for use with PurchaseOrder XML Documents
Key Points:
I Most end-users do not want to deal with XML. They want to see
information formatted into HTML The standard mechanism for converting
an XML document into HTML is a Style sheet, compliant with the W3C
XSLT Recommendation.
I The Style sheet is a standard W3C XSL Style sheet. There is nothing
Oracle-specic about this Style sheet.
I To create HTML from XML, an XSLT processor is required. The processor
takes the XML, and the instructions contained in the Style sheet and uses
them to generate HTML.
XSL allows display logic to be separated from processing logic. Different
Style sheets can be used to format a given XML document different ways.
For instance one Style sheet could format a document for display in a PC
Browser, another Style sheet could format the same document for display
on a WAP-enabled phone.
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
Oracle XML DB Basic Demo 26-81
In this example the Style sheet was loaded into Oracle XML DB Repository so
that the database can perform the XSLT processing.
2. Do not close the Browser window at this point.
8.3 Transforming PurchaseOrder Using XSLT
This step shows Oracle XML DBs Style sheet processor being used to transform a
PurchaseOrder document from XML into HTML.
Key Points:
I Oracle XML DB includes a XSLT style sheet processing engine linked to the
database.
I The XSLT processor can leverage Oracle XML DB performance optimizations
such as the Lazily Loaded DOM. These optimizations greatly reduce the
amount of parsing and memory overhead associated with performing XSL
Transformation.
I In conventional XSL processing the rst step is to create a DOM, (the in
memory representation of an XML document). The DOM is then passed to XSL
processor which uses the DOM API to obtain the information contained in the
document and format it as HTML. There are a number of problems associated
with the standard method of performing XSL transformation.
I The act of creating the DOM can be both processor and memory intensive.
The In-Memory representation of an XML document can be several times
the size of the original document.
I For entire document must be parsed and converted into a DOM structure
before XSLT processing can commence. This can be very in-efcient if only
a small part of the document is going to be included in the generated
output.
I For XML schema-based content the XML schema must also be parsed and
loaded into memory.
I Oracle XML DB addresses these issues. When transforming XML schema-based
content the XSLT processor is presented with an instance of the Oracle XML DB
lazily loaded virtual DOM. The XML DB DOM allows the XSLT processor to
See Also: Chapter 6, "Transforming and Validating XMLType
Data"
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
26-82 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
use the conventional DOM APIs to perform the transformation. However the
XML DB DOM has a number of advantages over a traditional DOM:
I The DOM is loaded directly from disk. No parsing is required in order to
load the DOM. DOM memory usage is reduced, as only the part of the
document being processed is loaded into the DOM.
I As processing continues other parts of the document will be loaded on
demand. A paging mechanism is used to manage the overall size of the
DOM.
I Any XML schemas will be accessed from the Oracle XML DB schema cache.
1. Open the XML DB Basic Demo item in the Favorites menu and select item8.3
PurchaseOrder XSL Transform This displays the result of transforming the
PurchaseOrder document with the XSL style sheet.
Figure 2649 Transforming the XML PurchaseOrder Document Using the XSL Style
sheet
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
Oracle XML DB Basic Demo 26-83
Key Points:
I Style sheet processing is performed by XSLT processor incorporated into
the database.
I The Stylesheet processor can be invoked from DBUriServlet by supplying
the transform=parameter as part of the URL. The value of the transform
parameter is a URL that identies the Style sheet to be used when
performing the transformation.
I The XSLT processor can also be invoked from SQL using XMLTypes
transform() method or the SQL xmltransform() function. The
transformation is performed by Oracle XML DB XSLT processor at the
database level.
I Style sheet processing is able to leverage Oracle XML DB optimizations
such as the Lazily Loaded DOM. This makes XSLT processing much more
efcient.
I The preceding example includes all of the information from the target
document. However image generated is a summary document based on
XSLT transformation of XML documents.
* In a conventional system, each document required would have to
parsed, converted into a DOM and then processed.
* With Oracle XML DB, assuming the summary did not contain
information fromthe lineItem elements, these would never be loaded
as part of the XSLT processing.
2. Do not close the Browser window at this point.]
8.4 Creating XMLType Views with SQL
This step introduces you to SQL/XML (SQLX) operators and functions used to
create XMLType views and generate XML from an SQL query.
1. Open the XML DB Basic Demo item in the Favorites menu and select item8.4
DEPTVIEW De nition.
2. This displays an HTML page showing the denition of the DEPTVIEW XMLType
view.
See Also: Chapter 11, "XMLType Views"
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
26-84 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2650 HTML Page Showing XMLType View DEPTVIEW
Key Points:
I SQL/XML is an ANSI/ISO standard. It falls into two main sections.
I The rst provides functions and operators for inserting, querying and
updating XML documents as part of a SQL operation, and for including an
XML document, or parts of an XML document in the resultset returned by a
SQL operation
I The second provides functions for generating an XML document from a
query against relational tables.
I The SQL/XML standard is being developed by Oracle, IBM, Microsoft, and
other interested parties.
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
Oracle XML DB Basic Demo 26-85
I This example shows how to use SQL/XML functions to generate an XMLType
view, which provides a persistent XML View of the contents of the EMP and
DEPT tables in the SCOTT sample schema.
I The view will consist of a collection of Department nodes. Each Department
will contain elements DNAME and LOC, as well as collection of Employee nodes
containing the details of each employee in the department.
I The SQL/XML operators have been designed to make it easy to generate any
shape of XML from a SQL result set.
I XMLForest() is so named because it contains a collection of Trees.
I Unlike other vendors, Oracle takes the SQL /XML operators into account when
determining which plan to use to resolve a query. This may result in the query
plan selected when generating XML to be different fromthe query plan selected
when generating the equivalent tabular resultset.
I Other vendors implement SQL/XML by creating a DOM based on the
SQL/XML operators, and then executing a conventional relational query,
forcing the result into the DOM, and then printing the DOM. This is much less
efcient for a number of reasons:
I The database is not able to consider the shape of the required output when
determining the query plan
I The tabular result set has to be forced into a DOM structure before the
required result set can be generated. This results in signicant memory and
processing overhead.
3. Do not close the Browser window at this point.
8.5 Displaying DEPTVIEW Raw XML Using DBUriServlet
This step shows how to use DBUriServle to display DEPTVIEW contents.
1. Open the XML DB Basic Demo item in the Favorites menu and select item8.5
Display DEPTVIEW. This displays the contents of the DEPTVIEW XMLType
view.
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
26-86 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2651 DEPTVIEW Contents
Key Points:
I The XMLType view exposes DEPT and EMP as a single XML document.
I There is one <ROW> element in the generated document for each row selected
fromDEPT table.
I The shape of the XML document is dened by the SQL/XML operators used in
the view denition.
8.6 Transforming DEPTVIEW From XML to HTML Using a Style Sheet
This step shows how to use a Style sheet to transform a PurchaseOrder document
from XML to HTML.
1. Open the XML DB Basic Demo item in the Favorites menu and select item8.6
DEPTVIEW style sheet This displays an XSL style sheet that can be used with
viewDEPTVIEW.
See Also: Chapter 12, "Creating and Accessing Data Through
URLs"
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
Oracle XML DB Basic Demo 26-87
Figure 2652 XSL Style Sheet for Use with DEPTVIEW
Key Points:
I The style sheet is a standard W3C compliant XSLT style sheet. There is nothing
Oracle-specic about it.
Do not close the Browser window at this point.
8.7 Displaying the Transformed DEPTVIEW After XSL Transformation
This step shows how you can use a Style sheet to transform a PurchaseOrder
document from XML to HTML.
1. Open the XML DB Basic Demo item in the Favorites menu and select item8.7
DEPTVIEWwith XSL Transformation. This displays the result of transforming
the PurchaseOrder document with the XSL style sheet.
8.0 XML DB Demo: Accessing Content Using DBUriServlet; Transforming Content Using XSL
26-88 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Figure 2653 A Style Sheet for Transforming PurchaseOrder Documents from XML to
HTML
Key Points:
I Oracle XML DB makes it easy to display the contents of relational tables
such as DEPT and EMP as an HTML document.
I Use the SQL/XML operators to create an XMLType view that format the
contents of the relational tables as an XML document then apply an XSLT
style sheet to transform the XML document into HTML.
I No procedural coding, servlets, or other application components need be
created or installed to achieve this functionality.
2. Close the Browser window.
9.0 XML DB Demo: OracleText Examples
Oracle XML DB Basic Demo 26-89
9.0 XML DB Demo: OracleText Examples
This step illustrates how OracleText functionality can be applied to XML content
stored in Oracle XML DB using Structured Storage techniques.
1. Execute the SQL script by clicking on the 9.0 Oracle Text Examples icon.
Figure 2654 Searching a PurchaseOrders Table by Using Oracle Texts contains()
Operator
Key Points:
I Oracle XML DB allows Oracle Text indexes to be created on XML content
stored in the database using Structured Storage Techniques.
I Two kinds o OracleText indexes are allowed:
9.0 XML DB Demo: OracleText Examples
26-90 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
* ctxsys.ctxxpath. This can be used to speed up the existsNode()
function.
* ctxsys.conte. This allows for a full text search on XML content.
I By default existsNode() looks for a B-Tree or function-based index and
then is used to resolve the query. If no such index exists it performs a
functional evaluation of each document in the table to see if it contains a
node that matches the supplied XPath expression.
I If a ctxsys.ctxxpath index has been created then existsNode() uses
this index as a primary lter when resolving an XPath expression that
cannot be resolved with a B-Tree or function-based Index. This is much
faster than performing a functional evaluation of every document in the
table.
I The example shows creating a full text (ctxsys.context) index on the
PURCHASEORDER table and then using the Oracle Text contains()
function to perform a Text-based search over the PurchaseOrder XML
documents.
2. Close the SQL*PLUS window by typing QUIT at the SQL> prompt.
See Also: Chapter 7, "Searching XML Data with Oracle Text"
Installing and Conguring Oracle XML DB A-1
A
Installing and Configuring Oracle XML DB
This appendix describes the ways you can manage and congure your Oracle XML
DB applications. It contains the following sections:
I Installing Oracle XML DB
I Installing or Reinstalling Oracle XML DB from Scratch
I Upgrading an Existing Oracle XML DB Installation
I Upgrading XML DB From Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
I Conguring Oracle XML DB
I Oracle XML DB Conguration File, xdbcong.xml
I Oracle XML DB Conguration Example
I Oracle XML DB Conguration API
Installing Oracle XML DB
A-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Installing Oracle XML DB
You will need to install Oracle XML DB under the following conditions:
I "Installing or Reinstalling Oracle XML DB from Scratch" on page A-2
I "Upgrading an Existing Oracle XML DB Installation" on page A-5
Installing or Reinstalling Oracle XML DB from Scratch
You can perform a new installation of Oracle XML DB with or without Database
Conguration Assistant (DBCA):
Installing a New Oracle XML DB with DBCA
Oracle XML DB is part of the seed database and installed by DBCA as part of
database installation by default. No additional steps are required to install Oracle
XML DB, however, if you choose to install Customized database, you can
congure Oracle XML DB tablespace and FTP, HTTP, and WebDAV port numbers.
By default DBCA performs the following tasks:
I Creates an Oracle XML DB tablespace for Oracle XML DB Repository
I Enables all protocol access
I Congures FTP at port 2100
I Congures HTTP/WebDAV at port 8080
The Oracle XML DB tablespace holds the data that is stored in Oracle XML DB
Repository. This includes data that is stored in the Repository using:
I SQL, for example using resource_view and path_view
I Protocols such as FTP, HTTP, and WebDAV
You can store data in tables outside this tablespace and access the data through the
Repository by having REFs to that data stored in the tables in this tablespace.
CAUTION: The Oracle XML DB tablespace should not be
dropped. If dropped it renders all Repository data inaccessible.
Installing or Reinstalling Oracle XML DB from Scratch
Installing and Conguring Oracle XML DB A-3
Dynamic Protocol Registration Registers FTP and HTTP Services with Local Listener
Oracle XML DB installation, includes a dynamic protocol registration that registers
FTP and HTTP services with the local Listener. You can perform start, stop, and
query with "lsnrctl". For example:
I start: lsnrctl start
I stop: lsnrctl stop
I query: lsnrctl status
Changing FTP or HTTP Port Numbers
To change FTP or HTTP port numbers, update the tags <ftp-port> and
<http-port> in le, /xdbconfig.xml in Oracle XML DB Repository.
After updating the port numbers dynamic protocol registration automatically stops
FTP/HTTP service on old port numbers and starts themon newport numbers if the
local Listener is up. If local Listener is not up, restart the Listener after updating the
port numbers.
Post Installation
As explained in the previous section, Oracle XML DB uses dynamic protocol
registration to setup FTP and HTTP listener services with the local Listener. So,
make certain that the Listener is up when accessing Oracle XML DB protocols.
To allow for unauthenticated access to your Oracle XML DB Repository data
through HTTP, you must unlock the ANONYMOUS user account.
See Also: Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
for a description of how to update /xdbconfig.xml.
Note: If the Listener is running on a non-standard port (for
example, not 1521) then in order for the protocols to register with
the correct listener the init.ora le must contain a
local_listener entry. This references a TNSNAME entry that
points to the correct listener. After editing the init.ora parameter
you must regenerate the SPFILE entry using CREATE SPFILE.
Installing or Reinstalling Oracle XML DB from Scratch
A-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Installing a New Oracle XML DB Manually Without DBCA
After the database installation, you must run the following SQL scripts in
rdbms/admin connecting to SYS to install Oracle XML DB after creating a new
tablespace for Oracle XML DB Repository. Here is the syntax for this:
catqm.sql <xdb_pass> <XDB_TS_NAME> <TEMP_TS_NAME> #Create the tables and views
needed to run XML DB
For example:
catqm.sql change_on_install XDB TEMP
Reconnect to SYS again and run the following:
catxdbj.sql #Load xdb java library
Post Installation
After the manual installation, carry out these tasks:
1. Add the following dispatcher entry to the init.ora le:
dispatchers="(PROTOCOL=TCP) (SERVICE=<sid>XDB)"
2. Restart database and listener to enable Oracle XML DB protocol access.
3. To allow for unauthenticated access to your Oracle XML DB Repository data
through HTTP, you must also unlock the ANONYMOUS user account.
Reinstalling Oracle XML DB
To reinstall Oracle XML DB, run following SQL commands connecting to SYS to
drop Oracle XML DB user and tablespace:
drop user xdb cascade;
alter tablespace <XDB_TS_NAME> offline;
drop tablespace <XDB_TS_NAME> including contents;
Note: Make sure that the database is started with Oracle9i Release
2 (9.2.0) compatibility or higher.
Note: All user data stored in Oracle XML DB Repository is also
lost when you drop xdb user!
Upgrading XML DB From Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
Installing and Conguring Oracle XML DB A-5
Install Oracle XML DB manually as described in "Installing a New Oracle XML DB
Manually Without DBCA" on page A-4.
Upgrading an Existing Oracle XML DB Installation
Run the script, catproc.sql, as always.
As a post upgrade step, if you want Oracle XML DB functionality, you must install
Oracle XML DB manually as described in "Installing a New Oracle XML DB
Manually Without DBCA" on page A-2.
Upgrading XML DB From Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
Oracle9i Release 2 (9.2.0.2) patchset for the Oracle9i Release 2 (9.2) database is a
required upgrade for users of Oracle XML DB Release 2 (9.2.0.1). Oracle XML DB
requires schema based XMLType tables and columns from release 9.2.0.1 to be
migrated to release 9.2.0.2. This mandatory migration is done automatically as part
of the database upgrade process. The migration is transparent except for a few
restrictions.
I You cannot use Database Upgrade Assistant to directly upgrade to release
9.2.0.2. It can only be used to upgrade to a major or minor release and not to a
patchset release. Hence the upgrade process has to be carried out manually.
I The manual upgrade steps are detailed in "Chapter 3 - Upgrading a database to
the newOracle9i Release" in the Oracle9i Database Migration. The steps required
to upgrade to 9.2.0.2 are identical. The only difference is in step 14.
I Steps 1-13 are the same. Check the system requirements and startup the
database in MIGRATE mode.
I Step 14 : Run catpatch.sql. This script created and alters certain dictionary
tables. It also runs the catalog.sql and catproc.sql scripts that come with the
new 9.2.0.2 release, which create the system catalog views and all the
necessary packages for using PL/SQL.
I Steps 15-21 are the same.
At this point, Oracle XML DB is automatically upgraded and schema based
XML data is migrated to a new format usable by the new release Oracle9i
Release 2 (9.2.0.2). Verify that all components are valid and have been upgraded
to the new release:
SQL> SELECT comp_id, version, status FROM dba_registry;
Upgrading XML DB From Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
A-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Migrating Data From Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
If you are migrating your data, follow these important instructions:
Before the Upgrade
You must back up all your XML schema-based data that is stored as
object-relational. This minimizes any data-corruption during the migration process
by deleting the corrupted rows and reloading the XML from scratch.
Also, before the upgrade, you must ensure that all XML schema-based XMLType
rows and columns stored as object-relational are schema-valid. In Release 2 (9.2.0.1),
Oracle XML DB did not perform rigorous checks that an XML document being
inserted into a table was valid against its XML schema. However, in Release 2
(9.2.0.2), certain aspects of data storage rely on the schema-validity of XML
documents stored. For this reason, non-conforming XML documents stored using
Release 2 (9.2.0.1) may not migrate to Release 2 (9.2.0.2).
When is Data Non-Migratable to Release 2 (9.2.0.2)?
There are two instances where an XML schema-based document cannot be migrated
to Release 2 (9.2.0.2). If your data falls in either of these two categories, Oracle
recommends that you do the following:
1. Save all documents conforming to the non-migrated XML schema as text XML
2. Unregister the XML schema before upgrading
3. Re-register the XML schema
4. Reload the documents after the upgrade is complete.
Note: If you have the ability to restore all your XML schema and
documents from scratch, Oracle strongly recommends that you
uninstall XML DB before the upgrade, then reinstall XML DB and
reload all data after the upgrade has succeeded. This approach has
two benets: the risk of an unsuccessful migration of the user's
XML data is eliminated, and all optimizations coded into Release 2
(9.2.0.2) will be used to their fullest extent if the data is freshly
loaded into the database post-migration rather than if it is migrated
from the Release 2 (9.2.0.1) format.
Upgrading XML DB From Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
Installing and Conguring Oracle XML DB A-7
If you try to migrate data that falls under one of the two following categories, an
error is logged in the trace le for each row that fails migration.
You Cannot Migrate a Document with anyType Element in the XML Schema The rst type of
XML document that cannot be migrated is one whose XML schema contains the
anyType element. Due to storage limitations for anyType in Release 2 (9.2.0.1),
Oracle changed the storage format of anyType in Release 2 (9.2.0.2) so that XML
documents with one or more non-NULL anyType element cannot be migrated.
You Cannot Migrate a Document with SubTyped Element Namespace Different from its Parent
Element Namespace The second type of XML document that cannot be migrated is
one whose XML schema contains a subtyped element with a namespace that differs
from the namespace of its parent element. This is because in Release 2 (9.2.0.1),
Oracle XML DB required and assumed the namespace of the subtyped element to
be that of its parent's namespace, and thus the real namespace of the subtyped
element was lost during the storage phase. For this reason, you cannot migrate
these XML schema, along with their conforming XML documents, to Release 2
(9.2.0.2).
The Release 2 (9.2.0.2) Oracle XML DB Upgrade Process
The migration of XMLType data happens transparently within the upgrade script
catpatch.sql.
Errors occurring during Oracle XML DB migration are reported to the trace le,
along with the table name and ROWID of the row for which the migration failed. If
an error occurs during migration of a row, the migration script simply reports the
error to the trace le and continues migrating the next row. In other words, the
script is not interrupted by errors.
If all rows are successfully migrated, Oracle XML DB is ready to use once the
database has been restarted.
Oracle XMl DB: Error Handling When Migrating to Release 2 (9.2.0.2)
If the trace le shows that errors occurred during migration of one or more
XMLType rows, the remainder of Oracle XML DB should remain usable despite the
lack of completion. If you later try to access an non-migrated row, Oracle throws an
ORA-1038 error. You can delete non-migrated rows fromXMLType tables without
harm.
See Also: .... for instructions on running this script.
Upgrading XML DB From Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
A-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
When a row is migrated and does not produce an error yet yields the row unusable
after the upgrade is complete, you should delete the row then restore it using the
raw XML data, assuming that a backup was taken prior to upgrade.
Even after upgrade, any XMLType table, migrated or not, can be re-run through the
migration engine. This may be useful when a particular XMLType row fails to be
migrated as a part of catpatch.sql, but you have since taken some action to
make the migration run successfully.
Summary of Functions that Trigger Migration of a Table
Table A1 lists the migration procedures available fromXDB.DBMS_XDB package
after upgrading to Release 2 (9.2.0.2).
Table A1 XDB.DBMS_XDB Package Release 2 (9.2.0.2) Migration Procedures
PROCEDURE Description
MigrateColumnFrom9201 Migrates one XMLType column from Release 2 (9.2.0.1) to Release 2 (9.2.0.2)
format. The column must exist inside an object table and must be of type
XMLType, XML schema-based, and stored in object-relational format. An exclusive
lock is taken on the table before the column is migrated.
PARAMETERS: owner (IN) - Database user who owns the XMLType table,
table_name (IN) - Name of the table, column_name (IN) - Name of the XMLType
column within the table, For example: "FOO"."BAR"
Syntax:
MigrateColumnFrom9201(owner IN VARCHAR2, table_name IN VARCHAR2, column_name IN
VARCHAR2)
MigrateTableFrom9201 Migrates one XMLType table fromthe 9.2.0.1 format to the 9.2.0.2 format. The table
must have XMLType as its rowtype, and the XMLType row must be schema-based
and stored in object-relational format. An exclusive lock is taken on the table
before it is operated on.
PARAMETERS: owner (IN) - Database user who owns the XMLType table,
table_name (IN) - Name of the XMLType table.
Syntax:
MigrateTableFrom9201(owner IN VARCHAR2, table_name IN VARCHAR2);
MigrateAllXmlFrom9201 Migrates all object-relational XMLType tables and XMLType columns from the
9.2.0.1 format to the 9.2.0.2 format. An exclusive lock is taken each table before it is
operated on.
PARAMETERS: None.
Syntax:
MigrateAllXmlFrom9201;
Oracle XML DB Configuration File, xdbconfig.xml
Installing and Conguring Oracle XML DB A-9
Conguring Oracle XML DB
The following sections describe how to congure Oracle XML DB. You can also
congure Oracle XML DB using Oracle Enterprise Manager.
Oracle XML DB is managed through a conguration resource stored in Oracle XML
DB Repository, /sys/xdbconfig.xml.
The Oracle XML DB conguration le is alterable at runtime. Simply updating the
conguration le, causes a new version of the le to be generated. At the start of
each session, the current version of the conguration is bound to that session. The
session will use this conguration for its life, unless you invoke an explicit call to
refresh to the latest conguration.
Oracle XML DB Conguration File, xdbcong.xml
Oracle XML DB conguration is stored as an XML resource, /xdbconfig.xml
conforming to the Oracle XML DB conguration XML schema:
http://xmlns.oracle.com/xdb/xdbconfig.xsd
To congure or modify the conguration of Oracle XML DB, update the
/xdbconfig.xml le by inserting, removing, or editing the appropriate XML
elements in xdbconfig.xml.
Oracle XML DB conguration XML schema has the following structure:
Top Level Tag <xdbcong>
A top level tag, <xdbconfig> is divided into two sections:
I <syscon g> This keeps system-specic, built-in parameters.
I <usercon g> This allows users to store new custom parameters.
The following describes the syntax:
<xdbconfig>
<sysconfig> ... </sysconfig>
<userconfig> ... </userconfig>
</xdbconfig>
See Also: Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
Oracle XML DB Configuration File, xdbconfig.xml
A-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<syscong>
The <sysconfig> section is further subdivided as follows:
<sysconfig>
General parameters
<protocolconfig> ... </protocolconfig>
</sysconfig>
It stores several general parameters that apply to all Oracle XML DB, for example,
the maximum age for an ACL, whether Oracle XML DB should be case sensitive,
and so on.
Protocol-specic parameters are grouped inside the <protocolconfig> tag.
<usercong>
The <userconfig> section contains any parameters that you may want to add.
<protocolcong>
The structure of the <protocolconfig> section is as follows:
<protocolconfig>
<common> ... </common>
<httpconfig> ... </httpconfig>
<ftpconfig> ... </ftpconfig>
</protocolconfig>
Under <common> Oracle9i stores parameters that apply to all protocols, such as
MIME type information. There are also HTTP and FTP specic parameters under
sections <httpconfig> and <ftpconfig> respectively.
<httpcong>
Inside <httpconfig> there is a further subsection, <webappconfig> that
corresponds to Web-based applications. It includes Web application specic
parameters, for example, icon name, display name for the application, list of
servlets in Oracle XML DB, and so on.
Oracle XML DB Configuration Example
Installing and Conguring Oracle XML DB A-11
Oracle XML DB Conguration Example
The following is a sample Oracle XML DB conguration le:
Example A1 Oracle XML DB Conguration File
<xdbconfig xmlns="http://xmlns.oracle.com/xdb/xdbconfig.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/xdbconfig.xsd
http://xmlns.oracle.com/xdb/xdbconfig.xsd">
<sysconfig>
<acl-max-age>900</acl-max-age>
<invalid-pathname-chars>,</invalid-pathname-chars>
<call-timeout>300</call-timeout>
<max-session-use>100</max-session-use>
<default-lock-timeout>3600</default-lock-timeout>
<xdbcore-logfile-path>/sys/log/xdblog.xml</xdbcore-logfile-path>
<xdbcore-log-level>1</xdbcore-log-level>
<protocolconfig>
<common>
<extension-mappings>
<mime-mappings>
<mime-mapping>
<extension>au</extension>
<mime-type>audio/basic</mime-type>
</mime-mapping>
<mime-mapping>
<extension>avi</extension>
<mime-type>video/x-msvideo</mime-type>
</mime-mapping>
<mime-mapping>
<extension>bin</extension>
<mime-type>application/octet-stream</mime-type>
</mime-mapping>
See Also:
I Chapter 19, "Using FTP, HTTP, and WebDAV Protocols",
Table 191, Table 192, and Table 193, for a list of protocol
conguration parameters.
I Chapter 20, "Writing Oracle XML DB Applications in Java",
"Conguring the Oracle XML DB Example Servlet" on
page 20-12.
Oracle XML DB Configuration Example
A-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<lang-mappings>
<lang-mapping>
<extension>en</extension>
<lang>english</lang>
</lang-mapping>
</lang-mappings>
<charset-mappings>
</charset-mappings>
<encoding-mappings>
<encoding-mapping>
<extension>gzip</extension>
<encoding>zip file</encoding>
</encoding-mapping>
<encoding-mapping>
<extension>tar</extension>
<encoding>tar file</encoding>
</encoding-mapping>
</encoding-mappings>
</extension-mappings>
<session-pool-size>50</session-pool-size>
<session-timeout>6000</session-timeout>
</common>
<ftpconfig>
<ftp-port>2100</ftp-port>
<ftp-listener>local_listener</ftp-listener>
<ftp-protocol>tcp</ftp-protocol>
<logfile-path>/sys/log/ftplog.xml</logfile-path>
<log-level>0</log-level>
<session-timeout>6000</session-timeout>
</ftpconfig>
<httpconfig>
<http-port>8080</http-port>
<http-listener>local_listener</http-listener>
<http-protocol>tcp</http-protocol>
<session-timeout>6000</session-timeout>
<server-name>XDB HTTP Server</server-name>
<max-header-size>16384</max-header-size>
<max-request-body>2000000000</max-request-body>
<logfile-path>/sys/log/httplog.xml</logfile-path>
Oracle XML DB Configuration Example
Installing and Conguring Oracle XML DB A-13
<log-level>0</log-level>
<servlet-realm>Basic realm="XDB"</servlet-realm>
<webappconfig>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
<error-pages>
</error-pages>
<servletconfig>
<servlet-mappings>
<servlet-mapping>
<servlet-pattern>/oradb/*</servlet-pattern>
<servlet-name>DBURIServlet</servlet-name>
</servlet-mapping>
</servlet-mappings>
<servlet-list>
<servlet>
<servlet-name>DBURIServlet</servlet-name>
<display-name>DBURI</display-name>
<servlet-language>C</servlet-language>
<description>Servlet for accessing DBURIs</description>
<security-role-ref>
<role-name>authenticatedUser</role-name>
<role-link>authenticatedUser</role-link>
</security-role-ref>
</servlet>
</servlet-list>
</servletconfig>
</webappconfig>
</httpconfig>
</protocolconfig>
</sysconfig>
<userconfig><numusers>40</numusers></userconfig>
</xdbconfig>
Oracle XML DB Configuration API
A-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Conguration API
The Oracle XML DB Conguration API can be accessed just like any other XML
schema-based resource in the hierarchy. It can be accessed and manipulated using
FTP, HTTP, WebDav, Oracle Enterprise Manager, or any of the resource and DOM
APIs for Java or PL/SQL.
For convenience, there is a PL/SQL API provided as part of the DBMS_XDB package
for conguration access. It exposes the following functions:
Get Conguration, cfg_get()
The cfg_get() function returns a copy of the conguration as an XMLType:
DBMS_XDB.CFG_GET() RETURN SYS.XMLTYPE
cfg_get() is auto-commit.
Update Conguration, cfg_update()
The cfg_update() function updates the conguration with a new one:
DBMS_XDB.CFG_UPDATE(newconfig SYS.XMLTYPE)
Example A2 Updating the Conguration File Using cfg_update() and cfg_get()
If you have a few parameters to update in the conguration le, you can use the
following:
BEGIN
DBMS_XDB.CFG_UPDATE(UPDATEXML(UPDATEXML
(DBMS_XDB.CFG_GET(),
/xdbconfig/descendant::ftp-port/text()', '2121'),
'/xdbconfig/descendant::http-port/text()',
19090'))
END;
/
If you have many parameters to update, the preceding example may prove too
cumbersome. Use instead FTP, HTTP, or Oracle Enterprise Manager.
Oracle XML DB Configuration API
Installing and Conguring Oracle XML DB A-15
Refresh Conguration, cfg_refresh()
The cfg_refresh() function updates the conguration snapshot to correspond to
the latest version on disk at that instant:
DBMS_XDB.CFG_REFRESH()
Typically, cfg_refresh() is called in one of the following scenarios:
I You have modied the conguration and now want the session to pick up the
latest version of the conguration information.
I It has been a long running session, the conguration has been modied by a
concurrent session, and you want the current session to pick up the latest
version of the conguration information.
I If updates to the conguration are made, Oracle XML DB Conguration API is
aware of them.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
the chapter on DBMS_XDB
Oracle XML DB Configuration API
A-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XML Schema Primer B-1
B
XML Schema Primer
This appendix includes introductory information about the W3C XML Schema
Recommendation. It contains the following sections:
I Introducing XML Schema
I XML Schema Components
I Simple Types
I Anonymous Type Denitions
I Element Content
I Annotations
I Building Content Models
I Attribute Groups
I Nil Values
I Building Content Models
I XML Schema Example, PurchaseOrder.xsd
Introducing XML Schema
B-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing XML Schema
Parts of this introduction are extracted from W3C XML Schema notes.
An XML schema (referred to in this appendix as schema) denes a class of XML
documents. The term instance document is often used to describe an XML
document that conforms to a particular XML schema. However, neither instances
nor schemas need to exist as documents, they may exist as streams of bytes sent
between applications, as elds in a database record, or as collections of XML Infoset
Information Items. But to simplify the description in this appendix, instances and
schemas are referred to as if they are documents and les.
Purchase Order, po.xml
Consider the following instance document in an XML le po.xml. It describes a
purchase order generated by a home products ordering and billing application:
<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20">
<shipTo country="US">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
<billTo country="US">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>PA</state>
<zip>95819</zip>
See Also:
I http://www.w3.org/TR/xmlschema-0/ Primer
I http://www.w3.org/TR/xmlschema-1/ Structures
I http://www.w3.org/TR/xmlschema-2/ Datatypes
I http://w3.org/XML/Schema
I http://www.oasis-open.org/cover/schemas.html
I http://www.xml.com/pub/a/2000/11/29/schemas/part1
.html
Introducing XML Schema
XML Schema Primer B-3
</billTo>
<comment>Hurry, my lawn is going wild!</comment>
<items>
<item partNum="872-AA">
<productName>Lawnmower</productName>
<quantity>1</quantity>
<USPrice>148.95</USPrice>
<comment>Confirm this is electric</comment>
</item>
<item partNum="926-AA">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
</item>
</items>
</purchaseOrder>
The purchase order consists of a main element, purchaseOrder, and the
subelements shipTo, billTo, comment, and items. These subelements (except
comment) in turn contain other subelements, andso on, until a subelement such as
USPrice contains a number rather than any subelements.
I Complex Type Elements. Elements that contain subelements or carry attributes
are said to have complex types
I Simple Type Elements. Elements that contain numbers (and strings, and dates,
and so on) but do not contain any subelements are said to have simple types.
Some elements have attributes; attributes always have simple types.
The complex types in the instance document, and some simple types, are dened in
the purchase order schema. The other simple types are dened as part of XML
Schema's repertoire of built-in simple types.
Association Between the Instance Document and Purchase Order Schema
The purchase order schema is not mentioned in the XML instance document. An
instance is not actually required to reference an XML schema, and although many
will. It is assumed that any processor of the instance document can obtain the
purchase order XML schema without any information from the instance document.
Later, you will see the explicit mechanisms for associating instances and XML
schemas.
Introducing XML Schema
B-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Purchase Order Schema, po.xsd
The purchase order schema is contained in the le po.xsd:
Purchase Order Schema, po.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:annotation>
<xsd:documentation xml:lang="en">
Purchase order schema for Example.com.
Copyright 2000 Example.com. All rights reserved.
</xsd:documentation>
</xsd:annotation>
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:element name="comment" type="xsd:string"/>
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
<xsd:element name="state" type="xsd:string"/>
<xsd:element name="zip" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN"fixed="US"/>
</xsd:complexType>
<xsd:complexType name="Items">
<xsd:sequence>
<xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
Introducing XML Schema
XML Schema Primer B-5
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="partNum" type="SKU" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<!-- Stock Keeping Unit, a code for identifying products -->
<xsd:simpleType name="SKU">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
The purchase order schema consists of a schema element and a variety of
subelements, most notably elements, complexType, and simpleType which
determine the appearance of elements and their content in the XML instance
documents.
Prefix xsd:
Each of the elements in the schema has a prex xsd: which is associated with the
XML Schema namespace through the declaration,
xmlns:xsd="http://www.w3.org/2001/XMLSchema", that appears in the
schema element. The prex xsd: is used by convention to denote the XML Schema
namespace, although any prex can be used. The same prex, and hence the same
association, also appears on the names of built-in simple types, such as,
xsd:string. This identies the elements and simple types as belonging to the
vocabulary of the XML Schema language rather than the vocabulary of the schema
author. For clarity, this description uses the names of elements and simple types, for
example, simpleType, and omits the prex.
XML Schema Components
B-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XML Schema Components
Schema component is the generic term for the building blocks that comprise the
abstract data model of the schema. An XML Schema is a set of schema
components. There are 13 kinds of component in all, falling into three groups.
Primary Components
The primary components, which may (type denitions) or must (element and
attribute declarations) have names are as follows:
I Simple type denitions
I Complex type denitions
I Attribute declarations
I Element declarations
Secondary Components
The secondary components, which must have names, are as follows:
I Attribute group denitions
I Identity-constraint denitions
I Model group denitions
I Notation declarations
Helper Components
Finally, the helper components provide small parts of other components; they are
not independent of their context:
I Annotations
I Model groups
I Particles
I Wildcards
I Attribute Uses
Complex Type Denitions, Element and Attribute Declarations
In XML Schema, there is a basic difference between complex and simple types:
XML Schema Components
XML Schema Primer B-7
I Complex types, allow elements in their content and may carry attributes
I Simple types, cannot have element content and cannot carry attributes.
There is also a major distinction between the following:
I De nitions which create new types (both simple and complex)
I Declarations which enable elements and attributes with specic names and types
(both simple and complex) to appear in document instances
This section denes complex types and declares elements and attributes that appear
within them.
New complex types are dened using the complexType element and such
denitions typically contain a set of element declarations, element references, and
attribute declarations. The declarations are not themselves types, but rather an
association between a name and the constraints which govern the appearance of
that name in documents governed by the associated schema. Elements are declared
using the element element, and attributes are declared using the attribute
element.
Defining the USAddress Type
For example, USAddress is dened as a complex type, and within the denition of
USAddress you see ve element declarations and one attribute declaration:
<xsd:complexType name="USAddress" >
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
<xsd:element name="state" type="xsd:string"/>
<xsd:element name="zip" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
</xsd:complexType>
Hence any element appearing in an instance whose type is declared to be
USAddress, such as, shipTo in po.xml, must consist of ve elements and one
attribute. These elements must:
I Be called name, street, city, state, and zip as specied by the values of
the declarations' name attributes
I Appear in the same sequence (order) in which they are declared. The rst four
of these elements will each contain a string, and the fth will contain a number.
XML Schema Components
B-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The element whose type is declared to be USAddress may appear with an
attribute called country which must contain the string US.
The USAddress denition contains only declarations involving the simple types:
string, decimal, and NMTOKEN.
Defining PurchaseOrderType
In contrast, the PurchaseOrderType denition contains element declarations
involving complex types, such as, USAddress, although both declarations use the
same type attribute to identify the type, regardless of whether the type is simple or
complex.
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
In dening PurchaseOrderType, two of the element declarations, for shipTo
and billTo, associate different element names with the same complex type, namely
USAddress. The consequence of this denition is that any element appearing in an
instance document, such as, po.xml, whose type is declared to be
PurchaseOrderType must consist of elements named shipTo and billTo, each
containing the ve subelements (name, street, city, state, and zip) that were
declared as part of USAddress. The shipTo and billTo elements may also carry
the country attribute that was declared as part of USAddress.
The PurchaseOrderType denition contains an orderDate attribute declaration
which, like the country attribute declaration, identies a simple type. In fact, all
attribute declarations must reference simple types because, unlike element
declarations, attributes cannot contain other elements or other attributes.
The element declarations we have described so far have each associated a name
with an existing type denition. Sometimes it is preferable to use an existing
element rather than declare a new element, for example:
<xsd:element ref="comment" minOccurs="0"/>
This declaration references an existing element, comment, declared elsewhere in the
purchase order schema. In general, the value of the ref attribute must reference a
XML Schema Components
XML Schema Primer B-9
global element, on other words, one that has been declared under schema rather
than as part of a complex type denition. The consequence of this declaration is that
an element called comment may appear in an instance document, and its content
must be consistent with that element's type, in this case, string.
Occurrence Constraints: minOccurs and maxOccurs
The comment element is optional in PurchaseOrderType because the value of the
minOccurs attribute in its declaration is 0. In general, an element is required to
appear when the value of minOccurs is 1 or more. The maximum number of times
an element may appear is determined by the value of a maxOccurs attribute in its
declaration. This value may be a positive integer such as 41, or the termunbounded
to indicate there is no maximum number of occurrences. The default value for both
the minOccurs and the maxOccurs attributes is 1.
Thus, when an element such as comment is declared without a maxOccurs
attribute, the element may not occur more than once. If you specify a value for only
the minOccurs attribute, make certain that it is less than or equal to the default
value of maxOccurs, that is, it is 0 or 1.
Similarly, if you specify a value for only the maxOccurs attribute, it must be greater
than or equal to the default value of minOccurs, that is, 1 or more. If both
attributes are omitted, the element must appear exactly once.
Attributes may appear once or not at all, but no other number of times, and so the
syntax for specifying occurrences of attributes is different from the syntax for
elements. In particular, attributes can be declared with a use attribute to indicate
whether the attribute is required, optional, or even prohibited. Recall for
example, the partNum attribute declaration in po.xsd:
<xsd:attribute name="partNum" type="SKU" use="required"/>
Default Attributes
Default values of both attributes and elements are declared using the default
attribute, although this attribute has a slightly different consequence in each case.
When an attribute is declared with a default value, the value of the attribute is
whatever value appears as the attribute's value in an instance document; if the
attribute does not appear in the instance document, the schema processor provides
the attribute with a value equal to that of the default attribute.
XML Schema Components
B-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Default Elements
The schema processor treats defaulted elements slightly differently. When an
element is declared with a default value, the value of the element is whatever value
appears as the element's content in the instance document.
If the element appears without any content, the schema processor provides the
element with a value equal to that of the default attribute. However, if the element
does not appear in the instance document, the schema processor does not provide
the element at all.
In summary, the differences between element and attribute defaults can be stated
as:
I Default attribute values apply when attributes are missing
I Default element values apply when elements are empty
The xed attribute is used in both attribute and element declarations to ensure that
the attributes and elements are set to particular values. For example, po.xsd
contains a declaration for the country attribute, which is declared with a xed value
US. This declaration means that the appearance of a country attribute in an
instance document is optional (the default value of use is optional), although if the
attribute does appear, its value must be US, and if the attribute does not appear, the
schema processor will provide a country attribute with the value US.
Table B1 summarizes the attribute values used in element and attribute
declarations to constrain their occurrences.
Note: Default values for attributes only make sense if the
attributes themselves are optional, and so it is an error to specify
both a default value and anything other than a value of optional for
use.
Note: The concepts of a xed value and a default value are
mutually exclusive, and so it is an error for a declaration to contain
both xed and default attributes.
XML Schema Components
XML Schema Primer B-11
Global Elements and Attributes
Global elements, and global attributes, are created by declarations that appear as
the children of the schema element. Once declared, a global element or a global
attribute can be referenced in one or more declarations using the ref attribute as
described in the preceding section.
A declaration that references a global element enables the referenced element to
appear in the instance document in the context of the referencing declaration. So,
for example, the comment element appears in po.xml at the same level as the
shipTo, billTo and items elements because the declaration that references
comment appears in the complex type denition at the same level as the
declarations of the other three elements.
Table B1 Occurrence Constraints for XML Schema Elements and Attributes
Elements
(minOccurs, maxOccurs)
xed, default
Attributes
use, xed,default
Notes
(1, 1) -, - required, -, - element/attribute must appear once, it may have any value
(1, 1) 37, - required, 37, - element/attribute must appear once, its value must be 37
(2, unbounded) 37, - n/a element must appear twice or more, its value must be 37; in
general, minOccurs and maxOccurs values may be positive
integers, and maxOccurs value may also be unbounded
(0, 1) -, - optional, -, - element/attribute may appear once, it may have any value
(0, 1) 37, - optional, 37, - element/attribute may appear once, if it does appear its
value must be 37, if it does not appear its value is 37
(0, 1) -, 37 optional, -, 37 element/attribute may appear once; if it does not appear its
value is 37, otherwise its value is that given
(0, 2) -, 37 n/a element may appear once, twice, or not at all; if the element
does not appear it is not provided; if it does appear and it is
empty, its value is 37; otherwise its value is that given; in
general, minOccurs and maxOccurs values may be positive
integers, and maxOccurs value may also be unbounded
(0, 0) -, - prohibited, -, - element/attribute must not appear
Note: Neither minOccurs, maxOccurs, nor use may appear in
the declarations of global elements and attributes.
XML Schema Components
B-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The declaration of a global element also enables the element to appear at the
top-level of an instance document. Hence purchaseOrder, which is declared as a
global element in po.xsd, can appear as the top-level element in po.xml.
Caveats: One caveat is that global declarations cannot contain references; global
declarations must identify simple and complex types directly. Global declarations
cannot contain the ref attribute, they must use the type attribute, or, be followed
by an anonymous type denition.
A second caveat is that cardinality constraints cannot be placed on global
declarations, although they can be placed on local declarations that reference global
declarations. In other words, global declarations cannot contain the attributes
minOccurs, maxOccurs, or use.
Naming Conicts
The preceding section described how to:
I Dene new complex types, such as, PurchaseOrderType
I Declare elements, such as, purchaseOrder
I Declare attributes, such as, orderDate
These involve naming. If two things are given the same name, in general, the more
similar the two things are, the more likely there will be a naming conict.
For example:
If the two things are both types, say a complex type called USStates and a simple
type called USStates, there is a conict.
If the two things are a type and an element or attribute, such as when dening a
complex type called USAddress and declaring an element called USAddress, there
is no conict.
If the two things are elements within different types, that is, not global elements,
say declare one element called name as part of the USAddress type and a second
element called name as part of the Item type, there is no conict. Such elements are
sometimes called local element declarations.
Note: This rationale also allows a comment element to appear as
the top-level element in a document like po.xml.
Simple Types
XML Schema Primer B-13
If the two things are both types and you dene one and XML Schema has dened
the other, say you dene a simple type called decimal, there is no conict. The
reason for the apparent contradiction in the last example is that the two types
belong to different namespaces. Namespaces are described in "Introducing the W3C
Namespaces in XML Recommendation" on page C-18.
Simple Types
The purchase order schema declares several elements and attributes that have
simple types. Some of these simple types, such as string and decimal, are built into
XML Schema, while others are derived from the built-in's.
For example, the partNum attribute has a type called SKU (Stock Keeping Unit) that
is derived from string. Both built-in simple types and their derivations can be used
in all element and attribute declarations. Table B2 lists all the simple types built
into XML Schema, along with examples of the different types.
Table B2 Simple Types Built into XML Schema
Simple Type Examples (delimited by commas) Notes
string Conrm this is electric --
normalizedString Conrm this is electric 3
token Conrm this is electric 4
byte -1, 126 2
unsignedByte 0, 126 2
base64Binary GpM7 --
hexBinary 0FB7 --
integer -126789, -1, 0, 1, 126789 2
positiveInteger 1, 126789 2
negativeInteger -126789, -1 2
nonNegativeInteger 0, 1, 126789 2
nonPositiveInteger -126789, -1, 0 2
int -1, 126789675 2
unsignedInt 0, 1267896754 2
long -1, 12678967543233 2
Simple Types
B-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
unsignedLong 0, 12678967543233 2
short -1, 12678 2
unsignedShort 0, 12678 2
decimal -1.23, 0, 123.4, 1000.00 2
oat -INF, -1E4, -0, 0, 12.78E-2, 12, INF,
NaN
equivalent to
single-precision 32-bit
oating point, NaN is
not a number. Note: 2
double -INF, -1E4, -0, 0, 12.78E-2, 12, INF,
NaN
equivalent to
double-precision 64-bit
oating point. Note: 2\
boolean true, false 1, 0 --
time 13:20:00.000, 13:20:00.000-05:00 2
dateTime 1999-05-31T13:20:00.000-05:00 May 31st 1999 at 1.20pm
Eastern Standard Time
which is 5 hours behind
Co-Ordinated Universal
Time, see 2
duration P1Y2M3DT10H30M12.3S 1 year, 2 months, 3 days,
10 hours, 30 minutes, and
12.3 seconds
date 1999-05-31 2
gMonth --05-- May, Notes: 2, 5
gYear 1999 1999, Notes: 2, 5
gYearMonth 1999-02 the month of February
1999, regardless of the
numberof
days. Notes: 2, 5
gDay ---31 the 31st day. Notes: 2, 5
gMonthDay --05-31 every May 31st. Notes: 2,
5
Name shipTo XML 1.0 Name type
QName po:USAddress XML Namespace
QName
Table B2 Simple Types Built into XML Schema (Cont.)
Simple Type Examples (delimited by commas) Notes
Simple Types
XML Schema Primer B-15
Notes:
(1) To retain compatibility between XML Schema and XML 1.0 DTDs, the simple
types ID, IDREF, IDREFS, ENTITY, ENTITIES, NOTATION, NMTOKEN,
NMTOKENS should only be used in attributes.
(2) A value of this type can be represented by more than one lexical format. For
example, 100 and 1.0E2 are both valid oat formats representing one hundred.
NCName USAddress XML Namespace
NCName, that is,
QName without the
prex and colon
anyURI http://www.example.com/,
http://www.example.com/doc.ht
ml#ID5
--
language en-GB, en-US, fr valid values for xml:lang
as dened in XML 1.0
ID -- XML 1.0 ID attribute
type, Note: 1
IDREF -- XML 1.0 IDREF attribute
type. Note: 1
IDREFS -- XML 1.0 IDREFS
attribute type, see (1)
ENTITY -- XML 1.0 ENTITY
attribute type. Note: 1
ENTITIES -- XML 1.0 ENTITIES
attribute type. Note: 1
NOTATION -- XML 1.0 NOTATION
attribute type. Note: 1
NMTOKEN US,Brsil XML 1.0 NMTOKEN
attribute type. Note: 1
NMTOKENS US UK,Brsil Canada Mexique XML 1.0 NMTOKENS
attribute type, that is, a
whitespace separated list
of NMTOKEN's. Note: 1
Table B2 Simple Types Built into XML Schema (Cont.)
Simple Type Examples (delimited by commas) Notes
Simple Types
B-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
However, rules have been established for this type that dene a canonical lexical
format, see XML Schema Part 2.
(3) Newline, tab and carriage-return characters in a normalizedString type are
converted to space characters before schema processing.
(4) As normalizedString, and adjacent space characters are collapsed to a single
space character, and leading and trailing spaces are removed.
(5) The g prex signals time periods in the Gregorian calender.
New simple types are dened by deriving them from existing simple types
(built-in's and derived). In particular, you can derive a new simple type by
restricting an existing simple type, in other words, the legal range of values for the
new type are a subset of the existing type's range of values.
Use the simpleType element to dene and name the new simple type. Use the
restriction element to indicate the existing (base) type, and to identify the facets
that constrain the range of values. A complete list of facets is provided in Appendix
B of XML Schema Primer, http://www.w3.org/TR/xmlschema-0/.
Suppose you want to create a new type of integer called myInteger whose range
of values is between 10000 and 99999 (inclusive). Base your denition on the
built-in simple type integer, whose range of values also includes integers less than
10000 and greater than 99999.
To dene myInteger, restrict the range of the integer base type by employing two
facets called minInclusive and maxInclusive:
Defining myInteger, Range 10000-99999
<xsd:simpleType name="myInteger">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="10000"/>
<xsd:maxInclusive value="99999"/>
</xsd:restriction>
</xsd:simpleType>
The example shows one particular combination of a base type and two facets used
to dene myInteger, but a look at the list of built-in simple types and their facets
should suggest other viable combinations.
The purchase order schema contains another, more elaborate, example of a simple
type denition. A new simple type called SKU is derived (by restriction) from the
simple type string. Furthermore, you can constrain the values of SKU using a facet
called pattern in conjunction with the regular expression "\d{3}-[A-Z]{2}"
Simple Types
XML Schema Primer B-17
that is read three digits followed by a hyphen followed by two upper-case ASCII
letters:
Defining the Simple Type SKU
<xsd:simpleType name="SKU">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>
This regular expression language is described more fully in Appendix D of
http://www.w3.org/TR/xmlschema-0/.
XML Schema denes fteen facets which are listed in Appendix B of
http://www.w3.org/TR/xmlschema-0/. Among these, the enumeration facet
is particularly useful and it can be used to constrain the values of almost every
simple type, except the boolean type. The enumeration facet limits a simple type to
a set of distinct values. For example, you can use the enumeration facet to dene a
new simple type called USState, derived from string, whose value must be one of
the standard US state abbreviations:
Using the Enumeration Facet
<xsd:simpleType name="USState">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="AK"/>
<xsd:enumeration value="AL"/>
<xsd:enumeration value="AR"/>
<!-- and so on ... -->
</xsd:restriction>
</xsd:simpleType>
USState would be a good replacement for the string type currently used in the
state element declaration. By making this replacement, the legal values of a state
element, that is, the state subelements of billTo and shipTo, would be limited to
one of AK, AL, AR, and so on. Note that the enumeration values specied for a
particular type must be unique.
List Types
XML Schema has the concept of a list type, in addition to the so-called atomic types
that constitute most of the types listed in Table B3. Atomic types, list types, and the
union types described in the next section are collectively called simple types. The
Simple Types
B-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
value of an atomic type is indivisible fromXML Schema's perspective. For example,
the NMTOKEN value US is indivisible in the sense that no part of US, such as the
character S, has any meaning by itself. In contrast, list types are comprised of
sequences of atomic types and consequently the parts of a sequence (the atoms)
themselves are meaningful. For example, NMTOKENS is a list type, and an element of
this type would be a white-space delimited list of NMTOKEN's, such as US UK
FR. XML Schema has three built-in list types:
I NMTOKENS
I IDREFS
I ENTITIES
In addition to using the built-in list types, you can create new list types by
derivation fromexisting atomic types. You cannot create list types from existing
list types, nor from complex types. For example, to create a list of myInteger's:
Creating a List of myInteger's
<xsd:simpleType name="listOfMyIntType">
<xsd:list itemType="myInteger"/>
</xsd:simpleType>
And an element in an instance document whose content conforms to
listOfMyIntType is:
<listOfMyInt>20003 15037 95977 95945</listOfMyInt>
Several facets can be applied to list types: length, minLength, maxLength, and
enumeration. For example, to dene a list of exactly six US states (SixUSStates),
we rst dene a new list type called USStateList fromUSState, and then we
derive SixUSStates by restricting USStateList to only six items:
List Type for Six US States
<xsd:simpleType name="USStateList">
<xsd:list itemType="USState"/>
</xsd:simpleType>
<xsd:simpleType name="SixUSStates">
<xsd:restriction base="USStateList">
<xsd:length value="6"/>
</xsd:restriction>
</xsd:simpleType>
Simple Types
XML Schema Primer B-19
Elements whose type is SixUSStates must have six items, and each of the six items
must be one of the (atomic) values of the enumerated type USState, for example:
<sixStates>PA NY CA NY LA AK</sixStates>
Note that it is possible to derive a list type from the atomic type string. However, a
string may contain white space, and white space delimits the items in a list type, so
you should be careful using list types whose base type is string. For example,
suppose we have dened a list type with a length facet equal to 3, and base type
string, then the following 3 item list is legal:
Asie Europe Afrique
But the following 3 item list is illegal:
Asie Europe Amrique Latine
Even though "Amrique Latine" may exist as a single string outside of the list,
when it is included in the list, the whitespace between Amrique and Latine
effectively creates a fourth item, and so the latter example will not conform to the
3-item list type.
Union Types
Atomic types and list types enable an element or an attribute value to be one or
more instances of one atomic type. In contrast, a union type enables an element or
attribute value to be one or more instances of one type drawn from the union of
multiple atomic and list types. To illustrate, we create a union type for representing
American states as singleton letter abbreviations or lists of numeric codes. The
zipUnion union type is built from one atomic type and one list type:
Union Type for Zipcodes
<xsd:simpleType name="zipUnion">
<xsd:union memberTypes="USState listOfMyIntType"/>
</xsd:simpleType>
When we dene a union type, the memberTypes attribute value is a list of all the
types in the union.
Now, assuming we have declared an element called zips of type zipUnion, valid
instances of the element are:
<zips>CA</zips>
<zips>95630 95977 95945</zips>
<zips>AK</zips>
Anonymous Type Definitions
B-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Two facets, pattern and enumeration, can be applied to a union type.
Anonymous Type Denitions
Schemas can be constructed by dening sets of named types such as
PurchaseOrderType and then declaring elements such as purchaseOrder that
reference the types using the type= construction. This style of schema construction
is straightforward but it can be unwieldy, especially if you dene many types that
are referenced only once and contain very few constraints. In these cases, a type can
be more succinctly dened as an anonymous type which saves the overhead of
having to be named and explicitly referenced.
The denition of the type Items in po.xsd contains two element declarations that
use anonymous types (item and quantity). In general, you can identify
anonymous types by the lack of a type= in an element (or attribute) declaration, and
by the presence of an un-named (simple or complex) type denition:
Two Anonymous Type Definitions
<xsd:complexType name="Items">
<xsd:sequence>
<xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="partNum" type="SKU" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
Element Content
XML Schema Primer B-21
In the case of the item element, it has an anonymous complex type consisting of
the elements productName, quantity, USPrice, comment, and shipDate, and
an attribute called partNum. In the case of the quantity element, it has an
anonymous simple type derived from integer whose value ranges between 1 and
99.
Element Content
The purchase order schema has many examples of elements containing other
elements (for example, items), elements having attributes and containing other
elements (such as, shipTo), and elements containing only a simple type of value
(for example, USPrice). However, we have not seen an element having attributes
but containing only a simple type of value, nor have we seen an element that
contains other elements mixed with character content, nor have we seen an element
that has no content at all. In this section we'll examine these variations in the
content models of elements.
Complex Types from Simple Types
Let us rst consider how to declare an element that has an attribute and contains a
simple value. In an instance document, such an element might appear as:
<internationalPrice currency="EUR">423.46</internationalPrice>
The purchase order schema declares a USPrice element that is a starting point:
<xsd:element name="USPrice" type="decimal"/>
Now, how do we add an attribute to this element? As we have said before, simple
types cannot have attributes, and decimal is a simple type.
Therefore, we must dene a complex type to carry the attribute declaration. We also
want the content to be simple type decimal. So our original question becomes: How
do we dene a complex type that is based on the simple type decimal? The answer
is to derive a new complex type from the simple type decimal:
Deriving a Complex Type from a Simple Type
<xsd:element name="internationalPrice">
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base="xsd:decimal">
<xsd:attribute name="currency" type="xsd:string"/>
</xsd:extension>
Element Content
B-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
We use the complexType element to start the denition of a new (anonymous)
type. To indicate that the content model of the new type contains only character
data and no elements, we use a simpleContent element. Finally, we derive the new
type by extending the simple decimal type. The extension consists of adding a
currency attribute using a standard attribute declaration. (We cover type derivation
in detail in Section 4.) The internationalPrice element declared in this way will
appear in an instance as shown in the example at the beginning of this section.
Mixed Content
The construction of the purchase order schema may be characterized as elements
containing subelements, and the deepest subelements contain character data. XML
Schema also provides for the construction of schemas where character data can
appear alongside subelements, and character data is not conned to the deepest
subelements.
To illustrate, consider the following snippet froma customer letter that uses some of
the same elements as the purchase order:
Snippet of Customer Letter
<letterBody>
<salutation>Dear Mr.<name>Robert Smith</name>.</salutation>
Your order of <quantity>1</quantity> <productName>Baby
Monitor</productName> shipped from our warehouse on
<shipDate>1999-05-21</shipDate>. ....
</letterBody>
Notice the text appearing between elements and their child elements. Specically,
text appears between the elements salutation, quantity, productName and shipDate
which are all children of letterBody, and text appears around the element name
which is the child of a child of letterBody. The following snippet of a schema
declares letterBody:
Snippet of Schema for Customer Letter
<xsd:element name="letterBody">
<xsd:complexType mixed="true">
<xsd:sequence>
<xsd:element name="salutation">
Element Content
XML Schema Primer B-23
<xsd:complexType mixed="true">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="quantity" type="xsd:positiveInteger"/>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
<!-- and so on -->
</xsd:sequence>
</xsd:complexType>
</xsd:element>
The elements appearing in the customer letter are declared, and their types are
dened using the element and complexType element constructions we previously
seen. To enable character data to appear between the child-elements of letterBody,
the mixed attribute on the type denition is set to true.
Note that the mixed model in XML Schema differs fundamentally from the mixed
model in XML 1.0. Under the XML Schema mixed model, the order and number of
child elements appearing in an instance must agree with the order and number of
child elements specied in the model. In contrast, under the XML 1.0 mixed model,
the order and number of child elements appearing in an instance cannot be
constrained. In summary, XML Schema provides full validation of mixed models in
contrast to the partial schema validation provided by XML 1.0.
Empty Content
Now suppose that we want the internationalPrice element to convey both the unit
of currency and the price as attribute values rather than as separate attribute and
content values. For example:
<internationalPrice currency="EUR" value="423.46"/>
Such an element has no content at all; its content model is empty.
An Empty Complex Type
To dene a type whose content is empty, we essentially dene a type that allows
only elements in its content, but we do not actually declare any elements and so the
type's content model is empty:
<xsd:element name="internationalPrice">
<xsd:complexType>
Element Content
B-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<xsd:complexContent>
<xsd:restriction base="xsd:anyType">
<xsd:attribute name="currency" type="xsd:string"/>
<xsd:attribute name="value" type="xsd:decimal"/>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
In this example, we dene an (anonymous) type having complexContent, that is,
only elements. The complexContent element signals that the intent to restrict or
extend the content model of a complex type, and the restriction of anyType
declares two attributes but does not introduce any element content (see Section 4.4
of the XML Schema Primer, for more details on restriction. The
internationalPrice element declared in this way may legitimately appear in
an instance as shown in the preceding example.
Shorthand for an Empty Complex Type
The preceding syntax for an empty-content element is relatively verbose, and it is
possible to declare the internationalPrice element more compactly:
<xsd:element name="internationalPrice">
<xsd:complexType>
<xsd:attribute name="currency" type="xsd:string"/>
<xsd:attribute name="value" type="xsd:decimal"/>
/xsd:complexType>
</xsd:element>
This compact syntax works because a complex type dened without any
simpleContent or complexContent is interpreted as shorthand for complex content
that restricts anyType.
AnyType
The anyType represents an abstraction called the ur-type which is the base type
from which all simple and complex types are derived. An anyType type does not
constrain its content in any way. It is possible to use anyType like other types, for
example:
<xsd:element name="anything" type="xsd:anyType"/>
The content of the element declared in this way is unconstrained, so the element
value may be 423.46, but it may be any other sequence of characters as well, or
Annotations
XML Schema Primer B-25
indeed a mixture of characters and elements. In fact, anyType is the default type
when none is specied, so the preceding could also be written as follows:
<xsd:element name="anything"/>
If unconstrained element content is needed, for example in the case of elements
containing prose which requires embedded markup to support internationalization,
then the default declaration or a slightly restricted form of it may be suitable. The
text type described in Section 5.5 is an example of such a type that is suitable for
such purposes.
Annotations
XML Schema provides three elements for annotating schemas for the benet of both
human readers and applications. In the purchase order schema, we put a basic
schema description and copyright information inside the documentation element,
which is the recommended location for human readable material. We recommend
you use the xml:lang attribute with any documentation elements to indicate the
language of the information. Alternatively, you may indicate the language of all
information in a schema by placing an xml:lang attribute on the schema element.
The appInfo element, which we did not use in the purchase order schema, can be
used to provide information for tools, stylesheets and other applications. An
interesting example using appInfo is a schema that describes the simple types in
XML Schema Part 2: Datatypes.
Information describing this schema, for example, which facets are applicable to
particular simple types, is represented inside appInfo elements, and this
information was used by an application to automatically generate text for the XML
Schema Part 2 document.
Both documentation and appInfo appear as subelements of annotation, which may
itself appear at the beginning of most schema constructions. To illustrate, the
following example shows annotation elements appearing at the beginning of an
element declaration and a complex type denition:
Annotations in Element Declaration & Complex Type Definition
<xsd:element name="internationalPrice">
<xsd:annotation>
<xsd:documentation xml:lang="en">
element declared with anonymous type
</xsd:documentation>
</xsd:annotation>
Building Content Models
B-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<xsd:complexType>
<xsd:annotation>
<xsd:documentation xml:lang="en">
empty anonymous type with 2 attributes
</xsd:documentation>
</xsd:annotation>
<xsd:complexContent>
<xsd:restriction base="xsd:anyType">
<xsd:attribute name="currency" type="xsd:string"/>
<xsd:attribute name="value" type="xsd:decimal"/>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
The annotation element may also appear at the beginning of other schema
constructions such as those indicated by the elements schema, simpleType, and
attribute.
Building Content Models
The denitions of complex types in the purchase order schema all declare sequences
of elements that must appear in the instance document. The occurrence of
individual elements declared in the so-called content models of these types may be
optional, as indicated by a 0 value for the attribute minOccurs (for example, in
comment), or be otherwise constrained depending upon the values of minOccurs
and maxOccurs.
XML Schema also provides constraints that apply to groups of elements appearing
in a content model. These constraints mirror those available in XML 1.0 plus some
additional constraints. Note that the constraints do not apply to attributes.
XML Schema enables groups of elements to be dened and named, so that the
elements can be used to build up the content models of complex types (thus
mimicking common usage of parameter entities in XML 1.0). Un-named groups of
elements can also be dened, and along with elements in named groups, they can
be constrained to appear in the same order (sequence) as they are declared.
Alternatively, they can be constrained so that only one of the elements may appear
in an instance.
To illustrate, we introduce two groups into the PurchaseOrderType denition
from the purchase order schema so that purchase orders may contain either
separate shipping and billing addresses, or a single address for those cases in which
the shippee and billee are co-located:
Building Content Models
XML Schema Primer B-27
Nested Choice and Sequence Groups
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:choice>
<xsd:group ref="shipAndBill"/>
<xsd:element name="singleUSAddress" type="USAddress"/>
</xsd:choice>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
<xsd:group name="shipAndBill">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
</xsd:sequence>
/xsd:group>
The choice group element allows only one of its children to appear in an instance.
One child is an inner group element that references the named group shipAndBill
consisting of the element sequence shipTo, billTo, and the second child is
asingleUSAddress. Hence, in an instance document, the purchaseOrder
element must contain either a shipTo element followed by a billTo element or a
singleUSAddress element. The choice group is followed by the comment and
items element declarations, and both the choice group and the element declarations
are children of a sequence group. The effect of these various groups is that the
address element(s) must be followed by comment and items elements in that order.
There exists a third option for constraining elements in a group: All the elements in
the group may appear once or not at all, and they may appear in any order. The all
group (which provides a simplied version of the SGML &-Connector) is limited to
the top-level of any content model.
Moreover, the group's children must all be individual elements (no groups), and no
element in the content model may appear more than once, that is, the permissible
values of minOccurs and maxOccurs are 0 and 1.
For example, to allow the child elements of purchaseOrder to appear in any order,
we could redene PurchaseOrderType as:
Building Content Models
B-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
An 'All' Group
<xsd:complexType name="PurchaseOrderType">
<xsd:all>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:all>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
By this denition, a comment element may optionally appear within
purchaseOrder, and it may appear before or after any shipTo, billTo and items
elements, but it can appear only once. Moreover, the stipulations of an all group do
not allow us to declare an element such as comment outside the group as a means
of enabling it to appear more than once. XML Schema stipulates that an all group
must appear as the sole child at the top of a content model. In other words, the
following is illegal:
Illegal Example with an 'All' Group
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:all>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element name="items" type="Items"/>
</xsd:all>
<xsd:sequence>
<xsd:element ref="comment" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
Finally, named and un-named groups that appear in content models (represented
by group and choice, sequence, all respectively) may carry minOccurs and
maxOccurs attributes. By combining and nesting the various groups provided by
XML Schema, and by setting the values of minOccurs and maxOccurs, it is
possible to represent any content model expressible with an XML 1.0 DTD.
Furthermore, the all group provides additional expressive power.
Attribute Groups
XML Schema Primer B-29
Attribute Groups
To provide more information about each itemin a purchase order, for example, each
item's weight and preferred shipping method, you can add weightKg and shipBy
attribute declarations to the item element's (anonymous) type denition:
Adding Attributes to the Inline Type Definition
<xsd:element name="Item" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="partNum" type="SKU" use="required"/>
<!-- add weightKg and shipBy attributes -->
<xsd:attribute name="weightKg" type="xsd:decimal"/>
<xsd:attribute name="shipBy">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="air"/>
<xsd:enumeration value="land"/>
<xsd:enumeration value="any"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
Alternatively, you can create a named attribute group containing all the desired
attributes of an item element, and reference this group by name in the item element
declaration:
Adding Attributes Using an Attribute Group
<xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
Attribute Groups
B-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<!-- attributeGroup replaces individual declarations -->
<xsd:attributeGroup ref="ItemDelivery"/>
</xsd:complexType>
</xsd:element>
<xsd:attributeGroup name="ItemDelivery">
<xsd:attribute name="partNum" type="SKU" use="required"/>
<xsd:attribute name="weightKg" type="xsd:decimal"/>
<xsd:attribute name="shipBy">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="air"/>
<xsd:enumeration value="land"/>
<xsd:enumeration value="any"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:attributeGroup>
Using an attribute group in this way can improve the readability of schemas, and
facilitates updating schemas because an attribute group can be dened and edited
in one place and referenced in multiple denitions and declarations. These
characteristics of attribute groups make them similar to parameter entities in XML
1.0. Note that an attribute group may contain other attribute groups. Note also that
both attribute declarations and attribute group references must appear at the end of
complex type denitions.
How DTDs and XML Schema Differ
XML Schema Primer B-31
Nil Values
One of the purchase order items listed in po.xml, the Lawnmower, does not have a
shipDate element. Within the context of our scenario, the schema author may
have intended such absences to indicate items not yet shipped. But in general, the
absence of an element does not have any particular meaning: It may indicate that
the information is unknown, or not applicable, or the element may be absent for
some other reason. Sometimes it is desirable to represent an unshipped item,
unknown information, or inapplicable information explicitly with an element,
rather than by an absent element.
For example, it may be desirable to represent a null value being sent to or from a
relational database with an element that is present. Such cases can be represented
using XML Schema's nil mechanism which enables an element to appear with or
without a non-nil value.
XML Schema's nil mechanism involves an out of band nil signal. In other words,
there is no actual nil value that appears as element content, instead there is an
attribute to indicate that the element content is nil. To illustrate, we modify the
shipDate element declaration so that nils can be signalled:
<xsd:element name="shipDate" type="xsd:date" nillable="true"/>
And to explicitly represent that shipDate has a nil value in the instance document,
we set the nil attribute (from the XML Schema namespace for instances) to true:
<shipDate xsi:nil="true"></shipDate>
The nil attribute is dened as part of the XML Schema namespace for instances,
http://www.w3.org/2001/XMLSchema-instance, and so it must appear in the
instance document with a prex (such as xsi:) associated with that namespace. (As
with the xsd: prex, the xsi: prex is used by convention only.) Note that the nil
mechanism applies only to element values, and not to attribute values. An element
with xsi:nil="true may not have any element content but it may still carry
attributes.
How DTDs and XML Schema Differ
DTD is a mechanism provided by XML 1.0 for declaring constraints on XML
markup. DTDs enable you to specify the following:
I Elements that can appear in your XML documents
I Elements (or sub-elements) that can be in the elements
How DTDs and XML Schema Differ
B-32 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I The order in which the elements can appear
The XML Schema language serves a similar purpose to DTDs, but it is more exible
in specifying XML document constraints and potentially more useful for certain
applications.
XML Example
Consider the XML document:
<?xml version="1.0">
<publisher pubid="ab1234">
<publish-year>2000</publish-year>
<title>The Cat in the Hat</title>
<author>Dr. Seuss</author>
<artist>Ms. Seuss</artist>
<isbn>123456781111</isbn>
</publisher>
DTD Example
Consider a typical DTD for the foregoing XML document:
<!ELEMENT publisher (year,title, author+, artist?, isbn)>
<!ELEMENT publisher (year,title, author+, artist?, isbn)>
<!ELEMENT publish-year (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT artist (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>
...
XML Schema Example
The XML schema denition equivalent to the preceding DTD example is:
<?xml version="1.0" encoding="UTF-8"?><schema
xmlns="http://www.w3.org/2001/XMLSchema">
<element name="publisher"> <complexType>
<sequence>
<element name="publish-year" type="short"/>
<element name="title" type="string"/>
<element name="author" type="string" maxOccurs="unbounded"/>
<element name="artist" type="string" nillable="true" minOccurs="0"/>
<element name="isbn" type="long"/>
</sequence>
<attribute name="pubid" type="hexBinary" use="required"/>
How DTDs and XML Schema Differ
XML Schema Primer B-33
</complexType>
</element></schema>
DTD Limitations
DTDs, also known as XML Markup Declarations, are considered decient in
handling certain applications which include the following:
I Document authoring and publishing
I Exchange of metadata
I E-commerce
I Inter-database operations
DTD limitations include:
I No integration with Namespace technology, meaning that users cannot import
and reuse code.
I No support of datatypes other than character data, a limitation for describing
metadata standards and database schemas.
I Applications need to specify document structure constraints more exibly than
the DTD allows for.
How DTDs and XML Schema Differ
B-34 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XML Schema Features Compared to DTD Features
Table B3 lists XML Schema features. Note that XML Schema features include DTD
features.
Table B3 XML Schema Features Compared to DTD Features
XML Schema Feature DTD Features
Built-In Datatypes
XML schemas specify a set of built-in datatypes. Some
of themare dened and called primitive datatypes, and
they form the basis of the type system: string, boolean,
oat, decimal, double, duration, dateTime, time, date,
gYearMonth, gYear, gMonthDat, gMonth, gDay,
Base64Binary, HexBinary, anyURI, NOTATION,
QName
Others are derived datatypes that are dened in terms
of primitive types.
DTDs do not support datatypes other than character
strings.
User-De ned Datatypes
Users can derive their own datatypes from the built-in
datatypes. There are three ways of datatype derivation:
restriction, list, and union. Restriction denes a more
restricted datatype by applying constraining facets to
the base type, list simply allows a list of values of its
item type, and union denes a new type whose value
can be of any of its member types.
The publish-year element in the DTD example cannot
be constrained further.
For example, to specify that the value of publish-year
type to be within a specic range:
<element name="publish-year">
<simpleType>
<restriction base="short"
<minInclusive value="1970"/
<maxInclusive value="2000"/>
</restriction>
</simpleType>
</element>
Constraining facets are: length, minLength, maxLength,
pattern, enumeration, whiteSpace, maxInclusive,
maxExclusive, minInclusive, minExclusive, totalDigits,
fractionDigits
Note that some facets only apply to certain base types.
--
How DTDs and XML Schema Differ
XML Schema Primer B-35
Occurrence Indicators (Content Model or Structure)
In XML Schema, the structure (called complexType)
of an instance document or element is dened in terms
of model and attribute groups. A model group may
further contain model groups or element particles,
while an attribute group contains attributes.
Wildcards can be used in both model and attribute
groups. There are three types of model group:
sequence, all, and choice, representing the sequence,
conjunction, and disjunction relationships among
particles, respectively. The range of the number of
occurrences of each particle can also be specied.
--
Like the datatype, complexType can be derived from
other types. The derivation method can be either
restriction or extension. The derived type inherits the
content of the base type plus corresponding
modications. In addition to inheritance, a type
denition can make references to other components.
This feature allows a component to be dened once and
used in many other structures.
The type declaration and denition mechanismin XML
Schema is much more exible and powerful than in
DTDs.
--
Table B3 XML Schema Features Compared to DTD Features (Cont.)
XML Schema Feature DTD Features
How DTDs and XML Schema Differ
B-36 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XML schema can be used to dene a class of XML documents.
Instance XML Documents
An instance XML document describes an XML document that conforms to a
particular XML schema. Although these instances and XML schemas need not exist
specically as documents, they are commonly referred to as les. They may however
exist as any of the following:
I Streams of bytes
minOccurs, maxOccurs Control by DTDs over the number of child elements
in an element are assigned with the following
symbols:
I ? = zero or one. In "DTD Example" on page B-32,
artist? implied that artist is optional.
I * = zero or more.
I + = one or more in the "DTD Example" on
page B-32, author+ implies that more than one
author is possible.
I (none) = exactly one.
Identity Constraints
XML Schema extends the concept of the XML
ID/IDREF mechanism with the declarations of unique,
key and keyref. They are part of the type denition and
allow not only attributes, but also element content as
keys. Each constraint has a scope. Constraint
comparison is in terms of their value rather than lexical
strings.
None.
Import/Export Mechanisms (Schema Import,
Inclusion and Modi cation)
All components of a schema need not be dened in a
single schema le. XML Schema provides a mechanism
for assembling multiple XML schemas. Import is used
to integrate XML schemas that use different
namespaces, while inclusion is used to add
components that have the same namespace. When
components are included, they can be modied using
redenition.
You cannot use constructs dened in external
schemas.
Table B3 XML Schema Features Compared to DTD Features (Cont.)
XML Schema Feature DTD Features
XML Schema Example, PurchaseOrder.xsd
XML Schema Primer B-37
I Fields in a database record
I Collections of XML Infoset information items
Oracle XML DB supports the W3C XML Schema Recommendation specications of
May 2, 2001: http://www.w3.org/2001/XMLSchema
Converting Existing DTDs to XML Schema?
Some XML editors, such as XMLSpy, facilitate the conversion of existing DTDs to
XML schemas, however you will still need to add further typing and validation
declarations to the resulting XML schema denition le before it will be useful or
can be used as an XML schema.
XML Schema Example, PurchaseOrder.xsd
The following example PurchaseOrder.xsd, is a W3C XML Schema example, in its
native form, as an XML Document. PurchaseOrder.xsd XML schema is used for the
examples described in Chapter 3, "Using Oracle XML DB":
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="ActionsType" >
<xs:sequence>
<xs:element name="Action" maxOccurs="4" >
<xs:complexType >
<xs:sequence>
<xs:element ref="User"/>
<xs:element ref="Date"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="RejectType" >
<xs:all>
<xs:element ref="User" minOccurs="0"/>
<xs:element ref="Date" minOccurs="0"/>
<xs:element ref="Comments" minOccurs="0"/>
</xs:all>
</xs:complexType>
<xs:complexType name="ShippingInstructionsType" >
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="address"/>
XML Schema Example, PurchaseOrder.xsd
B-38 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<xs:element ref="telephone"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="LineItemsType" >
<xs:sequence>
<xs:element name="LineItem"
type="LineItemType"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="LineItemType" >
<xs:sequence>
<xs:element ref="Description"/>
<xs:element ref="Part"/>
</xs:sequence>
<xs:attribute name="ItemNumber" type="xs:integer"/>
</xs:complexType>
<!--
-->
<xs:element name="PurchaseOrder" >
<xs:complexType>
<xs:sequence>
<xs:element ref="Reference"/>
<xs:element name="Actions"
type="ActionsType"/>
<xs:element name="Reject" I
type="RejectType"
minOccurs="0"/>
<xs:element ref="Requestor"/>
<xs:element ref="User"/>
<xs:element ref="CostCenter"/>
<xs:element name="ShippingInstructions"
type="ShippingInstructionsType"/>
<xs:element ref="SpecialInstructions"/>
<xs:element name="LineItems"
type="LineItemsType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:simpleType name="money">
<xs:restriction base="xs:decimal">
<xs:fractionDigits value="2"/>
<xs:totalDigits value="12"/>
</xs:restriction>
XML Schema Example, PurchaseOrder.xsd
XML Schema Primer B-39
</xs:simpleType>
<xs:simpleType name="quantity">
<xs:restriction base="xs:decimal">
<xs:fractionDigits value="4"/>
<xs:totalDigits value="8"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="User" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="10"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Requestor" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="0"/>
<xs:maxLength value="128"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Reference" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="26"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="CostCenter" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="4"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Vendor" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="0"/>
<xs:maxLength value="20"/>
</xs:restriction>
XML Schema Example, PurchaseOrder.xsd
B-40 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</xs:simpleType>
</xs:element>
<xs:element name="PONumber" >
<xs:simpleType>
<xs:restriction base="xs:integer"/>
</xs:simpleType>
</xs:element>
<xs:element name="SpecialInstructions" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="0"/>
<xs:maxLength value="2048"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="name" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="20"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="address" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="256"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="telephone" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="24"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Date" type="xs:date" />
<xs:element name="Comments" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="2048"/>
XML Schema Example, PurchaseOrder.xsd
XML Schema Primer B-41
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Description" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="256"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Part" >
<xs:complexType>
<xs:attribute name="Id" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="12"/>
<xs:maxLength value="14"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="Quantity" type="money"/>
<xs:attribute name="UnitPrice" type="quantity"/>
</xs:complexType>
</xs:element>
</xs:schema>
XML Schema Example, PurchaseOrder.xsd
B-42 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XPath and Namespace Primer C-1
C
XPath and Namespace Primer
This appendix describes introductory information about the W3C XPath
Recommendation, Namespace Recommendation, and the Information Set (infoset).
It contains the following sections:
I Introducing the W3C XML Path Language (XPath) 1.0 Recommendation
I The XPath Expression
I Location Paths
I XPath 1.0 Data Model
I Introducing the W3C XML Path Language (XPath) 2.0 Working Draft
I Introducing the W3C Namespaces in XML Recommendation
I Introducing the W3C XML Information Set
Introducing the W3C XML Path Language (XPath) 1.0 Recommendation
C-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing the W3C XML Path Language (XPath) 1.0 Recommendation
XML Path Language (XPath) is a language for addressing parts of an XML
document, designed to be used by both XSLT and XPointer. It can be used as a
searching or query language as well as in hypertext linking. Parts of this brief XPath
primer are extracted from the W3C XPath Recommendation.
XPath also facilities the manipulation of strings, numbers and booleans.
XPath uses a compact, non-XML syntax to facilitate use of XPath in URIs and XML
attribute values. XPath operates on the abstract, logical structure of an XML
document, rather than its surface syntax. It gets its name from its use of a path
notation as in URLs for navigating through the hierarchical structure of an XML
document.
In addition to its use for addressing, XPath is also designed so that it has a natural
subset that can be used for matching, that is, testing whether or not a node matches
a pattern. This use of XPath is described in the W3C XSLT Recommendation.
XPath Models an XML Document as a Tree of Nodes
XPath models an XML document as a tree of nodes. There are different types of
nodes, including element nodes, attribute nodes, and text nodes. XPath denes a
way to compute a string-value for each type of node. Some types of nodes also have
names. XPath fully supports XML Namespaces. Thus, the name of a node is
modeled as a pair consisting of a local part and a possibly null namespace URI; this
is called an expanded-name. The data model is described in detail in "XPath 1.0
Data Model" on page C-10. A summary of XML Namespaces is provided in
"Introducing the W3C Namespaces in XML Recommendation" on page C-18.
Note: In this release, Oracle XML DB supports a subset of the
XPath 1.0 Recommendation. It does not support XPaths that return
booleans, numbers, or strings. However, Oracle XML DB does
support these XPath types within predicates.
The XPath Expression
XPath and Namespace Primer C-3
The XPath Expression
The primary syntactic construct in XPath is the expression. An expression matches
the production Expr. An expression is evaluated to yield an object, which has one
of the following four basic types:
I node-set (an unordered collection of nodes without duplicates)
I boolean (true or false)
I number (a oating-point number)
I string (a sequence of UCS characters)
Evaluating Expressions with Respect to a Context
Expression evaluation occurs with respect to a context. XSLT and XPointer specify
how the context is determined for XPath expressions used in XSLT and XPointer
respectively. The context consists of the following:
I Node, the context node
I Pair of nonzero positive integers, context position and context size. Context
position is always less than or equal to the context size.
I Set of variable bindings. These consist of a mapping from variable names to
variable values. The value of a variable is an object, which can be of any of the
types possible for the value of an expression, can also be of additional types not
specied here.
See Also:
I http://www.w3.org/TR/xpath
I http://www.w3.org/TR/xpath20/
I http://www.zvon.org/xxl/XPathTutorial/General/exa
mples.html
I http://www.mulberrytech.com/quickref/XSLTquickref
.pdf
I http://www.oreilly.com/catalog/xmlnut/chapter/ch0
9.html
I http://www.w3.org/TR/2002/NOTE-unicode-xml-200202
18/ for information about using unicode in XML.
The XPath Expression
C-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Function library. This consists of a mapping from function names to functions.
Each function takes zero or more arguments and returns a single result. See the
XPath Recommendation for the core function library denition, that all XPath
implementations must support. For a function in the core function library,
arguments and result are of the four basic types:
Node Set functions
String Functions
Boolean functions
Number functions
Both XSLT and XPointer extend XPath by dening additional functions; some of
these functions operate on the four basic types; others operate on additional
data types dened by XSLT and XPointer.
I Set of namespace declarations in scope for the expression. These consist of a
mapping from prexes to namespace URIs.
Evaluating Subexpressions
The variable bindings, function library, and namespace declarations used to
evaluate a subexpression are always the same as those used to evaluate the
containing expression.
The context node, context position, and context size used to evaluate a
subexpression are sometimes different from those used to evaluate the containing
expression. Several kinds of expressions change the context node; only predicates
change the context position and context size. When the evaluation of a kind of
expression is described, it will always be explicitly stated if the context node,
context position, and context size change for the evaluation of subexpressions; if
nothing is said about the context node, context position, and context size, they
remain unchanged for the evaluation of subexpressions of that kind of expression.
XPath Expressions Often Occur in XML Attributes
The grammar specied here applies to the attribute value after XML 1.0
normalization. So, for example, if the grammar uses the character <, this must not
appear in the XML source as < but must be quoted according to XML 1.0 rules by,
for example, entering it as &lt;.
Within expressions, literal strings are delimited by single or double quotation
marks, which are also used to delimit XML attributes. To avoid a quotation mark in
Location Paths
XPath and Namespace Primer C-5
an expression being interpreted by the XML processor as terminating the attribute
value:
I The quotation mark can be entered as a character reference (&quot; or
&apos;)
I The expression can use single quotation marks if the XML attribute is delimited
with double quotation marks or vice-versa
Location Paths
One important kind of expression is a location path. A location path is the route to
be taken. The route can consist of directions and several steps, each step being
separated by a /.
A location path selects a set of nodes relative to the context node. The result of
evaluating an expression that is a location path is the node-set containing the nodes
selected by the location path.
Location paths can recursively contain expressions used to lter sets of nodes. A
location path matches the production LocationPath.
Expressions are parsed by rst dividing the character string to be parsed into tokens
and then parsing the resulting sequence of tokens. Whitespace can be freely used
between tokens.
Although location paths are not the most general grammatical construct in the
XPath language (a LocationPath is a special case of an Expr), they are the most
important construct.
Location Path Syntax Abbreviations
Every location path can be expressed using a straightforward but rather verbose
syntax. There are also a number of syntactic abbreviations that allow common cases
to be expressed concisely. The next sections:
I "Location Path Examples Using Unabbreviated Syntax" on page C-5 describes
the semantics of location paths using the unabbreviated syntax
I "Location Path Examples Using Abbreviated Syntax" on page C-7 describes the
unabbreviated syntax
Location Path Examples Using Unabbreviated Syntax
Table C1 lists examples of location paths using the unabbreviated syntax.
Location Paths
C-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Table C1 XPath: Location Path Examples Using Unabbreviated Syntax
Unabbreviated Location Path Description
child::para Selects the para element children of the context node
child::* Selects all element children of the context node
child::text() Selects all text node children of the context node
child::node() Selects all the children of the context node, whatever their
node type
attribute::name Selects the name attribute of the context node
attribute::* Selects all the attributes of the context
nodedescendant::para Selects the para element descendants of the context node
ancestor::div Selects all div ancestors of the context node
ancestor-or-self::div Selects the div ancestors of the context node and, if the
context node is a div element, the context node as well
descendant-or-self::para Selects the para element descendants of the context node and,
if the context node is a para element, the context node as well
self::para Selects the context node if it is a para element, and otherwise
selects nothing
child::chapter/descendant::para Selects the para element descendants of the chapter element
children of the context node
child::*/child::para Selects all para grandchildren of the context node
/ Selects the document root which is always the parent of the
document element
/descendant::para Selects all the para elements in the same document as the
context node
/descendant::olist/child::item Selects all the itemelements that have an olist parent and that
are in the same document as the context node
child::para[position()=1] Selects the rst para child of the context node
child::para[position()=last()] Selects the last para child of the context node
child::para[position()=last()-1] Selects the last but one para child of the context node
child::para[position()>1] Selects all the para children of the context node other than the
rst para child of the context node
following-sibling::chapter[position()=1] Selects the next chapter sibling of the context node
preceding-sibling::chapter[position()=1] Selects the previous chapter sibling of the context node
Location Paths
XPath and Namespace Primer C-7
Location Path Examples Using Abbreviated Syntax
Table C2 lists examples of location paths using abbreviated syntax.
/descendant::gure[position()=42] Selects the forty-second gure element in the document
/child::doc/child::chapter[position()=5]/child::section
[position()=2]
Selects the second section of the fth chapter of the doc
document element
child::para[attribute::type="warning"] Selects all para children of the context node that have a type
attribute with value warning
child::para[attribute::type='warning'][position()=5] Selects the fth para child of the context node that has a type
attribute with value warning
child::para[position()=5][attribute::type= "warning"] Selects the fth para child of the context node if that child has
a type attribute with value warning
child::chapter[child::title='Introduction'] Selects the chapter children of the context node that have one
or more title children with string-value equal to Introduction
child::chapter[child::title] Selects the chapter children of the context node that have one
or more title children
child::*[self::chapter or self::appendix] Selects the chapter and appendix children of the context node
child::*[self::chapter or self::appendix][position()=last()] Selects the last chapter or appendix child of the context node
Table C2 XPath: Location Path Examples Using Abbreviated Syntax
Abbreviated Location Path Description
para Selects the para element children of the context node
* Selects all element children of the context node
text() Selects all text node children of the context node
@name Selects the name attribute of the context node
@* Selects all the attributes of the context node
para[1] Selects the rst para child of the context node
para[last()] Selects the last para child of the context node
*/para Selects all para grandchildren of the context node
/doc/chapter[5]/section[2] Selects the second section of the fth chapter of the doc
Table C1 XPath: Location Path Examples Using Unabbreviated Syntax (Cont.)
Unabbreviated Location Path Description
Location Paths
C-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The most important abbreviation is that child:: can be omitted from a location
step. In effect, child is the default axis. For example, a location path div/para is
short for child::div/child::para.
Attribute Abbreviation @
There is also an abbreviation for attributes: attribute:: can be abbreviated to @.
For example, a location path para[@type="warning"] is short for
child::para[attribute::type="warning"] and so selects para children
with a type attribute with value equal to warning.
chapter//para Selects the para element descendants of the chapter element
children of the context node
//para Selects all the para descendants of the document root and
thus selects all para elements in the same document as the
context node
//olist/item Selects all the item elements in the same document as the
context node that have an olist parent
. Selects the context node
.//para Selects the para element descendants of the context node
.. Selects the parent of the context node
../@lang Selects the lang attribute of the parent of the context node
para[@type="warning"] Selects all para children of the context node that have a type
attribute with value warning
para[@type="warning"][5] Selects the fth para child of the context node that has a type
attribute with value warning
para[5][@type="warning"] Selects the fth para child of the context node if that child has
a type attribute with value warning
chapter[title="Introduction"] Selects the chapter children of the context node that have one
or more title children with string-value equal to Introduction
chapter[title] Selects the chapter children of the context node that have one
or more title children
employee[@secretary and @assistant] Selects all the employee children of the context node that
have both a secretary attribute and an assistant attribute
Table C2 XPath: Location Path Examples Using Abbreviated Syntax (Cont.)
Abbreviated Location Path Description
Location Paths
XPath and Namespace Primer C-9
Path Abbreviation //
// is short for /descendant-or-self::node()/. For example, //para is short
for /descendant-or-self::node()/child::para and so will select any para
element in the document (even a para element that is a document element will be
selected by //para since the document element node is a child of the root node);
div//para is short for div/descendant-or-self::node()/child::para
and so will select all para descendants of div children.
Location Step Abbreviation .
A location step of . is short for self::node(). This is particularly useful in
conjunction with //. For example, the location path .//para is short for:
self::node()/descendant-or-self::node()/child::para
and so will select all para descendant elements of the context node.
Location Step Abbreviation ..
Similarly, a location step of .. is short for parent::node(). For example,
../title is short for:
parent::node()/child::title
and so will select the title children of the parent of the context node.
Abbreviation Summary
AbbreviatedAbsoluteLocationPath ::= '//' RelativeLocationPath
AbbreviatedRelativeLocationPath ::= RelativeLocationPath '//' Step
AbbreviatedStep ::= '.' | '..'
AbbreviatedAxisSpecier ::= '@'?
Relative and Absolute Location Paths
There are two kinds of location path:
Note: Location path //para[1] does not mean the same as the
location path /descendant::para[1]. The latter selects the rst
descendant para element; the former selects all descendant para
elements that are the rst para children of their parents.
XPath 1.0 Data Model
C-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
I Relative location paths. Arelative location path consists of a sequence of one or
more location steps separated by /. The steps in a relative location path are
composed together from left to right. Each step in turn selects a set of nodes
relative to a context node. An initial sequence of steps is composed together
with a following step as follows. The initial sequence of steps selects a set of
nodes relative to a context node. Each node in that set is used as a context node
for the following step. The sets of nodes identied by that step are unioned
together. The set of nodes identied by the composition of the steps is this
union.
For example, child::div/child::para selects the para element children of
the div element children of the context node, or, in other words, the para
element grandchildren that have div parents.
I Absolute location paths. An absolute location path consists of / optionally
followed by a relative location path. A / by itself selects the root node of the
document containing the context node. If it is followed by a relative location
path, then the location path selects the set of nodes that would be selected by
the relative location path relative to the root node of the document containing
the context node.
Location Path Syntax Summary
Location path provides a means to search for target nodes. Here is the general
syntax for location path:
axisname :: nodetest expr1 expr2 ...
LocationPath ::= RelativeLocationPath
| AbsoluteLocationPath
AbsoluteLocationPath ::= '/' RelativeLocationPath?
| AbbreviatedAbsoluteLocationPath
RelativeLocationPath ::= Step
| RelativeLocationPath '/' Step
| AbbreviatedRelativeLocationPath
XPath 1.0 Data Model
XPath operates on an XML document as a tree. This section describes how XPath
models an XML document as a tree. The relationship of this model to the XML
documents operated on by XPath must conform to the XML Namespaces
Recommendation.
XPath 1.0 Data Model
XPath and Namespace Primer C-11
Nodes
The tree contains nodes. There are seven types of node:
I Root Nodes
I Element Nodes
I Text Nodes
I Attribute Nodes
I Namespace Nodes
I Processing Instruction Nodes
I Comment Nodes
Root Nodes
The root node is the root of the tree. It does not occur except as the root of the tree.
The element node for the document element is a child of the root node. The root
node also has as children processing instruction and comment nodes for processing
instructions and comments that occur in the prolog and after the end of the
document element. The string-value of the root node is the concatenation of the
string-values of all text node descendants of the root node in document order. The
root node does not have an expanded-name.
Element Nodes
There is an element node for every element in the document. An element node has
an expanded-name computed by expanding the QName of the element specied in
the tag in accordance with the XML Namespaces Recommendation. The namespace
URI of the element's expanded-name will be null if the QName has no prex and
there is no applicable default namespace.
See Also: Introducing the W3C Namespaces in XML
Recommendation on page C-18
XPath 1.0 Data Model
C-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The children of an element node are the element nodes, comment nodes, processing
instruction nodes and text nodes for its content. Entity references to both internal
and external entities are expanded. Character references are resolved. The
string-value of an element node is the concatenation of the string-values of all text
node descendants of the element node in document order.
Unique IDs. An element node may have a unique identier (ID). This is the value
of the attribute that is declared in the DTD as type ID. No two elements in a
document may have the same unique ID. If an XML processor reports two elements
in a document as having the same unique ID (which is possible only if the
document is invalid) then the second element in document order must be treated as
not having a unique ID.
Text Nodes
Character data is grouped into text nodes. As much character data as possible is
grouped into each text node: a text node never has an immediately following or
preceding sibling that is a text node. The string-value of a text node is the character
data. A text node always has at least one character of data. Each character within a
CDATA section is treated as character data. Thus, <![CDATA[<]]> in the source
document will treated the same as &lt;. Both will result in a single < character in a
text node in the tree. Thus, a CDATA section is treated as if the <![CDATA[ and ]]>
were removed and every occurrence of < and & were replaced by &lt; and &amp;
respectively.
Note: In the notation of Appendix A.3 of
http://www.w3.org/TR/REC-xml-names/, the local part of
the expanded-name corresponds to the type attribute of the
ExpEType element; the namespace URI of the expanded-name
corresponds to the ns attribute of the ExpEType element, and is null
if the ns attribute of the ExpEType element is omitted.
Note: If a document does not have a DTD, then no element in the
document will have a unique ID.
XPath 1.0 Data Model
XPath and Namespace Primer C-13
Attribute Nodes
Each element node has an associated set of attribute nodes; the element is the parent
of each of these attribute nodes; however, an attribute node is not a child of its
parent element.
Elements never share attribute nodes: if one element node is not the same node as
another element node, then none of the attribute nodes of the one element node will
be the same node as the attribute nodes of another element node.
A defaulted attribute is treated the same as a specied attribute. If an attribute was
declared for the element type in the DTD, but the default was declared as
#IMPLIED, and the attribute was not specied on the element, then the element's
attribute set does not contain a node for the attribute.
Some attributes, such as xml:lang and xml:space, have the semantics that they
apply to all elements that are descendants of the element bearing the attribute,
unless overridden with an instance of the same attribute on another descendant
element. However, this does not affect where attribute nodes appear in the tree: an
element has attribute nodes only for attributes that were explicitly specied in the
start-tag or empty-element tag of that element or that were explicitly declared in the
DTD with a default value.
Note: When a text node that contains a < character is written out
as XML, the < character must be escaped by for example, using &lt;,
or including it in a CDATA section. Characters inside comments,
processing instructions and attribute values do not produce text
nodes. Line-endings in external entities are normalized to #xA as
specied in the XML Recommendation. A text node does not have
an expanded-name.
Note: This is different from the DOM, which does not treat the
element bearing an attribute as the parent of the attribute.
Note: The = operator tests whether two nodes have the same
value, not whether they are the same node. Thus attributes of two
different elements may compare as equal using =, even though they
are not the same node.
XPath 1.0 Data Model
C-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
An attribute node has an expanded-name and a string-value. The expanded-name
is computed by expanding the QName specied in the tag in the XML document in
accordance with the XML Namespaces Recommendation. The namespace URI of
the attribute's name will be null if the QName of the attribute does not have a
prex.
An attribute node has a string-value. The string-value is the normalized value as
specied by the XML Recommendation. An attribute whose normalized value is a
zero-length string is not treated specially: it results in an attribute node whose
string-value is a zero-length string.
There are no attribute nodes corresponding to attributes that declare namespaces.
Namespace Nodes
Each element has an associated set of namespace nodes, one for each distinct
namespace prex that is in scope for the element (including the xml prex, which is
implicitly declared by the XML Namespaces Recommendation) and one for the
default namespace if one is in scope for the element. The element is the parent of
each of these namespace nodes; however, a namespace node is not a child of its
parent element.
Elements never share namespace nodes: if one element node is not the same node as
another element node, then none of the namespace nodes of the one element node
Note: In the notation of Appendix A.3 of XML Namespaces
Recommendation, the local part of the expanded-name corresponds
to the name attribute of the ExpAName element; the namespace URI
of the expanded-name corresponds to the ns attribute of the
ExpAName element, and is null if the ns attribute of the ExpAName
element is omitted.
Note: It is possible for default attributes to be declared in an
external DTD or an external parameter entity. The XML
Recommendation does not require an XML processor to read an
external DTD or an external parameter unless it is validating. A
stylesheet or other facility that assumes that the XPath tree contains
default attribute values declared in an external DTD or parameter
entity may not work with some non-validating XML processors.
XPath 1.0 Data Model
XPath and Namespace Primer C-15
will be the same node as the namespace nodes of another element node. This means
that an element will have a namespace node:
I For every attribute on the element whose name starts with xmlns:;
I For every attribute on an ancestor element whose name starts xmlns: unless the
element itself or a nearer ancestor re-declares the prex;
I For an xmlns attribute, if the element or some ancestor has an xmlns attribute,
and the value of the xmlns attribute for the nearest such element is non-empty
A namespace node has an expanded-name: the local part is the namespace prex
(this is empty if the namespace node is for the default namespace); the namespace
URI is always NULL.
The string-value of a namespace node is the namespace URI that is being bound to
the namespace prex; if it is relative, it must be resolved just like a namespace URI
in an expanded-name.
Processing Instruction Nodes
There is a processing instruction node for every processing instruction, except for
any processing instruction that occurs within the document type declaration.
A processing instruction has an expanded-name: the local part is the processing
instruction's target; the namespace URI is NULL. The string-value of a processing
instruction node is the part of the processing instruction following the target and
any whitespace. It does not include the terminating ?>.
Comment Nodes
There is a comment node for every comment, except for any comment that occurs
within the document type declaration. The string-value of comment is the content
of the comment not including the opening <!-- or the closing -->. A comment node
does not have an expanded-name.
Note: An attribute xmlns="" "undeclares" the default
namespace.
Note: The XML declaration is not a processing instruction.
Therefore, there is no processing instruction node corresponding to
the XML declaration.
XPath 1.0 Data Model
C-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
For every type of node, there is a way of determining a string-value for a node of
that type. For some types of node, the string-value is part of the node; for other
types of node, the string-value is computed from the string-value of descendant
nodes.
Expanded-Name
Some types of node also have an expanded-name, which is a pair consisting of:
I A local part. This is a string.
I A namespace URI. The namespace URI is either null or a string. If specied in
the XML document it can be a URI reference as dened in RFC2396; this means
it can have a fragment identier and be relative. A relative URI should be
resolved into an absolute URI during namespace processing: the namespace
URIs of expanded-names of nodes in the data model should be absolute.
Two expanded-names are equal if they have the same local part, and either both
have a null namespace URI or both have non-null namespace URIs that are equal.
Document Order
There is an ordering, document order, dened on all the nodes in the document
corresponding to the order in which the rst character of the XML representation of
each node occurs in the XML representation of the document after expansion of
general entities. Thus, the root node will be the rst node.
Element nodes occur before their children. Thus, document order orders element
nodes in order of the occurrence of their start-tag in the XML (after expansion of
entities). The attribute nodes and namespace nodes of an element occur before the
children of the element. The namespace nodes are dened to occur before the
attribute nodes.
The relative order of namespace nodes is implementation-dependent.
The relative order of attribute nodes is implementation-dependent.
Reverse document order is the reverse of document order.
Root nodes and element nodes have an ordered list of child nodes. Nodes never
share children: if one node is not the same node as another node, then none of the
Note: For element nodes and root nodes, the string-value of a
node is not the same as the string returned by the DOM nodeValue
method.
Introducing the W3C XML Path Language (XPath) 2.0 Working Draft
XPath and Namespace Primer C-17
children of the one node will be the same node as any of the children of another
node.
Every node other than the root node has exactly one parent, which is either an
element node or the root node. A root node or an element node is the parent of each
of its child nodes. The descendants of a node are the children of the node and the
descendants of the children of the node.
Introducing the W3C XML Path Language (XPath) 2.0 Working Draft
XPath 2.0 is the result of joint work by the W3C XSL and XML Query Working
Groups. XPath 2.0 is a language derived from both XPath 1.0 and XQuery. The
XPath 2.0 and XQuery 1.0 Working Drafts are generated from a common source.
These languages are closely related and share much of the same expression syntax
and semantics. The two Working Drafts in places are identical.
XPath is designed to be embedded in a host language such as XSLT or XQuery.
XPath has a natural subset that can be used for matching, that is, testing whether or
not a node matches a pattern.
XQuery Version 1.0 contains XPath Version 2.0 as a subset. Any expression that is
syntactically valid and executes successfully in both XPath 2.0 and XQuery 1.0 will
return the same result in both languages.
XPath also depends on and is closely related to the following specications:
I The XPath data model denes the information in an XML document that is
available to an XPath processor. The data model is dened in XQuery 1.0 and
XPath 2.0 Data Model.
I The static and dynamic semantics of XPath are formally dened in XQuery 1.0
Formal Semantics. This is done by mapping the full XPath language into a
"core" subset for which the semantics is dened. This document is useful for
implementers and others who require a rigorous denition of XPath.
I The library of functions and operators supported by XPath is dened in XQuery
1.0 and XPath 2.0 Functions and Operators.
XPath 2.0 Expressions
The basic building block of XPath is the expression. The language provides several
kinds of expressions which may be constructed from keywords, symbols, and
operands. In general, the operands of an expression are other expressions.
Introducing the W3C Namespaces in XML Recommendation
C-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XPath is a functional language which allows various kinds of expressions to be
nested with full generality. It is also a strongly-typed language in which the
operands of various expressions, operators, and functions must conform to
designated types.
Like XML, XPath is a case-sensitive language. All keywords in XPath use lower-case
characters.
Expr
::=
OrExpr
| AndExpr
| ForExpr
| QuantifiedExpr
| IfExpr
| GeneralComp
| ValueComp
| NodeComp
| OrderComp
| InstanceofExpr
| RangeExpr
| AdditiveExpr
| MultiplicativeExpr
| UnionExpr
| IntersectExceptExpr
| UnaryExpr
| CastExpr
| PathExpr
Introducing the W3C Namespaces in XML Recommendation
Software modules must recognize tags and attributes which they are designed to
process, even in the face of "collisions" occurring when markup intended for some
other software package uses the same element type or attribute name.
Document constructs should have universal names, whose scope extends beyond
their containing document. The W3C Namespaces in XML Recommendation
describes the mechanism, XML namespaces, which accomplishes this.
See Also: http://www.w3.org/TR/REC-xml-names/
Introducing the W3C Namespaces in XML Recommendation
XPath and Namespace Primer C-19
What Is a Namespace?
An XML namespace is a collection of names, identied by a URI reference
[RFC2396], which are used in XML documents as element types and attribute
names. XML namespaces differ from the "namespaces" conventionally used in
computing disciplines in that the XML version has internal structure and is not,
mathematically speaking, a set. These issues are discussed in the W3C Namespace
Recommendation, appendix, "A. The Internal Structure of XML Namespaces".
URI References
URI references which identify namespaces are considered identical when they are
exactly the same character-for-character. Note that URI references which are not
identical in this sense may in fact be functionally equivalent. Examples include URI
references which differ only in case, or which are in external entities which have
different effective base URIs.
Names from XML namespaces may appear as qualied names, which contain a
single colon, separating the name into a namespace prex and a local part.
The prex, which is mapped to a URI reference, selects a namespace. The
combination of the universally managed URI namespace and the document's own
namespace produces identiers that are universally unique. Mechanisms are
provided for prex scoping and defaulting.
URI references can contain characters not allowed in names, so cannot be used
directly as namespace prexes. Therefore, the namespace prex serves as a proxy
for a URI reference. An attribute-based syntax described in the following section is
used to declare the association of the namespace prex with a URI reference;
software which supports this namespace proposal must recognize and act on these
declarations and prexes.
Notation and Usage
Many of the nonterminals in the productions in this specication are dened not
here but in the W3C XML Recommendation. When nonterminals dened here have
the same names as nonterminals dened in the W3C XML Recommendation, the
productions here in all cases match a subset of the strings matched by the
corresponding ones there.
In this document's productions, the NSC is a "Namespace Constraint", one of the
rules that documents conforming to this specication must follow.
All Internet domain names used in examples, with the exception of w3.org, are
selected at random and should not be taken as having any import.
Introducing the W3C Namespaces in XML Recommendation
C-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Declaring Namespaces
A namespace is declared using a family of reserved attributes. Such an attribute's
name must either be xmlns or have xmlns: as a prex. These attributes, like any
other XML attributes, can be provided directly or by default.
Attribute Names for Namespace Declaration
[1] NSAttName ::= PrefixedAttName
| DefaultAttName
[2] PrefixedAttName ::= 'xmlns:' NCName
[NSC: Leading "XML" ]
[3] DefaultAttName ::= 'xmlns'
[4] NCName ::= (Letter | '_') (NCNameChar)*
/* An XML Name, minus the ":" */
[5] NCNameChar ::= Letter | Digit | '.' | '-' | '_' | CombiningChar
| Extender
The attribute's value, a URI reference, is the namespace name identifying the
namespace. The namespace name, to serve its intended purpose, should have the
characteristics of uniqueness and persistence. It is not a goal that it be directly
usable for retrieval of a schema (if any exists). An example of a syntax that is
designed with these goals in mind is that for Uniform Resource Names [RFC2141].
However, it should be noted that ordinary URLs can be managed in such a way as
to achieve these same goals.
When the Attribute Name Matches the PrefixedAttName
If the attribute name matches PrefixedAttName, then the NCName gives the
namespace prex, used to associate element and attribute names with the
namespace name in the attribute value in the scope of the element to which the
declaration is attached. In such declarations, the namespace name may not be
empty.
When the Attribute Name Matches the DefaultAttName
If the attribute name matches DefaultAttName, then the namespace name in the
attribute value is that of the default namespace in the scope of the element to which
the declaration is attached. In such a default declaration, the attribute value may be
empty. Default namespaces and overriding of declarations are discussed in section
"Applying Namespaces to Elements and Attributes" on page C-23 of the W3C
Namespace Recommendation.
Introducing the W3C Namespaces in XML Recommendation
XPath and Namespace Primer C-21
The following example namespace declaration associates the namespace prex edi
with the namespace name http://ecommerce.org/schema:
<x xmlns:edi='http://ecommerce.org/schema'>
<!-- the "edi" prefix is bound to http://ecommerce.org/schema
for the "x" element and contents -->
</x>
Namespace Constraint: Leading "XML"
Prexes beginning with the three-letter sequence x, m, l, in any case combination,
are reserved for use by XML and XML-related specications.
Qualied Names
In XML documents conforming to the W3C Namespace Recommendation, some
names (constructs corresponding to the nonterminal Name) may be given as
qualied names, dened as follows:
Qualified Name Syntax
[6] QName ::= (Prefix ':')? LocalPart
[7] Prefix ::= NCName
[8] LocalPart::= NCName
What is the Prefix?
The Prex provides the namespace prex part of the qualied name, and must be
associated with a namespace URI reference in a namespace declaration.
The LocalPart provides the local part of the qualied name. Note that the prex
functions only as a placeholder for a namespace name. Applications should use the
namespace name, not the prex, in constructing names whose scope extends
beyond the containing document.
Using Qualied Names
In XML documents conforming to the W3C Namespace Recommendation, element
types are given as qualied names, as follows:
Element Types
[9] STag ::= '<' QName (S Attribute)* S? '>' [NSC: Prefix Declared ]
[10] ETag::= '</' QName S? '>'[NSC: Prefix Declared ]
[11] EmptyElemTag ::= '<' QName (S Attribute)* S? '/>' [NSC: Prefix Declared ]
Introducing the W3C Namespaces in XML Recommendation
C-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
The following is an example of a qualied name serving as an element type:
<x xmlns:edi='http://ecommerce.org/schema'>
<!-- the 'price' element's namespace is http://ecommerce.org/schema -->
<edi:price units='Euro'>32.18</edi:price>
</x>
Attributes are either namespace declarations or their names are given as qualied
names:
Attribute
[12] Attribute::= NSAttName Eq AttValue|QName Eq AttValue [NSC:Prefix Declared]
The following is an example of a qualied name serving as an attribute name:
<x xmlns:edi='http://ecommerce.org/schema'>
<!-- the 'taxClass' attribute's namespace is http://ecommerce.org/schema -->
<lineItem edi:taxClass="exempt">Baby food</lineItem>
</x>
Namespace Constraint: Prex Declared
The namespace prex, unless it is xml or xmlns, must have been declared in a
namespace declaration attribute in either the start-tag of the element where the
prex is used or in an ancestor element, that is, an element in whose content the
prexed markup occurs:
The prex xml is by denition bound to the namespace name
http://www.w3.org/XML/1998/namespace.
The prex xmlns is used only for namespace bindings and is not itself bound to
any namespace name.
This constraint may lead to operational difculties in the case where the namespace
declaration attribute is provided, not directly in the XML document entity, but
through a default attribute declared in an external entity. Such declarations may not
be read by software which is based on a non-validating XML processor.
Many XML applications, presumably including namespace-sensitive ones, fail to
require validating processors. For correct operation with such applications,
namespace declarations must be provided either directly or through default
attributes declared in the internal subset of the DTD.
Introducing the W3C Namespaces in XML Recommendation
XPath and Namespace Primer C-23
Element names and attribute types are also given as qualied names when they
appear in declarations in the DTD:
Qualified Names in Declarations
[13] doctypedecl::= '<!DOCTYPE' S QName (S ExternalID)? S? ('[' (markupdecl |
PEReference | S)* ']' S?)? '>'
[14] elementdecl::= '<!ELEMENT' S QName S contentspec S? '>'
[15] cp ::= (QName | choice | seq) ('?' | '*' | '+')?
[16] Mixed ::= '(' S? '#PCDATA' (S? '|' S? QName)* S? ')*'
| '(' S? '#PCDATA' S? ')'
[17] AttlistDecl::= '<!ATTLIST' S QName AttDef* S? '>'
[18] AttDef ::= S (QName | NSAttName) S AttType S DefaultDecl
Applying Namespaces to Elements and Attributes
Namespace Scoping
The namespace declaration is considered to apply to the element where it is
specied and to all elements within the content of that element, unless overridden
by another namespace declaration with the same NSAttName part:
<?xml version="1.0"?>
<!-- all elements here are explicitly in the HTML namespace -->
<html:html xmlns:html='http://www.w3.org/TR/REC-html40'>
<html:head><html:title>Frobnostication</html:title></html:head>
<html:body><html:p>Moved to
<html:a href='http://frob.com'>here.</html:a></html:p></html:body>
</html:html>
Multiple namespace prexes can be declared as attributes of a single element, as
shown in this example:
<?xml version="1.0"?>
<!-- both namespace prefixes are available throughout -->
<bk:book xmlns:bk='urn:loc.gov:books'
xmlns:isbn='urn:ISBN:0-395-36341-6'>
<bk:title>Cheaper by the Dozen</bk:title>
<isbn:number>1568491379</isbn:number>
</bk:book>
Introducing the W3C Namespaces in XML Recommendation
C-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Namespace Defaulting
A default namespace is considered to apply to the element where it is declared (if
that element has no namespace prex), and to all elements with no prex within the
content of that element. If the URI reference in a default namespace declaration is
empty, then un-prexed elements in the scope of the declaration are not considered
to be in any namespace. Note that default namespaces do not apply directly to
attributes.
<?xml version="1.0"?>
<!-- elements are in the HTML namespace, in this case by default -->
<html xmlns='http://www.w3.org/TR/REC-html40'>
<head><title>Frobnostication</title></head>
<body><p>Moved to
<a href='http://frob.com'>here</a>.</p></body>
</html>
<?xml version="1.0"?>
<!-- unprefixed element types are from "books" -->
<book xmlns='urn:loc.gov:books'
xmlns:isbn='urn:ISBN:0-395-36341-6'>
<title>Cheaper by the Dozen</title>
<isbn:number>1568491379</isbn:number>
</book>
A larger example of namespace scoping:
<?xml version="1.0"?>
<!-- initially, the default namespace is "books" -->
<book xmlns='urn:loc.gov:books'
xmlns:isbn='urn:ISBN:0-395-36341-6'>
<title>Cheaper by the Dozen</title>
<isbn:number>1568491379</isbn:number>
<notes>
<!-- make HTML the default namespace for some commentary -->
<p xmlns='urn:w3-org-ns:HTML'>
This is a <i>funny</i> book!
</p>
</notes>
</book>
The default namespace can be set to the empty string. This has the same effect,
within the scope of the declaration, of there being no default namespace.
<?xml version='1.0'?>
<Beers>
Introducing the W3C Namespaces in XML Recommendation
XPath and Namespace Primer C-25
<!-- the default namespace is now that of HTML -->
<table xmlns='http://www.w3.org/TR/REC-html40'>
<th><td>Name</td><td>Origin</td><td>Description</td></th>
<tr>
<!-- no default namespace inside table cells -->
<td><brandName xmlns="">Huntsman</brandName></td>
<td><origin xmlns="">Bath, UK</origin></td>
<td>
<details xmlns=""><class>Bitter</class><hop>Fuggles</hop>
<pro>Wonderful hop, light alcohol, good summer beer</pro>
<con>Fragile; excessive variance pub to pub</con>
</details>
</td>
</tr>
</table>
</Beers>
Uniqueness of Attributes
In XML documents conforming to this specication, no tag may contain two
attributes which:
I Have identical names, or
I Have qualied names with the same local part and with prexes which have
been bound to namespace names that are identical.
For example, each of the bad start-tags is illegal in the following:
<!-- http://www.w3.org is bound to n1 and n2 -->
<x xmlns:n1="http://www.w3.org"
xmlns:n2="http://www.w3.org" >
<bad a="1" a="2" />
<bad n1:a="1" n2:a="2" />
</x>
However, each of the following is legal, the second because the default namespace
does not apply to attribute names:
<!-- http://www.w3.org is bound to n1 and is the default -->
<x xmlns:n1="http://www.w3.org"
xmlns="http://www.w3.org" >
<good a="1" b="2" />
<good a="1" n1:a="2" />
</x>
Introducing the W3C XML Information Set
C-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Conformance of XML Documents
In XML documents which conform to the W3C Namespace Recommendation,
element types and attribute names must match the production for QName and must
satisfy the "Namespace Constraints".
An XML document conforms to this specication if all other tokens in the document
which are required, for XML conformance, to match the XML production for Name,
match this specication's production for NCName.
The effect of conformance is that in such a document:
I All element types and attribute names contain either zero or one colon.
I No entity names, PI targets, or notation names contain any colons.
Strictly speaking, attribute values declared to be of types ID, IDREF(S),
ENTITY(IES), and NOTATION are also Names, and thus should be colon-free.
However, the declared type of attribute values is only available to processors which
read markup declarations, for example validating processors. Thus, unless the use
of a validating processor has been specied, there can be no assurance that the
contents of attribute values have been checked for conformance to this specication.
The following W3C Namespace Recommendation Appendixes are not included in
this primer:
I A. The Internal Structure of XML Namespaces (Non-Normative)
I A.1 The Insufciency of the Traditional Namespace
I A.2 XML Namespace Partitions
I A.3 Expanded Element Types and Attribute Names
I A.4 Unique Expanded Attribute Names
Introducing the W3C XML Information Set
The W3C XML Information Set specication denes an abstract data set called the
XML Information Set (Infoset). It provides a consistent set of denitions for use in
other specications that need to refer to the information in a well-formed XML
document.
The primary criterion for inclusion of an information itemor property has been that
of expected usefulness in future specications. It does not constitute a minimum set
of information that must be returned by an XML processor.
Introducing the W3C XML Information Set
XPath and Namespace Primer C-27
An XML document has an information set if it is well-formed and satises the
namespace constraints described in the following section.
There is no requirement for an XML document to be valid in order to have an
information set.
Information sets may be created by methods (not described in this specication)
other than parsing an XML document. See "Synthetic Infosets" on page C-29.
An XML document's information set consists of a number of information items; the
information set for any well-formed XML document will contain at least a
document information item and several others. An information item is an abstract
description of some part of an XML document: each information item has a set of
associated named properties. In this specication, the property names are shown in
square brackets, [thus]. The types of information item are listed in section 2.
The XML Information Set does not require or favor a specic interface or class of
interfaces. This specication presents the information set as a modied tree for the
sake of clarity and simplicity, but there is no requirement that the XML Information
Set be made available through a tree structure; other types of interfaces, including
(but not limited to) event-based and query-based interfaces, are also capable of
providing information conforming to the XML Information Set.
The terms "information set" and "information item" are similar in meaning to the
generic terms "tree" and "node", as they are used in computing. However, the
former terms are used in this specication to reduce possible confusion with other
specic data models. Information items do not map one-to-one with the nodes of
the DOM or the "tree" and "nodes" of the XPath data model.
In this specication, the words "must", "should", and "may" assume the meanings
specied in [RFC2119], except that the words do not appear in uppercase.
Namespaces
XML 1.0 documents that do not conform to the W3C Namespace Recommendation,
though technically well-formed, are not considered to have meaningful information
sets. That is, this specication does not dene an information set for documents that
have element or attribute names containing colons that are used in other ways than
as prescribed by the W3C Namespace Recommendation.
Also, the XML Infoset specication does not dene an information set for
documents which use relative URI references in namespace declarations. This is in
See Also: http://www.w3.org/TR/xml-infoset/
Introducing the W3C XML Information Set
C-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
accordance with the decision of the W3C XML Plenary Interest Group described in
Relative Namespace URI References in the W3C Namespace Recommendation.
The value of a namespace name property is the normalized value of the
corresponding namespace attribute; no additional URI escaping is applied to it by
the processor.
Entities
An information set describes its XML document with entity references already
expanded, that is, represented by the information items corresponding to their
replacement text. However, there are various circumstances in which a processor
may not perform this expansion. An entity may not be declared, or may not be
retrievable. A non-validating processor may choose not to read all declarations, and
even if it does, may not expand all external entities. In these cases an un-expanded
entity reference information item is used to represent the entity reference.
End-of-Line Handling
The values of all properties in the Infoset take account of the end-of-line
normalization described in the XML Recommendation, 2.11 "End-of-Line
Handling".
Base URIs
Several information items have a base URI or declaration base URI property. These
are computed according to XML Base. Note that retrieval of a resource may involve
redirection at the parser level (for example, in an entity resolver) or at a lower level;
in this case the base URI is the nal URI used to retrieve the resource after all
redirection.
The value of these properties does not reect any URI escaping that may be
required for retrieval of the resource, but it may include escaped characters if these
were specied in the document, or returned by a server in the case of redirection.
In some cases (such as a document read from a string or a pipe) the rules in XML
Base may result in a base URI being application dependent. In these cases this
specication does not dene the value of the base URI or declaration base URI
property.
When resolving relative URIs the base URI property should be used in preference
to the values of xml:base attributes; they may be inconsistent in the case of Synthetic
Infosets.
Introducing the W3C XML Information Set
XPath and Namespace Primer C-29
Unknown and No Value
Some properties may sometimes have the value unknown or no value, and it is
said that a property value is unknown or that a property has no value respectively.
These values are distinct from each other and from all other values. In particular
they are distinct from the empty string, the empty set, and the empty list, each of
which simply has no members. This specication does not use the termnull since in
some communities it has particular connotations which may not match those
intended here.
Synthetic Infosets
This specication describes the information set resulting from parsing an XML
document. Information sets may be constructed by other means, for example by use
of an API such as the DOM or by transforming an existing information set.
An information set corresponding to a real document will necessarily be consistent
in various ways; for example the in-scope namespaces property of an element will
be consistent with the [namespace attributes] properties of the element and its
ancestors. This may not be true of an information set constructed by other means; in
such a case there will be no XML document corresponding to the information set,
and to serialize it will require resolution of the inconsistencies (for example, by
outputting namespace declarations that correspond to the namespaces in scope).
Introducing the W3C XML Information Set
C-30 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XSLT Primer D-1
D
XSLT Primer
This appendix describes introductory information about the W3C XSL and XSLT
Recommendation. It contains the following sections:
I Introducing XSL
I XSL Transformation (XSLT)
I XML Path Language (Xpath)
I CSS Versus XSL
I XSL Stylesheet Example, PurchaseOrder.xsl
Introducing XSL
D-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Introducing XSL
XML documents have structure but no format. Extensible Stylesheet Language
(XSL) adds formatting to XML documents. It provides a way to display XML
semantics and can map XML elements into other formatting languages such as
HTML.
The W3C XSL Transformation Recommendation Version 1.0
This specication denes the syntax and semantics of XSLT, which is a language for
transforming XML documents into other XML documents.
XSLT is designed for use as part of XSL, which is a stylesheet language for XML. In
addition to XSLT, XSL includes an XML vocabulary for specifying formatting. XSL
species the styling of an XML document by using XSLT to describe how the
document is transformed into another XML document that uses the formatting
vocabulary.
XSLT is also designed to be used independently of XSL. However, XSLT is not
intended as a completely general-purpose XML transformation language. Rather it
is designed primarily for the kinds of transformations that are needed when XSLT is
used as part of XSL.
This specication denes the syntax and semantics of the XSLT language. A
transformation in the XSLT language is expressed as a well-formed XML document
See Also:
I Oracle9i XML Case Studies and Applications in particular, the
chapters that describe customizing content, Oracle9i Wireless
Edition, and customizing presentation with XML and XSL.
I http://www.oasis-open.org/cover/xsl.html
I http://www.mulberrytech.com/xsl/xsl-list/
I http://www.builder.com/Authoring/XmlSpot/?tag=st.cn.sr1.ssr.
bl_xml
I http://www.zvon.org/HTMLonly/XSLTutorial/Books/Book1/in
dex.html
I Chapter 6, "Transforming and Validating XMLType Data"
See Also: http://www.w3.org/TR/xslt
Introducing XSL
XSLT Primer D-3
conforming to the Namespaces in XML Recommendation, which may include both
elements that are dened by XSLT and elements that are not dened by XSLT.
XSLT-dened elements are distinguished by belonging to a specic XML namespace
(see [2.1 XSLT Namespace]), which is referred to in this specication as the XSLT
namespace. Thus this specication is a denition of the syntax and semantics of the
XSLT namespace.
A transformation expressed in XSLT describes rules for transforming a source tree
into a result tree. The transformation is achieved by associating patterns with
templates. A pattern is matched against elements in the source tree. A template
is instantiated to create part of the result tree. The result tree is separate from the
source tree. The structure of the result tree can be completely different from the
structure of the source tree. In constructing the result tree, elements from the
source tree can be ltered and reordered, and arbitrary structure can be added.
A transformation expressed in XSLT is called a stylesheet. This is because, in the
case when XSLT is transforming into the XSL formatting vocabulary, the
transformation functions as a stylesheet.
This document does not specify how an XSLT stylesheet is associated with an XML
document. It is recommended that XSL processors support the mechanism
described in. When this or any other mechanismyields a sequence of more than one
XSLT stylesheet to be applied simultaneously to a XML document, then the effect
should be the same as applying a single stylesheet that imports each member of the
sequence in order.
A stylesheet contains a set of template rules. A template rule has two parts: a
pattern which is matched against nodes in the source tree and a template which can
be instantiated to form part of the result tree. This allows a stylesheet to be
applicable to a wide class of documents that have similar source tree structures.
The W3C is developing the XSL specication as part of its Style Sheets Activity. XSL
has document manipulation capabilities beyond styling. It is a stylesheet language
for XML.
The July 1999 W3C XSL specication, was split into two separate documents:
I XSL syntax and semantics
I How to use XSL to apply style sheets to transform one document into another
The formatting objects used in XSL are based on prior work on Cascading Style
Sheets (CSS) and the Document Style Semantics & Specication Language (DSSSL).
XSL is designed to be easier to use than DSSSL.
Introducing XSL
D-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Capabilities provided by XSL as dened in the proposal enable the following
functionality:
I Formatting of source elements based on ancestry and descendency, position,
and uniqueness
I The creation of formatting constructs including generated text and graphics
I The denition of reusable formatting macros
I Writing-direction independent stylesheets
I An extensible set of formatting objects.
Namespaces in XML
A namespace is a unique identier or name. This is needed because XML
documents can be authored separately with different DTDs or XML Schemas.
Namespaces prevent conicts in markup tags by identifying which DTD or XML
Schema a tag comes from. Namespaces link an XML element to a specic DTD or
XML Schema.
Before you can use a namespace marker such as rml:, xhtml:, or xsl:, you must
identify it using the namespace indicator, xmlns as shown in the next paragraph.
XSL Stylesheet Architecture
The XSL stylesheets must include the following syntax:
I Start tag stating the stylesheet, such as <xsl:stylesheet2>
I Namespace indicator, such as
xmlns:xsl="http//www.w3.org/TR/WD-xsl" for an XSL namespace
indicator and xmlns:fo="http//www.w3.org/TR/WD-xsl/FO" for a
formatting object namespace indicator
I Template rules including font families and weight, colors, and breaks. The
templates have instructions that control the element and element values
I End of stylesheet declaration, </xsl:stylesheet2>
See Also: http://www.w3.org/Style/XSL/
See Also: http://w3.org/TR/REC-xml-names
CSS Versus XSL
XSLT Primer D-5
XSL Transformation (XSLT)
XSLT is designed to be used as part of XSL. In addition to XSLT, XSL includes an
XML vocabulary for specifying formatting. XSL species the styling of an XML
document by using XSLT to describe howthe document is transformed into another
XML document that uses the formatting vocabulary.
Meanwhile the second part is concerned with the XSL formatting objects, their
attributes, and how they can be combined.
XML Path Language (Xpath)
A separate, related specication is published as the XML Path Language (XPath)
Version 1.0. XPath is a language for addressing parts of an XML document, essential
for cases where you want to specify exactly which parts of a document are to be
transformed by XSL. For example, XPath lets you select all paragraphs belonging to
the chapter element, or select the elements called special notes. XPath is designed to
be used by both XSLT and XPointer. XPath is the result of an effort to provide a
common syntax and semantics for functionality shared between XSL
transformations and XPointer.
CSS Versus XSL
W3C is working to ensure that interoperable implementations of the formatting
model is available.
Cascading Stylesheets (CSS)
Cascading Stylesheets (CSS) can be used to style HTML documents. CSS were
developed by the W3C Style Working Group. CSS2 is a style sheet language that
allows authors and users to attach styles (for example, fonts, spacing, or aural cues)
to structured documents, such as HTML documents and XML applications.
By separating the presentation style of documents from the content of documents,
CSS2 simplies Web authoring and site maintenance.
See Also: Chapter 6, "Transforming and Validating XMLType
Data"
See Also: Appendix C, "XPath and Namespace Primer"
XSL Stylesheet Example, PurchaseOrder.xsl
D-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XSL
XSL, on the other hand, is able to transform documents. For example, XSL can be
used to transform XML data into HTML/CSS documents on the Web server. This
way, the two languages complement each other and can be used together. Both
languages can be used to style XML documents. CSS and XSL will use the same
underlying formatting model and designers will therefore have access to the same
formatting features in both languages.
The model used by XSL for rendering documents on the screen builds on years of
work on a complex ISO-standard style language called DSSSL. Aimed mainly at
complex documentation projects, XSL also has many uses in automatic generation
of tables of contents, indexes, reports, and other more complex publishing tasks.
XSL Stylesheet Example, PurchaseOrder.xsl
The following example, PurchaseOrder.xsl, is an example of an XSL stylesheet.
the example stylesheet is used in the examples in Chapter 3, "Using Oracle XML
DB".
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xdb="http://xmlns.oracle.com/xdb"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:template match="/">
<html>
<head/>
<body bgcolor="#003333" text="#FFFFCC" link="#FFCC00"
vlink="#66CC99" alink="#669999">
<FONT FACE="Arial, Helvetica, sans-serif">
<xsl:for-each select="PurchaseOrder"/>
<xsl:for-each select="PurchaseOrder">
<center>
<span style="font-family:Arial; font-weight:bold">
<FONT COLOR="#FF0000">
<B>Purchase Order </B>
</FONT>
</span>
</center>
<br/>
<center>
<xsl:for-each select="Reference">
<span style="font-family:Arial; font-weight:bold">
<xsl:apply-templates/>
XSL Stylesheet Example, PurchaseOrder.xsl
XSLT Primer D-7
</span>
</xsl:for-each>
</center>
</xsl:for-each>
<P>
<xsl:for-each select="PurchaseOrder">
<br/>
</xsl:for-each>
<P/>
<P>
<xsl:for-each select="PurchaseOrder">
<br/>
</xsl:for-each>
</P>
</P>
<xsl:for-each select="PurchaseOrder"/>
<xsl:for-each select="PurchaseOrder">
<table border="0" width="100%" BGCOLOR="#000000">
<tbody>
<tr>
<td WIDTH="296">
<P>
<B>
<FONT SIZE="+1" COLOR="#FF0000"
FACE="Arial, Helvetica, sans-serif">Internal
</FONT>
</B>
</P>
<table border="0" width="98%" BGCOLOR="#000099">
<tbody>
<tr>
<td WIDTH="49%">
<B>
<FONT COLOR="#FFFF00">Actions</FONT>
</B>
</td>
<td WIDTH="51%">
<xsl:for-each select="Actions">
<xsl:for-each select="Action">
<table border="1" WIDTH="143">
<xsl:if test="position()=1">
<thead>
<tr>
<td HEIGHT="21">
<FONT
XSL Stylesheet Example, PurchaseOrder.xsl
D-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
COLOR="#FFFF00">User</FONT>
</td>
<td HEIGHT="21">
<FONT
COLOR="#FFFF00">Date</FONT>
</td>
</tr>
</thead>
</xsl:if>
<tbody>
<tr>
<td>
<xsl:for-each select="User">
<xsl:apply-templates/>
</xsl:for-each>
</td>
<td>
<xsl:for-each select="Date">
<xsl:apply-templates/>
</xsl:for-each>
</td>
</tr>
</tbody>
</table>
</xsl:for-each>
</xsl:for-each>
</td>
</tr>
<tr>
<td WIDTH="49%">
<B>
<FONT COLOR="#FFFF00">Requestor</FONT>
</B>
</td>
<td WIDTH="51%">
<xsl:for-each select="Requestor">
<xsl:apply-templates/>
</xsl:for-each>
</td>
</tr>
<tr>
<td WIDTH="49%">
<B>
<FONT COLOR="#FFFF00">User</FONT>
</B>
XSL Stylesheet Example, PurchaseOrder.xsl
XSLT Primer D-9
</td>
<td WIDTH="51%">
<xsl:for-each select="User">
<xsl:apply-templates/>
</xsl:for-each>
</td>
</tr>
<tr>
<td WIDTH="49%">
<B>
<FONT COLOR="#FFFF00">Cost Center</FONT>
</B>
</td>
<td WIDTH="51%">
<xsl:for-each select="CostCenter">
<xsl:apply-templates/>
</xsl:for-each>
</td>
</tr>
</tbody>
</table>
</td>
<td width="93"/>
<td valign="top" WIDTH="340">
<B>
<FONT COLOR="#FF0000">
<FONT SIZE="+1">Ship To</FONT>
</FONT>
</B>
<xsl:for-each select="ShippingInstructions">
<xsl:if test="position()=1"/>
</xsl:for-each>
<xsl:for-each select="ShippingInstructions">
<xsl:if test="position()=1">
<table border="0" BGCOLOR="#999900">
<tbody>
<tr>
<td WIDTH="126" HEIGHT="24">
<B>Name</B>
</td>
<xsl:for-each
select="../ShippingInstructions">
<td WIDTH="218" HEIGHT="24">
<xsl:for-each select="name">
<xsl:apply-templates/>
XSL Stylesheet Example, PurchaseOrder.xsl
D-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
</xsl:for-each>
</td>
</xsl:for-each>
</tr>
<tr>
<td WIDTH="126" HEIGHT="34">
<B>Address</B>
</td>
<xsl:for-each
select="../ShippingInstructions">
<td WIDTH="218" HEIGHT="34">
<xsl:for-each select="address">
<span style="white-space:pre">
<xsl:apply-templates/>
</span>
</xsl:for-each>
</td>
</xsl:for-each>
</tr>
<tr>
<td WIDTH="126" HEIGHT="32">
<B>Telephone</B>
</td>
<xsl:for-each
select="../ShippingInstructions">
<td WIDTH="218" HEIGHT="32">
<xsl:for-each select="telephone">
<xsl:apply-templates/>
</xsl:for-each>
</td>
</xsl:for-each>
</tr>
</tbody>
</table>
</xsl:if>
</xsl:for-each>
</td>
</tr>
</tbody>
</table>
<br/>
<B>
<FONT COLOR="#FF0000" SIZE="+1">Items:</FONT>
</B>
<br/>
XSL Stylesheet Example, PurchaseOrder.xsl
XSLT Primer D-11
<br/>
<table border="0">
<xsl:for-each select="LineItems">
<xsl:for-each select="LineItem">
<xsl:if test="position()=1">
<thead>
<tr bgcolor="#C0C0C0">
<td>
<FONT COLOR="#FF0000">
<B>ItemNumber</B>
</FONT>
</td>
<td>
<FONT COLOR="#FF0000">
<B>Description</B>
</FONT>
</td>
<td>
<FONT COLOR="#FF0000">
<B>PartId</B>
</FONT>
</td>
<td>
<FONT COLOR="#FF0000">
<B>Quantity</B>
</FONT>
</td>
<td>
<FONT COLOR="#FF0000">
<B>Unit Price</B>
</FONT>
</td>
<td>
<FONT COLOR="#FF0000">
<B>Total Price</B>
</FONT>
</td>
</tr>
</thead>
</xsl:if>
<tbody>
<tr bgcolor="#DADADA">
<td>
<FONT COLOR="#000000">
<xsl:for-each select="@ItemNumber">
XSL Stylesheet Example, PurchaseOrder.xsl
D-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<xsl:value-of select="."/>
</xsl:for-each>
</FONT>
</td>
<td>
<FONT COLOR="#000000">
<xsl:for-each select="Description">
<xsl:apply-templates/>
</xsl:for-each>
</FONT>
</td>
<td>
<FONT COLOR="#000000">
<xsl:for-each select="Part">
<xsl:for-each select="@Id">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:for-each>
</FONT>
</td>
<td>
<FONT COLOR="#000000">
<xsl:for-each select="Part">
<xsl:for-each select="@Quantity">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:for-each>
</FONT>
</td>
<td>
<FONT COLOR="#000000">
<xsl:for-each select="Part">
<xsl:for-each select="@UnitPrice">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:for-each>
</FONT>
</td>
<td>
<FONT FACE="Arial, Helvetica, sans-serif"
COLOR="#000000">
<xsl:for-each select="Part">
<xsl:value-of select="@Quantity*@UnitPrice"/>
</xsl:for-each>
</FONT>
XSL Stylesheet Example, PurchaseOrder.xsl
XSLT Primer D-13
</td>
</tr>
</tbody>
</xsl:for-each>
</xsl:for-each>
</table>
</xsl:for-each>
</FONT>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XSL Stylesheet Example, PurchaseOrder.xsl
D-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Java DOM API for XMLType, Resource API for Java: Quick Reference E-1
E
Java DOM API for XMLType, Resource API
for Java: Quick Reference
This appendix contains a quick reference for the following Oracle XML DB Java
APIs:
I Java DOM API For XMLType
I Oracle XML DB Resource API for Java
Java DOM API For XMLType
E-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Java DOM API For XMLType
Packages oracle.xdb and oracle.xdb.dom implements the Java DOMAPI for
XMLType. Java DOM API for XMLType implements the W3C DOM
Recommendation Level 1.0 and Level 2.0 Core and also provides Oracle-specic
extensions.
Table E1 lists the Java DOM API for XMLType (oracle.xdb.dom and
oracle.xdb) classes. Note that class XMLType is in package oracle.xdb and not
oracle.xdb.dom.
Non-Supported Java Methods
The following are methods documented in Release 2 (9.2.0.1) but not currently
supported in Release 2 (9.2.0.2):
I XDBDocument.getElementByID
I XDBDocument.importNode
I XDBNode.normalize
I XDBNode.isSupported
I XDBDomImplementation.hasFeature
See Also:
I Oracle9i XML API Reference - XDK and Oracle XML DB
I Chapter 9, "Java API for XMLType"
Table E1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes
Java DOM API for XMLType Description
XDBAttribute Implements the W3C DOM Node interface for interacting with XOBs.
XDBCData Implements org.w3c.dom.CData, the W3C text interface.
XDBCharData Implements org.w3c.dom.CharData, the W3C CharacterData interface.
XDBComment Implements the org.w3c.dom.Comment interface.
Java DOM API For XMLType
Java DOM API for XMLType, Resource API for Java: Quick Reference E-3
XDBDocument Implements the org.w3c.dom.Document interface.
Methods:
XDBDocument() constructor:
XDBDocument();Creates new Document. Can be used in server only.
XDBDocument( byte[ ] source);Populates Document from source. Can be
used in server only.
XDBDocument( Connection conn);Opens connection for caching Document
source.
XDBDocument( Connection conn, byte[] source); Connection for caching
bytes for Document source.
XDBDocument( Connection conn, String source);Opens connection for
caching string containing XML text.
XDBDocument(String source);The string containing XML text. Can be used
in server only.
Parameters: source - Contains XML text., conn -Connection to be used.
XDBDomImplementation Implements org.w3c.dom.DomImplementation.
Methods:
XDBDomImplementation()- Opens a JDBC connection to the server.
XDBElement Implements org.w3c.dom.Element.
XDBEntity Implements org.w3c.dom.Entity.
XDBNodeMap Implements org.w3c.dom.NamedNodeMap.
XDBNode Implements org.w3c.dom.Node, the W3C DOM Node interface for
interacting with XOBs.
Methods:
write() -Writes XML for this Node and all subnodes to an OutputStream. If
the OutputStream is ServletOutputStream, the servlet output is committed
and data is written using native streaming.
public void write( OutputStream s, String charEncoding, short indent);
Parameters:
s - stream to write the output toContains XML text
charEncoding - IANA char code (for example, "ISO-8859")
indent - number of characters to indent nested elements
Table E1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes (Cont.)
Java DOM API for XMLType Description
Java DOM API For XMLType
E-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XDBNodeList Implements org.w3c.dom.NodeList.
XDBNotation Implements org.w3c.dom.Notation.
XDBProcInst Implements org.w3c.dom.ProcInst, the W3C DOM
ProcessingInstruction interface.
XDBText Implements org.w3c.dom.Text.
XMLType
(package oracle.xdb)
Implements Java methods for the SQL type SYS.XMLTYPE.
Methods:
createXML() - Creates an XMLType. Use this method when accessing data
through JDBC.
getStringVal() - Retrieves string value containing the XML data from
the XMLType
getClobVal() - Retrieves the CLOB value containing the XML data from
the XMLType
extract() - Extracts the given set of nodes from the XMLType
existsNode() - Checks for the existence of the given set of nodes in the
XMLType
transform() - Transforms the XMLType using the given XSL document
isFragment() - Checks if the XMLType is a regular document or a
document fragment
getDOM() - Retrieves the DOM document associated with the XMLType.
createXML() Creates an XMLType. Throws java.sql.SQLException if the XMLType
could not be created:
public static XMLType createXML( OPAQUE opq); Creates and returns an
XMLType given the opaque type containing the XMLType bytes.
public static XMLType createXML(Connection conn, String xmlval);
Creates and returns an XMLType given the string containing the XML data.
public static XMLType createXML( Connection conn, CLOB xmlval);
Creates and returns an XMLType given a CLOB containing the XML data.
public static XMLType createXML(Connection conn, Document domdoc);
Creates and returns an XMLType given an instance of the DOM document.
Parameters:
opq - opaque object from which the XMLType is to be constructed
conn - connection object to be used, xmlval - contains the XML data
domdoc - the DOM Document which represents the DOM tree,
Table E1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes (Cont.)
Java DOM API for XMLType Description
Java DOM API For XMLType
Java DOM API for XMLType, Resource API for Java: Quick Reference E-5
getStringVal() Retrieves the string value containing the XML data from the XMLType.
Throws java.sql.SQLException.
public String getStringVal();
getClobVal() Retrieves the CLOB value containing the XML data from the XMLType.
Throws java.sql.SQLException
public CLOB getClobVal();
extract() Extracts and returns the given set of nodes from the XMLType. The set of
nodes is specied by the XPath expression. The original XMLType remains
unchanged. Works only in the thick case. If no nodes match the specied
expression, returns NULL. Throws java.sql.SQLException
public XMLType extract( String xpath, String nsmap);
Parameters:
xpath - xpath expression which species for which nodes to search
nsmap - map of namespaces which resolves the prexes in the xpath
expression; format is "xmlns=a.com xmlns:b=b.com"
existsNode() Checks for existence of given set of nodes in the XMLType. This set of nodes
is specied by the xpath expression. Returns TRUE if specied nodes exist in
the XMLType; otherwise, returns FALSE. Throws
java.sql.SQLException
public boolean existsNode( String xpath, String nsmap);
Parameters:
xpath - xpath expression that species for which nodes to search
nsmap - map of namespaces that resolves prexes in the xpath
expression;format is "xmlns=a.com xmlns:b=b.com",
Table E1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes (Cont.)
Java DOM API for XMLType Description
Oracle XML DB Resource API for Java
E-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Oracle XML DB Resource API for Java
Oracle XML DB Resource API for Javas WebDav support is implemented using
package oracle.xdb.spi classes that render the service provider interface (SPI)
drivers. Classes in oracle.xdb.spi implement core WebDAV support for Oracle XML
DB. Table E2 lists the oracle.xdb.spi classes.
transform() Transforms and returns the XMLType using the given XSL document. The
new (transformed) XML document is returned. Throws
java.sql.SQLException.
public XMLType transform( XMLType xsldoc, String parammap);
Parameters:
xsldoc - The XSL document to be applied to the XMLType
parammap - top level parameters to be passed to the XSL transformation. Use
format "a=b c=d e=f". Can be NULL.
isFragment() Checks if the XMLType is a regular document or document fragment.
Returns TRUE if doc is a fragment; otherwise, returns FALSE. Throws
java.sql.SQLException.
public boolean isFragment();
getDOM() Retrieves the DOM document associated with the XMLType. This document
is the org.w3c.dom.Document. The caller can perform all DOM operations
on the Document. If the document is binary, getDOM returns NULL. Throws
java.sql.SQLException.
public org.w3c.dom.Document getDOM();
See Also: Chapter 17, "Oracle XML DB Resource API for Java"
Table E1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes (Cont.)
Java DOM API for XMLType Description
Oracle XML DB Resource API for Java
Java DOM API for XMLType, Resource API for Java: Quick Reference E-7
Table E2 Oracle XML DB Resource API for Java (oracle.xdb.spi)
oracle.xdb.spi Class Description
XDBContext Class Implements the Java naming and context interface for Oracle
XML DB, which extends javax.naming.context. In this
release there is no federation support, in other words, it is
completely unaware of the existence of other namespaces.
Methods:
XDBContext() - Class XDBContext constructor.
I public XDBContext( Hashtable env); Creates an instance
of XDBContext class given the environment.
I public XDBContext( Hashtable env, String path); Creates
an instance of XDBContext class given the environment
and path.
Parameters: env - Environment to describe properties of
context, path - Initial path for the context.
XDBContextFactory Class Implements javax.naming.context.
Methods:
XDBContextFactory() - Constructor for class
XDBContextFactory. public XDBContextFactory();
XDBNameParser Class Implements javax.naming.NameParser
XDBNamingEnumeration Class Implements javax.naming.NamingEnumeration
Oracle XML DB Resource API for Java
E-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XDBResource Class Implements the core features for Oracle XML DB JNDI service
provider interface (SPI). This release has no federation support,
and is unaware of the existence of other namespaces.
public class XDBResource extends java.lang.Object.
Methods:
XDBResource()- Creates a new instance of XDBResource
getAuthor() - Returns author of the resource
getComment() - Returns the DAV comment of the resource
getContent() - Returns the content of the resource
getContentType() - Returns the content type of the resource
getCreateDate() - Returns the create date of the resource
getDisplayName() - Returns the display name of the resource
getLanguage() - Returns the language of the resource
getLastModDate() - Returns the last modication date of the
resource
getOwnerId() - Returns the owner ID of the resource
setACL() - Sets the ACL on the resource
setAuthor() - Sets the author of the resource
setComment() - Sets the DAV comment of the resource
setContent() - Sets the content of the resource
setContentType() - Sets the content type of the resource
setCreateDate() - Sets the creation date of the resource
setDisplayName() - Sets the display name of the resource
setLanguage() - Sets the language of the resource
setLastModDate() - Sets the last modication date of the
resource
setOwnerId() -Sets the owner ID of the resource
XDBResource() Creates a new instance of XDBResource. public Creates a new
instance of XDBResource given the environment.
public XDBResource( Hashtable env, String path); Creates a
new instance of XDBResource given the environment and path.
Parameters: env - Environment passed in, path - Path to the
resource
Table E2 Oracle XML DB Resource API for Java (oracle.xdb.spi) (Cont.)
oracle.xdb.spi Class Description
Oracle XML DB Resource API for Java
Java DOM API for XMLType, Resource API for Java: Quick Reference E-9
getAuthor() Retrieves the author of the resource.
public String getAuthor();
getComment() Retrieves the DAV (Web Distributed Authoring and
Versioning) comment of the resource.
public String getComment();
getContent() Returns the content of the resource.
public Object getContent();
getContentType() Returns the content type of the resource. public String
getContentType();
getCreateDate() Returns the creation date of the resource. public Date
getCreateDate();
getDisplayName() Returns the display name of the resource. public String
getDisplayName();
getLanguage() Returns the Language of the resource. public String
getLanguage();
getLastModDate() Returns the last modication date of the resource.
public Date getLastModDate();
getOwnerId() Returns the owner id of the resource. The value expected by
this method is the user id value for the database user as
provided by the catalog views such as ALL_USERS, and so on.
public long getOwnerId();
setACL() Sets the ACL on the resource.
public void setACL( String aclpath);
Parametes: aclpath - The path to the ACL resource.
setAuthor() Sets the author of the resource. public void setAuthor( String
authname); Parameter: authname - Author of the resource.
setComment() Sets the DAV (Web Distributed Authoring and Versioning)
comment of the resource.
public void setComment(String davcom); Parameter: davcom-
DAV comment of the resource.
setContent() Sets the content of the resource.
public void setContent( Object xmlobj); Parameter: xmlobj -
Content of the resource.
Table E2 Oracle XML DB Resource API for Java (oracle.xdb.spi) (Cont.)
oracle.xdb.spi Class Description
Oracle XML DB Resource API for Java
E-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
setContentType() Sets the content type of the resource.
public void setContentType( String conttype);
Parameter: conttype - Content type of the resource.
setCreateDate() Sets the creation date of the resource.
public void setCreateDate( Date credate);
Parameter: credate - Creation date of the resource.
setDisplayName() Sets the display name of the resource.
public void setDisplayName( String dname);
Parameter: dname - Display name of the resource.
setLanguage() Sets the language of the resource.
public void setLanguage(String lang);
Parameter: lang - Language of the resource.
setLastModDate() Sets the last modication date of the resource.
public void - setLastModDate( Date d);
Parameter: d - Last modication date of the resource.
setOwnerId() Sets the owner id of the resource. The owner id value expected
by this method is the user id value for the database user as
provided by the catalog views such as ALL_USERS, and so on.
public void setOwnerId( long ownerid);
Parameters: ownerid - Owner id of the resource.
Table E2 Oracle XML DB Resource API for Java (oracle.xdb.spi) (Cont.)
oracle.xdb.spi Class Description
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-1
F
Oracle XML DB XMLType API, PL/SQL and
Resource PL/SQL APIs: Quick Reference
This appendix provides a summary of the following Oracle XML DB SQL and
PL/SQL APIs:
I XMLType API
I PL/SQL DOM API for XMLType (DBMS_XMLDOM)
I PL/SQL Parser for XMLType (DBMS_XMLPARSER)
I PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
I DBMS_XMLSCHEMA
I Oracle XML DB XML Schema Catalog Views
I Resource API for PL/SQL (DBMS_XDB)
I RESOURCE_VIEW, PATH_VIEW
I DBMS_XDB_VERSION
I DBMS_XDBT
XMLType API
F-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
XMLType API
XMLType is a system-dened opaque type for handling XML data. XMLType has
predened member functions to extract XML nodes and fragments. You can create
columns of XMLType and insert XML documents into them. You can also generate
XML documents as XMLType instances dynamically using SQL functions,
SYS_XMLGEN and SYS_XMLAGG, the PL/SQL package DBMS_XMLGEN, and the
SQLX functions.
Table F1 lists the XMLType API functions.
See Also:
I Oracle9i XML API Reference - XDK and Oracle XML DB
I Chapter 4, "Using XMLType"
XMLType API
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-3
Table F1 XMLType API
Function Description
XMLType()
constructor function XMLType(xmlData IN clob,
schema IN varchar2 := NULL, validated IN
number := 0, wellformed IN Number := 0) return
self as result
constructor function XMLType(xmlData IN
varchar2, schema IN varchar2 := NULL,validated
IN number := 0, wellformed IN number := 0)
return self as result
constructor function XMLType (xmlData IN
"<ADT_1>", schema IN varchar2 := NULL,
element IN varchar2 := NULL, validated IN
number := 0) return self as result
onstructor function XMLType(xmlData IN
SYS_REFCURSOR, schema in varchar2 := NULL,
element in varchar2 := NULL, validated in number
:= 0) return self as result
Constructor that constructs an instance of the XMLType datatype.
The constructor can take in the XML as a CLOB, VARCHAR2 or
take in a object type.
Parameters:
xmlData - data in the form of a CLOB, REF cursor, VARCHAR2 or
object type.
schema - optional schema URL used to make the input conform to
the given schema.
validated - ag to indicate that the instance is valid according to the
given XMLSchema. (default 0)
wellformed - ag to indicate that the input is wellformed. If set,
then the database would not do well formed check on the input
instance. (default 0)
element - optional element name in the case of the ADT_1 or REF
CURSOR constructors. (default null)
-- --
createXML()
STATIC FUNCTION createXML( xmlval IN
varchar2) RETURN XMLType deterministic
STATIC FUNCTION createXML( xmlval IN clob)
RETURN XMLType
STATIC FUNCTIONcreateXML (xmlData INclob,
schema IN varchar2, validated IN number := 0,
wellformed IN number := 0 ) RETURN XMLType
deterministic
STATIC FUNCTION createXML ( xmlData IN
varchar2, schema IN varchar2, validated IN
number := 0, wellformed IN number := 0)
RETURN XMLType deterministic
STATIC FUNCTION createXML (xmlData IN
"<ADT_1>", schema IN varchar2 := NULL,
element IN varchar2 := NULL, validated IN
NUMBER := 0) RETURN XMLType deterministic
STATIC FUNCTION createXML ( xmlData IN
SYS_REFCURSOR, schema in varchar2 := NULL,
element in varchar2 := NULL, validated in number
:= 0) RETURN XMLType deterministic
Static function for creating and returning an XMLType instance. The
string and clob parameters used to pass in the date must contain
well-formed and valid XML documents. The options are described
in the following table.
Parameters:
xmlData - Actual data in the form of a CLOB, REF cursor,
VARCHAR2 or object type.
schema - optional Schema URL to be used to make the input
conform to the given schema.
validated - ag to indicate that the instance is valid according to the
given XMLSchema. (default 0)
wellformed - ag to indicate that the input is wellformed. If set,
then the database would not do well formed check on the input
instance. (default 0)
element - optional element name in the case of the ADT_1 or REF
CURSOR constructors. (default null)
XMLType API
F-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
existsNode()
MEMBER FUNCTION existsNode(xpath IN
varchar2) RETURN number deterministic
MEMBER FUNCTION existsNode( xpath in
varchar2, nsmap in varchar2) RETURN number
deterministic
Takes an XMLType instance and a XPath and returns 1 or 0
indicating if applying the XPath returns a non-empty set of nodes.
If the XPath string is NULL or the document is empty, then a value
of 0 is returned, otherwise returns 1.
Parameters:
xpath - XPath expression to test.
nsmap - optional namespace mapping.
extract()
MEMBER FUNCTIONextract( xpath INvarchar2)
RETURN XMLType deterministic
MEMBER FUNCTION extract(xpath IN varchar2,
nsmap IN varchar2) RETURN XMLType
deterministic
Extracts an XMLType fragment and returns an XMLType instance
containing the result node(s). If the XPath does not result in any
nodes, it returns NULL.
Parameters:
xpath - XPath expression to apply.
nsmap - optional prex to namespace mapping information.
isFragment()
MEMBER FUNCTION isFragment() RETURN
number deterministic
Determines if the XMLType instance corresponds to a well-formed
document, or a fragment. Returns 1 or 0 indicating if the XMLType
instance contains a fragment or a well-formed document. Returns 1
or 0 indicating if the XMLType instance contains a fragment or a
well-formed document..
getClobVal()
MEMBER FUNCTIONgetClobVal() RETURNclob
deterministic
Returns a CLOB containing the serialized XML representation; if
the return is a temporary CLOB, it must be freed after use.
getNumberVal()
MEMBER FUNCTION getNumberVal() RETURN
number deterministic
Returns a numeric value, formatted from the text value pointed to
by the XMLType instance. The XMLType must point to a valid text
node that contains a numerical value.
getStringVal()
MEMBER FUNCTION getStringVal() RETURN
varchar2 deterministic
Returns the document as a string containing the serialized XML
representation, or for text nodes, the text itself. If the XML
document is bigger than the maximum size of the VARCHAR2,
4000, then an error is raised at run time.
transform()
MEMBER FUNCTION transform(xsl IN
XMLType, parammap in varchar2 := NULL)
RETURN XMLType deterministic
Transforms XML data using the XSL stylesheet argument and the
top-level parameters passed as a string of name=value pairs. If any
argument other than the parammap is NULL, a NULL is returned.
Parameter
xsl - XSL stylesheet describing the transformation
parammap - top level parameters to the XSL - string of name=value
pairs
Table F1 XMLType API (Cont.)
Function Description
XMLType API
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-5
toObject()
MEMBER PROCEDURE toObject(SELF in
XMLType, object OUT "<ADT_1>", schema in
varchar2 := NULL, element in varchar2 := NULL)
Converts XML data into an instance of a user dened type, using
the optional schema and top-level element arguments.
Parameters:
SELF - instance to be converted. Implicit if used as a member
procedure.
object - converted object instance of the required type may be
passed in to this function.
schema - schema URL. Mapping of the XMLType instance to the
converted object instance can be specied using a schema.
element - top-level element name. This species the top-level
element name in the XMLSchema document to map the XMLType
instance.
isSchemaBased()
MEMBER FUNCTION isSchemaBased return
number deterministic
Determines if the XMLType instance is schema-based. Returns 1 or
0 depending on whether the XMLType instance is schema-based or
not.
getSchemaURL()
MEMBER FUNCTION getSchemaURL return
varchar2 deterministic
Returns the XML schema URL corresponding to the XMLType
instance, if the XMLType instance is a schema-based document.
Otherwise returns NULL.
getRootElement()
MEMBER FUNCTION getRootElement return
varchar2 deterministic
Gets the root element of the XMLType instance. Returns NULL if
the instance is a fragment.
createSchemaBasedXML()
MEMBER FUNCTION
createSchemaBasedXML(schema IN varchar2 :=
NULL) return sys.XMLType deterministic
Creates a schema-based XMLType instance from a
non-schema-based XML and a schemaURL.
Parameter:
schema - schema URL If NULL, then the XMLType instance must
contain a schema URL.
createNonSchemaBasedXML()
MEMBER FUNCTION
createNonSchemaBasedXML return XMLType
deterministic
Creates a non-schema-based XML document from an XML
schema-based instance.
getNamespace()
MEMBER FUNCTION getNamespace return
varchar2 deterministic
Returns the namespace of the top level element in the instance.
NULL if the input is a fragment or is a non-schema-based instance.
schemaValidate()
MEMBER PROCEDURE schemaValidate
Validates the XML instance against its schema if it has not already
validated. For non-schema based documents an error is raised. If
validation fails an error is raised; else, the documents status is
changed to validated.
Table F1 XMLType API (Cont.)
Function Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
F-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Table F2 lists the PL/SQL DOM API for XMLType (DBMS_XMLDOM) methods
supported in Release 2 (9.2.0.1). These are grouped according to the W3C DOM
Recommendation. The following DBMS_XMLDOM methods are not supported in
Release 2 (9.2.0.2):
I hasFeature
I getVersion
I setVersion
I getCharset
I setCharset
I getStandalone
I setStandalone
I writeExternalDTDToFile
I writeExternalDTDToBuffer
isSchemaValidated()
MEMBER FUNCTION isSchemaValidated return
NUMBER deterministic
Returns the validation status of the XMLType instance if it has been
validated against its schema. Returns 1 if validated against the
schema, 0 otherwise.
setSchemaValidated()
MEMBER PROCEDURE setSchemaValidated(ag
IN BINARY_INTEGER := 1)
Sets the VALIDATION state of the input XML instance to avoid
schema validation.
Parameter: ag - 0 = NOT VALIDATED; 1 = VALIDATED; Default
value is 1.
isSchemaValid()
member function isSchemaValid(schurl IN
VARCHAR2 := NULL, elem IN VARCHAR2 :=
NULL) return NUMBER deterministic
Checks if the input instance conforms to a specied schema. Does
not change validation status of the XML instance. If an XML
schema URL is not specied and the XML document is
schema-based, conformance is checked against the XMLType
instances own schema.
Parameter:
schurl - URL of the XML Schema against which to check
conformance.
elem - Element of a specied schema, against which to validate.
Useful when you have an XML Schema that denes more than one
top level element, and you need to check conformance against a
specic elements.
Table F1 XMLType API (Cont.)
Function Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-7
I writeExternalDTDToClob
Table F3 . lists additional methods supported in Release 2 (9.2.0.2).
See Also: Chapter 8, "PL/SQL API for XMLType"
Table F2 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods
Group/Method Description
Node methods --
isNull() Tests if the node is NULL.
makeAttr() Casts the node to an Attribute.
makeCDataSection() Casts the node to a CDataSection.
makeCharacterData() Casts the node to CharacterData.
makeComment() Casts the node to a Comment.
makeDocumentFragment() Casts the node to a DocumentFragment.
makeDocumentType() Casts the node to a Document Type.
makeElement() Casts the node to an Element.
makeEntity() Casts the node to an Entity.
makeEntityReference() Casts the node to an EntityReference.
makeNotation() Casts the node to a Notation.
makeProcessingInstruction() Casts the node to a DOMProcessingInstruction.
makeText() Casts the node to a DOMText.
makeDocument() Casts the node to a DOMDocument.
writeToFile() Writes the contents of the node to a le.
writeToBuffer() Writes the contents of the node to a buffer.
writeToClob() Writes the contents of the node to a clob.
getNodeName() Retrieves the Name of the Node.
getNodeValue() Retrieves the Value of the Node.
setNodeValue() Sets the Value of the Node.
getNodeType() Retrieves the Type of the node.
getParentNode() Retrieves the parent of the node.
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
F-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
getChildNodes() Retrieves the children of the node.
getFirstChild() Retrieves the rst child of the node.
getLastChild() Retrieves the last child of the node.
getPreviousSibling() Retrieves the previous sibling of the node.
getNextSibling() Retrieves the next sibling of the node.
getAttributes() Retrieves the attributes of the node.
getOwnerDocument() Retrieves the owner document of the node.
insertBefore() Inserts a child before the reference child.
replaceChild() Replaces the old child with a new child.
removeChild() Removes a specied child from a node.
appendChild() Appends a new child to the node.
hasChildNodes() Tests if the node has child nodes.
cloneNode() Clones the node.
Named node map methods --
isNull() Tests if the NodeMap is NULL.
getNamedItem() Retrieves the item specied by the name.
setNamedItem() Sets the item in the map specied by the name.
removeNamedItem() Removes the item specied by name.
item() Retrieves the item given the index in the map.
getLength() Retrieves the number of items in the map.
Node list methods --
isNull() Tests if the Nodelist is NULL.
item() Retrieves the item given the index in the nodelist.
getLength() Retrieves the number of items in the list.
Attr methods --
isNull() Tests if the Attribute Node is NULL.
makeNode() Casts the Attribute to a node.
Table F2 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-9
getQualiedName() Retrieves the Qualied Name of the attribute.
getNamespace() Retrieves the NS URI of the attribute.
getLocalName() Retrieves the local name of the attribute.
getExpandedName() Retrieves the expanded name of the attribute.
getName() Retrieves the name of the attribute.
getSpeciied() Tests if attribute was specied in the owning
element.
getValue() Retrieves the value of the attribute.
setValue() Sets the value of the attribute.
C data section methods --
isNull()isNull() Tests if the CDataSection is NULL.
makeNode()makeNode() Casts the CDatasection to a node.
Character data methods --
isNull() Tests if the CharacterData is NULL.
makeNode() Casts the CharacterData to a node.
getData() Retrieves the data of the node.
setData() Sets the data to the node.
getLength() Retrieves the length of the data.
substringData() Retrieves the substring of the data.
appendData() Appends the given data to the node data.
insertData() Inserts the data in the node at the given offSets.
deleteData() Deletes the data from the given offSets.
replaceData() Replaces the data from the given offSets.
Comment methods --
isNull() Tests if the comment is NULL.
makeNode() Casts the Comment to a node.
DOM implementation methods --
Table F2 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
F-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
isNull() Tests if the DOMImplementation node is NULL.
hasFeature() Tests if the DOM implements a given feature. [Not
supported in this release]
Document fragment methods --
isNull() Tests if the DocumentFragment is NULL.
makeNode() Casts the Document Fragment to a node.
Document type methods --
isNull() Tests if the Document Type is NULL.
makeNode() Casts the document type to a node.
ndEntity() Finds the specied entity in the document type.
ndNotation() Finds the specied notation in the document type.
getPublicId() Retrieves the public ID of the document type.
getSystemId() Retrieves the system ID of the document type.
writeExternalDTDToFile() Writes the document type denition to a le.
writeExternalDTDToBuffer() Writes the document type denition to a buffer.
writeExternalDTDToClob() Writes the document type denition to a clob.
getName() Retrieves the name of the Document type.
getEntities() Retrieves the nodemap of entities in the Document
type.
getNotations() Retrieves the nodemap of the notations in the
Document type.
Element methods --
isNull() Tests if the Element is NULL.
makeNode() Casts the Element to a node.
getQualiedName() Retrieves the qualied name of the element.
getNamespace() Retrieves the NS URI of the element.
getLocalName() Retrieves the local name of the element.
getExpandedName() Retrieves the expanded name of the element.
Table F2 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-11
getChildrenByTagName() Retrieves the children of the element by tag name.
getElementsByTagName() Retrieves the elements in the subtree by element.
resolveNamespacePrex() Resolve the prex to a namespace uri.
getTagName() Retrieves the Tag name of the element.
getAttribute() Retrieves the attribute node specied by the name.
setAttribute() Sets the attribute specied by the name.
removeAttribute() Removes the attribute specied by the name.
getAttributeNode() Retrieves the attribute node specied by the name.
setAttributeNode() Sets the attribute node in the element.
removeAttributeNode() Removes the attribute node in the element.
normalize() Normalizes the text children of the element. [Not
supported in this release]
Entity methods --
isNull() Tests if the Entity is NULL.
makeNode() Casts the Entity to a node.
getPublicId() Retrieves the public Id of the entity.
getSystemId() Retrieves the system Id of the entity.
getNotationName() Retrieves the notation name of the entity.
Entity reference methods --
isNull() Tests if the entity reference is NULL.
makeNode() Casts the Entity reference to NULL.
Notation methods --
isNull() Tests if the notation is NULL.
makeNode() Casts the notation to a node.
getPublicId() Retrieves the public Id of the notation.
getSystemId() Retrieves the system Id of the notation.
Processing instruction methods --
Table F2 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
F-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
isNull() Tests if the processing instruction is NULL.
makeNode() Casts the Processing instruction to a node.
getData() Retrieves the data of the processing instruction.
getTarget() Retrieves the target of the processing instruction.
setData() Sets the data of the processing instruction.
Text methods --
isNull() Tests if the text is NULL.
makeNode() Casts the text to a node.
splitText() Splits the contents of the text node into 2 text nodes.
Document methods --
isNull() Tests if the document is NULL.
makeNode() Casts the document to a node.
newDOMDocument() Creates a new document.
freeDocument() Frees the document.
getVersion() Retrieves the version of the document. [Not
supported in this release]
setVersion() Sets the version of the document. [Not supported in
this release]
getCharset() Retrieves the Character set of the document. [Not
supported in this release]
setCharset() Sets the Character set of the document. [Not
supported in this release]
getStandalone() Retrieves if the document is specied as standalone.
[Not supported in this release]
setStandalone() Sets the document standalone. [Not supported in
this release]
writeToFile() Writes the document to a le.
writeToBuffer() Writes the document to a buffer.
writeToClob() Writes the document to a clob.
Table F2 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-13
writeExternalDTDToFile() Writes the DTD of the document to a le. [Not
supported in this release]
writeExternalDTDToBuffer() Writes the DTD of the document to a buffer. [Not
supported in this release]
writeExternalDTDToClob() Writes the DTD of the document to a clob. [Not
supported in this release]
getDoctype() Retrieves the DTD of the document.
getImplementation() Retrieves the DOM implementation.
getDocumentElement() Retrieves the root element of the document.
createElement() Creates a new element.
createDocumentFragment() Creates a new document fragment.
createTextNode() Creates a Text node.
createComment() Creates a comment node.
createCDATASection() Creates a CDatasection node.
createProcessingInstruction() Creates a processing instruction.
createAttribute() Creates an attribute.
createEntityReference() Creates an Entity reference.
getElementsByTagName() Retrieves the elements in the by tag name.
Table F3 DBMS_XMLDOM Methods Added in Release 2 (9.2.0.2)
Method Syntax
createDocument FUNCTION createDocument (namspaceURI IN VARCHAR2, qualiedName
IN VARCHAR2, doctype IN DOMType :=NULL) REURN DocDocument;
getPrex FUNCTION getPrex(n DOMNode) RETURN VARCHAR2;
setPrex PROCEDURE setPrex (n DOMNode) RETURN VARCHAR2;
hasAttributes FUNCTION hasAttributes (n DOMNode) RETURN BOOLEAN;
getNamedItem FUNCTION getNamedItem (nnm DOMNamedNodeMap, name IN
VARCHAR2, ns IN VARCHAR2) RETURN DOMNode;
setNamedItem FUNCTION getNamedItem (nnm DOMNamedNodeMap, arg IN DOMNode,
ns IN VARCHAR2) RETURN DOMNode;
Table F2 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods (Cont.)
Group/Method Description
PL/SQL Parser for XMLType (DBMS_XMLPARSER)
F-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
PL/SQL Parser for XMLType (DBMS_XMLPARSER)
You can access the content and structure of XML documents through the PL/SQL
Parser for XMLType (DBMS_XMLPARSER).
Table F4 lists the PL/SQL Parser for XMLType (DBMS_XMLPARSER) functions
and procedures.
removeNamedItem FUNCTION removeNamedItem (nnm DOMNamesNodeMap, name in
VARCHAR2, ns IN VARCHAR2) RETURN DOMNode;
getOwnerElement FUNCTION getOwnerElement (a DOMAttr) RETURN DOMElement;
getAttribute FUNCTION getAttribute (elem DOMElement, name IN VARCHAR2, ns IN
VARCHAR2) RETURN VARCHAR2;
hasAttribute FUNCTION hasAttribute (elem DOMElement, name IN VARCHAR2)
RETURN BOOLEAN;
hasAttribute FUNCTION hasAttribute (elem DOMElement, name IN VARCHAR2, ns IN
VARCHAR2) RETURN BOOLEAN;
setAttribute PROCEDURE setAttribute (elem DOMElement, name IN VARCHAR2,
newvalue IN VARCHAR2, ns IN VARCHAR2);
removeAttribute PROCEDURE removeAttribute (elem DOMElement, name IN VARCHAR2,
ns IN VARCHAR2);
getAttributeNode FUNCTION getAttributeNode(elem DOMElement, name IN VARCHAR2, ns
IN VARCHAR2) RETURN DOMAttr;
setAttributeNode FUNCTION setAttributeNode(elem DOMElement, newAttr IN DOMAttr, ns IN
VARCHAR2) RETURN DOMAttr;
createElement FUNCTION createElement (doc DOMDocument, tagname IN VARCHAR2,
ns IN VARCHAR2) RETURN DOMElement;
createAttribute FUNCTION createAttribute (doc DOMDocument, name IN VARCHAR2, ns
IN VARCHAR2) RETURN DOMAttr;
See Also: Chapter 8, "PL/SQL API for XMLType"
Table F3 DBMS_XMLDOM Methods Added in Release 2 (9.2.0.2) (Cont.)
Method Syntax
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-15
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
This PL/SQL implementation of the XSL processor follows the W3C XSLT Working
Draft (Rev WD-xslt-19990813).
Table F5 summarizes the PL/SQL XSLT Processor for XMLType
(DBMS_XSLPROCESSOR) functions and procedures.
Table F4 DBMS_XMLPARSER Functions and Procedures
Functions/Procedures Description
parse() Parses XML stored in the given URL/le.
newParser() Returns a new parser instance
parseBuffer() Parses XML stored in the given buffer
parseClob() Parses XML stored in the given clob
parseDTD() Parses DTD stored in the given url/le
parseDTDBuffer() Parses DTD stored in the given buffer
parseDTDClob() Parses DTD stored in the given clob
setBaseDir() Sets base directory used to resolve relative URLs.
showWarnings() Turns warnings on or off.
setErrorLog() Sets errors to be sent to the specied le
setPreserveWhitespace() Sets white space preserve mode
setValidationMode() Sets validation mode.
getValidationMode() Returns validation mode.
setDoctype() Sets DTD.
getDoctype() Gets DTD Parser.
getDocument() Gets DOM document.
freeParser() Frees a parser object.
getReleaseVersion() Returns the release version of Oracle XML Parser for
PL/SQL.
See Also: Chapter 8, "PL/SQL API for XMLType"
DBMS_XMLSCHEMA
F-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
DBMS_XMLSCHEMA
This package is created by dbmsxsch.sql during the Oracle XML DB installation.
It provides procedures for registering and deleting your XML schemas. Table F6
summarizes the DBMS_XMLSCHEMA functions and procedures.
Table F5 PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
Functions
Functions and Procedures Description
newProcessor() Returns a new processor instance.
processXSL() Transforms an input XML document.
showWarnings() Turns warnings on or off.
setErrorLog() Sets errors to be sent to the specied le.
newStylesheet() Creates a new stylesheet using the given input and
reference URLs.
transformNode() Transforms a node in a DOM tree using the given
stylesheet.
selectNodes() Selects nodes from a DOM tree that match the given
pattern.
selectSingleNodes() Selects the rst node from the tree that matches the
given pattern.
valueOf() Retrieves the value of the rst node from the tree
that matches the given pattern
setParam() Sets a top-level parameter in the stylesheet
removeParam() Removes a top-level stylesheet parameter
resetParams() Resets the top-level stylesheet parameters
freeStylesheet() Frees a stylesheet object
freeProcessor() Frees a processor object
See Also: Chapter 5, "Structured Mapping of XMLType"
DBMS_XMLSCHEMA
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-17
Table F6 DBMS_XMLSCHEMA Functions and Procedures
Constant Description
registerSchema()
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN
VARCHAR2, local IN BOOLEAN :=
TRUE, genTypes IN BOOLEAN :=
TRUE, genbean IN BOOLEAN :=
FALSE, genTables IN BOOLEAN :=
TRUE, force IN BOOLEAN :=
FALSE, owner IN VARCHAR2 :=
null);
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN CLOB,
local IN BOOLEAN := TRUE,
genTypes IN BOOLEAN := TRUE,
genbean IN BOOLEAN := FASLE,
force IN BOOLEAN := FALSE,
owner IN VARCHAR2 := null);
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN BFILE,
local IN BOOLEAN := TRUE,
genTypes IN BOOLEAN := TRUE,
genbean IN BOOLEAN := FALSE,
force IN BOOLEAN := FALSE,
owner IN VARCHAR2 := null);
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN
SYS.XMLType, local IN BOOLEAN
:= TRUE, genTypes INBOOLEAN:=
TRUE, genbean IN BOOLEAN :=
FALSE, force IN BOOLEAN :=
FALSE, owner IN VARCHAR2 :=
null);
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN
SYS.URIType, local INBOOLEAN:=
TRUE, genTypes IN BOOLEAN :=
TRUE, genbean IN BOOLEAN :=
FALSE, force IN BOOLEAN :=
FALSE, owner IN VARCHAR2 :=
null);
Registers the specied XML schema for use by
Oracle XML DB. This schema can then be used to
store documents that conform to it.
Parameters:
schemaURL - URL that uniquely identies the
schema document. This value is used to derive the
path name of the schema document within the XML
DB hierarchy.
schemaDoc - a valid XML schema document
local - is this a local or global schema? By default, all
schemas are registered as local schemas, that is
under /sys/schemas/<username/... If a schema is
registered as global, it is added under
/sys/schemas/PUBLIC/.... You need write
privileges on the preceding directory to be able to
register a schema as global.
genTypes - should the schema compiler generate
object types? By default, TRUE
genbean - should the schema compiler generate Java
beans? By default, FALSE.
genTables - sShould the schema compiler generate
default tables? By default, TRUE
force - if this parameter is set to TRUE, the schema
registration will not raise errors. Instead, it creates
an invalid XML schema object in case of any errors.
By default, the value of this parameter is FALSE.
owner - species the name of the database user
owning the XML schema object. By default, the user
registering the XML schema owns the XML schema
object. Can be used to register an XML schema to be
owned by a different database user.
DBMS_XMLSCHEMA
F-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
DBMS_XMLSCHEMA constants:
I DELETE_RESTRICT, CONSTANT NUMBER := 1;
registerURI()
procedure registerURI(schemaURL
IN varchar2, schemaDocURI IN
varchar2, local IN
BOOLEAN := TRUE, genTypes IN
BOOLEAN := TRUE, genbean IN
BOOLEAN := FALSE, genTables IN
BOOLEAN := TRUE, force IN
BOOLEAN := FALSE, owner IN
VARCHAR2 := null);
Registers an XML schema specied by a URI name.
deleteSchema()
procedure
deleteSchema(schemaURL IN
varchar2, delete_option IN
pls_integer := DELETE_RESTRICT);
Removes the XML schema from Oracle XML DB.
generateBean()
procedure generateBean(schemaURL
IN varchar2);
Generates the Java Bean code corresponding to a
registered XML schema.
compileSchema()
procedure compileSchema(
schemaURL IN varchar2);
Recompiles an already registered XML schema.
Useful for bringing an invalid schema to a valid
state.
generateSchema()
function
generateSchemas(schemaName IN
varchar2, typeName IN varchar2,
elementName IN varchar2 := NULL,
schemaURL IN varchar2 := NULL,
annotate IN BOOLEAN := TRUE,
embedColl INBOOLEAN:= TRUE )
return sys.XMLSequenceType;
function generateSchema(
schemaName IN varchar2,
typeName IN varchar2,
elementName IN varchar2 := NULL,
recurse IN BOOLEAN := TRUE,
annotate IN BOOLEAN := TRUE,
embedColl IN BOOLEAN := TRUE )
return sys.XMLType;
Generates XML schema(s) from an Oracle type
name.
Table F6 DBMS_XMLSCHEMA Functions and Procedures (Cont.)
Constant Description
Oracle XML DB XML Schema Catalog Views
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-19
I DELETE_INVALIDATE,CONSTANT NUMBER := 2;
I DELETE_CASCADE, CONSTANT NUMBER := 3;
I DELETE_CASCADE_FORCE, CONSTANT NUMBER := 4;
Oracle XML DB XML Schema Catalog Views
Table F7 lists the Oracle XML DB XML schema catalog views.
Table F7 Oracle XML DB: XML Schema Catalog View
Schema Description
USER_XML_SCHEMAS Lists all registered XML Schemas owned by the user.
ALL_XML_SCHEMAS Lists all registered XML Schemas usable by the
current user.
DBA_XML_SCHEMAS Lists all registered XML Schemas in Oracle XML DB.
DBA_XML_TABLES Lists all XMLType tables in the system.
USER_XML_TABLES Lists all XMLType tables owned by the current user.
ALL_XML_TABLES Lists all XMLType tables usable by the current user.
DBA_XML_TAB_COLS Lists all XMLType table columns in the system.
USER_XML_TAB_COLS Lists all XMLType table columns in tables owned by
the current user.
ALL_XML_TAB_COLS Lists all XMLType table columns in tables usable by
the current user.
DBA_XML_VIEWS Lists all XMLType views in the system.
USER_XML_VIEWS Lists all XMlType views owned by the current user.
ALL_XML_VIEWS Lists all XMLType views usable by the current user.
DBA_XML_VIEW_COLS Lists all XMLType view columns in the system.
USER_XML_VIEW_COLS Lists all XMLType view columns in views owned by
the current user.
ALL_XML_VIEW_COLS Lists all XMLType view columns in views usable by
the current user.
Resource API for PL/SQL (DBMS_XDB)
F-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Resource API for PL/SQL (DBMS_XDB)
Resource API for PL/SQL (DBMS_XDB) PL/SQL package provides functions for the
following oracle XML DB tasks:
I Resource management of Oracle XML DB hierarchy. These functions
complement the functionality provided by Resource Views.
I Oracle XML DB's Access Control List (ACL) for security management. The
ACL-based security mechanism can be used for either:
In-hierarchy ACLs, ACLs stored through Oracle XML DB resource API
In-memory ACLs, that can be stored outside Oracle XML DB.
Some of these methods can be used for both Oracle XML DB resources and
arbitrary database objects. AclCheckPrivileges() enables database users
access to Oracle XML DB ACL-based security mechanism without having to
store their objects in the Oracle XML DB hierarchy.
I Oracle XML DB conguration session management.
I Rebuilding of hierarchical indexes.
Table F8 summarizes the DBMS_XDB functions and procedures.
See Also: Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
Table F8 DBMS_XDB Functions and Procedures
Function/Procedure Description
getAclDocument()
FUNCTION getAclDocument(
abspath IN VARCHAR2) RETURN
sys.xmltype;
Retrieves ACL document that protects resource
given its path name.
getPrivileges()
FUNCTION getPrivileges( res_path
IN VARCHAR2) RETURN
sys.xmltype;
Gets all privileges granted to the current user on the
given XML DB resource.
changePrivileges()
FUNCTION changePrivileges(
res_path IN VARCHAR2, ace IN
xmltype) RETURN
pls_integer;
Adds the given ACE to the given resource's ACL.
Resource API for PL/SQL (DBMS_XDB)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-21
checkPrivileges()
FUNCTION checkPrivileges(
res_path IN VARCHAR2, privs IN
xmltype) RETURN pls_integer;
Checks access privileges granted to the current user
on the specied XML DB resource.
setacl()
PROCEDURE setacl( res_path IN
VARCHAR2, acl_path IN
VARCHAR2);
Sets the ACL on the given XML DB resource to be
the ACL specied.
AclCheckPrivileges()
FUNCTION AclCheckPrivileges(
acl_path IN VARCHAR2, owner IN
VARCHAR2, privs IN xmltype)
RETURN pls_integer;
Checks access privileges granted to the current user
by specied ACL document on a resource whose
owner is specied by the 'owner' parameter.
LockResource()
FUNCTION LockResource( path IN
VARCHAR2, depthzero IN
BOOLEAN, shared IN boolean)
RETURN BOOLEAN;
Gets a WebDAV-style lock on that resource given a
path to that resource.
GetLockToken()
PROCEDURE GetLockToken( path
IN VARCHAR2, locktoken OUT
VARCHAR2);
Returns that resource's lock token for the current
user given a path to a resource.
UnlockResource()
FUNCTION UnlockResource( path
IN VARCHAR2, deltoken IN
VARCHAR2) RETURN BOOLEAN;
Unlocks the resource given a lock token and a path
to the resource.
Table F8 DBMS_XDB Functions and Procedures (Cont.)
Function/Procedure Description
Resource API for PL/SQL (DBMS_XDB)
F-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
CreateResource()
FUNCTIONCreateResource(pathIN
VARCHAR2,data IN VARCHAR2)
RETURN BOOLEAN;
FUNCTIONCreateResource(pathIN
VARCHAR2, data IN
SYS.XMLTYPE) RETURN
BOOLEAN;
FUNCTIONCreateResource(pathIN
VARCHAR2, datarow IN REF
SYS.XMLTYPE) RETURN
BOOLEAN;
FUNCTIONCreateResource(pathIN
VARCHAR2, data IN CLOB)
RETURN BOOLEAN;
FUNCTION CreateResource(path
IN VARCHAR2, data IN BFILE)
RETURN BOOLEAN;
FUNCTION CreateResource(
abspath INVARCHAR2,
data IN BFILE, csid IN NUMBER :=
0) RETURN BOOLEAN;
FUNCTION CreateResource(
abspath IN VARCHAR2, data IN
BLOB, csid IN NUMBER := 0)
RETURN BOOLEAN;
Creates a new resource.
CreateFolder()
FUNCTION CreateFolder( path IN
VARCHAR2) RETURN BOOLEAN;
Creates a new folder resource in the hierarchy.
DeleteResource()
PROCEDURE DeleteResource( path
IN VARCHAR2);
Deletes a resource from the hierarchy.
Link()
PROCEDURE Link( srcpath IN
VARCHAR2, linkfolder IN
VARCHAR2, linkname IN
VARCHAR2);
Creates a link to an existing resource.
CFG_Refresh()
PROCEDURE CFG_Refresh;
Refreshes the session's conguration information to
the latest conguration.
Table F8 DBMS_XDB Functions and Procedures (Cont.)
Function/Procedure Description
DBMS_XMLGEN
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-23
DBMS_XMLGEN
PL/SQL package DBMS_XMLGEN transforms SQL query results into a canonical
XML format. It inputs an arbitrary SQL query, converts it to XML, and returns the
result as a CLOB. DBMS_XMLGEN is similar to the DBMS_XMLQUERY, except that it is
written in C and compiled in the kernel. This package can only be run in the
database.
Table F9 summarizes the DBMS_XMLGEN functions and procedures.
CFG_Get()
FUNCTION CFG_Get RETURN
SYS.XMLType;
Retrieves the session's conguration information.
CFG_Update()
PROCEDURE CFG_Update(
xdbcong IN SYS.XMLTYPE);
Updates the conguration information.
See Also: Chapter 10, "Generating XML Data from the Database"
Table F9 DBMS_XMLGEN Functions and Procedures
Function/Procedure Description
newContext() Creates a new context handle.
setRowTag() Sets the name of the element enclosing each row of
the result. The default tag is ROW.
setRowSetTag () Sets the name of the element enclosing the entire
result. The default tag is ROWSET.
getXML() Gets the XML document.
getNumRowsProcessed() Gets the number of SQL rows that were processed in
the last call to getXML.
setMaxRows() Sets the maximum number of rows to be fetched
each time.
setSkipRows() Sets the number of rows to skip every time before
generating the XML. The default is 0.
Table F8 DBMS_XDB Functions and Procedures (Cont.)
Function/Procedure Description
RESOURCE_VIEW, PATH_VIEW
F-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
RESOURCE_VIEW, PATH_VIEW
Oracle XML DB RESOURCE_VIEW and PATH_VIEW provide a mechanism for
SQL-based access of data stored in the Oracle XML DB Repository. Data stored in
the Oracle XML DB Repository through protocols such as FTP or WebDAV API can
be accessed in SQL through RESOURCE and PATH VIEWS.
Oracle XML DB Resource API for PL/SQL is based on RESOURCE_VIEW, PATH
VIEW and some PL/SQL packages. It provides query and DML functionality.
PATH_VIEW has one row for each unique path in the Repository, whereas
REOURCE_VIEW has one row for each resource in the Repository.
Table F10 summarizes the Oracle XML DB Resource API for PL/SQL operators.
setConvertSpecialChars() Sets whether special characters such as $, which are
non-XML characters, should be converted or not to
their escaped representation. The default is to
perform the conversion.
convert() Converts the XML into the escaped or unescaped
XML equivalent.
useItemTagsForColl() Forces the use of the collection column name
appended with the tag _ITEM for collection
elements. The default is to set the underlying object
type name for the base element of the collection.
restartQUERY() Restarts the query to start fetching from the
beginning.
closeContext() Closes the context and releases all resources.
See Also: Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
Table F9 DBMS_XMLGEN Functions and Procedures (Cont.)
Function/Procedure Description
DBMS_XDB_VERSION
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-25
DBMS_XDB_VERSION
DBMS_XDB_VERSION along with DBMS_XDB implement the Oracle XML DB
versioning API.
Table F11 summarizes the DBMS_XDB_VERSION functions and procedures.
Table F10 RESOURCE_VIEW, PATH_VIEW Operators
Operator Description
UNDER_PATH
INTEGER UNDER_PATH(
resource_column, pathname);
INTEGER UNDER_PATH(
resource_column, depth, pathname);
INTEGER UNDER_PATH(
resource_column,pathname,correlati
on)
INTEGER UNDER_PATH(
resource_column, depth,pathname,
correlation)
Using the Oracle XML DB hierarchical index,
returns sub-paths of a particular path.
Parameters:
resource_column - column name or column alias of the
'resource' column in the path_view or
resource_view.
pathname - path name to resolve.
depth - maximum depth to search; a depth of less than 0 is
treated as 0.
correlation - integer that can be used to correlate the
UNDER_PATH operator (a primary operator) with ancillary
operators (PATH and DEPTH).
EQUALS_PATH
EQUALS_PATH INTEGER
EQUALS_PATH(resource_column,
pathname);
Finds the resource with the specied path name.
PATH
PATH VARCHAR2 PATH(
correlation);
Returns the relative path name of the resource under
the specied path name argument.
DEPTH
DEPTH INTEGER DEPTH(
correlation);
Returns the folder depth of the resource under the
specied starting path.
See Also: Chapter 14, "Oracle XML DB Versioning"
DBMS_XDB_VERSION
F-26 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Table F11 DBMS_XDB_VERSION Functions and Procedures
Function/Procedure Description
MakeVersioned()
FUNCTION MakeVersioned(
pathname VARCHAR2) RETURN
dbms_xdb.resid_type;
Turns a regular resource whose path name is given
into a version-controlled resource.
Checkout()
PROCEDURE Checkout( pathname
VARCHAR2);
Checks out a VCR before updating or deleting it.
Checkin()
FUNCTION Checkin( pathname
VARCHAR2) RETURN
dbms_xdb.resid_type;
Checks in a checked-out VCR and returns the
resource id of the newly-created version.
Uncheckout()
FUNCTION Uncheckout( pathname
VARCHAR2) RETURN
dbms_xdb.resid_type;
Checks in a checked-out resource and returns
the resource id of the version before the
resource is checked out.
GetPredecessors()
FUNCTION GetPredecessors(
pathname VARCHAR2) RETURN
resid_list_type;
Retrieves the list of predecessors by path name.
GetPredsByResId()
FUNCTION GetPredsByResId( resid
resid_type) RETURN resid_list_type;
Retrieves the list of predecessors by resource id.
GetResourceByResId()
FUNCTION GetResourceByResId(
resid resid_type) RETURN
XMLType;
Obtains the resource as an XMLType, given the
resource objectID.
GetSuccessors()
FUNCTION GetSuccessors(
pathname VARCHAR2) RETURN
resid_list_type;
Retrieves the list of successors by path name.
GetSuccsByResId()
FUNCTION GetSuccsByResId( resid
resid_type) RETURN resid_list_type;
Retrieves the list of successors by resource id.
DBMS_XDBT
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-27
DBMS_XDBT
Using DBMS_XDBT you can set up an Oracle Text ConText index on the Oracle
XML DB Repository hierarchy. DBMS_XDBT creates default preferences and the
Oracle Text index. It also sets up automatic synchronization of the ConText index.
DBMS_XDBT contains variables that describe the conguration settings for the
ConText index. These are intended to cover the basic customizations that
installations may require, but they are not a complete set.
Use DBMS_XDBT for the following tasks:
I To customize the package to set up the appropriate conguration
I To drop existing index preferences using dropPreferences()
I To create new index preferences using createPreferences()
I To create the ConText index using the createIndex()
I To set up automatic synchronization of the ConText index using the
configureAutoSync()
Table F12 summarizes the DBMS_XDBT functions and procedures.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Table F12 DBMS_XDBT Functions and Procedures
Procedure/Function Description
dropPreferences() Drops any existing preferences.
createPreferences() Creates preferences required for the ConText index
on the XML DB hierarchy.
createDatastorePref() Creates a USER datastore preference for the ConText
index.
createFilterPref() Creates a lter preference for the ConText index.
createLexerPref() Creates a lexer preference for the ConText index.
createWordlistPref() Creates a stoplist for the ConText index.
createStoplistPref() Creates a section group for the ConText index.
createStoragePref() Creates a wordlist preference for the ConText
index.
createSectiongroupPref() Creates a storage preference for the ConText index.
DBMS_XDBT
F-28 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
createIndex() Creates the ConText index on the XML DB
hierarchy.
congureAutoSync() Congures the ConText index for automatic
maintenance (SYNC).
Table F12 DBMS_XDBT Functions and Procedures (Cont.)
Procedure/Function Description
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-1
G
Example Setup scripts. Oracle XML DB -
Supplied XML Schemas
This appendix describes a few example setup scripts for use with the examples in
Chapter 3, "Using Oracle XML DB". It also includes the structure of Resource View
and Path View and the Oracle XML DB supplied XML schema:
I Example Setup Scripts
I RESOURCE_VIEW and PATH_VIEW Database and XML Schema
I XDBResource.xsd: XML Schema for Representing Oracle XML DB Resources
I acl.xsd: XML Schema for Representing Oracle XML DB ACLs
I xdbcong.xsd: XML Schema for Conguring Oracle XML DB
Example Setup Scripts
G-2 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
Example Setup Scripts
The following sections include the setup scripts and sample les used for the
examples in Chapter 3, "Using Oracle XML DB".
Chapter 3 Examples Set Up Script: Creating User and Directory
set echo on
connect / as sysdba
drop directory DIR;
drop user &1 cascade;
create user &1 identified by &2;
grant create any directory, drop any directory to &1;
grant connect, resource to &1;
connect &1/&2
create or replace function getFileContent(file bfile)
return CLOB deterministic
is
charContent CLOB := ;
targetFile bfile;
warning number;
begin
targetFile := file;
DBMS_LOB.fileopen(targetFile, DBMS_LOB.file_readonly);
DBMS_LOB.loadfromFile(charContent,targetFile,
DBMS_LOB.getLength(targetFile),1,1);
DBMS_LOB.fileclose(targetFile);
return charContent;
end;
/
show errors;
drop directory DIR;
create directory DIR as &3;
create or replace function getDocument(filename varchar2)
return CLOB deterministic
is
file bfile := bfilename(DIR,filename);
charContent CLOB := ;
targetFile bfile;
warning number;
begin
targetFile := file;
DBMS_LOB.fileopen(targetFile, DBMS_LOB.file_readonly);
DBMS_LOB.loadfromFile(charContent,targetFile,
DBMS_LOB.getLength(targetFile),1,1);
Example Setup Scripts
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-3
DBMS_LOB.fileclose(targetFile);
return charContent;
end;
/
show errors
declare
result boolean;
begin
result := dbms_xdb.createfolder(/public/&4);
end;
/
commit;
quit
Chapter 3 Examples Set Up Script: Granting Privileges, Creating Table...
This script grants appropriate privileges, creates tables with XMLType Columns,
creates XMLType tables, Inserts, queries, and updates the tables:
set echo on
connect scott/tiger
grant all on emp to &1;
connect &1/&2
--
-- Table Creation Examples
--
create table EXAMPLE1
(
KEYVALUE varchar2(10) primary key,
XMLCOLUMN xmltype
);
create table XMLTABLE of XMLType;
--
-- Insert Example
--
describe getDocument;
insert into XMLTABLE
values (xmltype(getDocument(purchaseorder.xml)))
/
commit
/
--
-- Valid existsNode operations
--
select existsNode(value(X),/PurchaseOrder/Reference)
Example Setup Scripts
G-4 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
from XMLTABLE X
/
select existsNode(value(X),
/PurchaseOrder[Reference="ADAMS-20011127121040988PST"])
from XMLTABLE X
/
select existsNode(value(X),
/PurchaseOrder/LineItems/LineItem[2]/Part[@Id="037429135020"])
from XMLTABLE X
/
select existsNode(value(X),
/PurchaseOrder/LineItems/LineItem[Description="8 1/2"])
from XMLTABLE X
/
--
-- Invalid existsNode() operations
--
select existsNode(value(X),/PurchaseOrder/UserName)
from XMLTABLE X
/
select existsNode(value(X),
/PurchaseOrder[Reference="ADAMS-XXXXXXXXXXXXXXXXXXXX"])
from XMLTABLE X
/
select existsNode(value(X),
/PurchaseOrder/LineItems/LineItem[3]/Part[@Id="037429135020"])
from XMLTABLE X
/
select existsNode(value(X),
/PurchaseOrder/LineItems/LineItem[Description="Snow White"])
from XMLTABLE X
/
--
-- existsNode() in where clause examples
--
select count(*)
from XMLTABLE x
where existsNode(value(x),/PurchaseOrder[User="ADAMS"]) = 1
/
delete from XMLTABLE x
where existsNode(value(x),/PurchaseOrder[User="ADAMS"]) = 1
/
commit
/
--
Example Setup Scripts
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-5
-- Reload the Sample Document.
--
insert into XMLTABLE
values (xmltype(getDocument(purchaseorder.xml)))
/
commit
/
--
-- Valid extractValue() operiations
--
select extractValue(value(x),/PurchaseOrder/Reference)
from XMLTABLE X
/
select extractValue(value(x),
/PurchaseOrder/LineItems/LineItem[2]/Part/@Id)
from XMLTABLE X
/
--
-- Invalid extractValue() operations
--
select extractValue(value(X),
/PurchaseOrder/LineItems/LineItem/Description)
from XMLTABLE X
/
select extractValue(value(X),
/PurchaseOrder/LineItems/LineItem[1])
from XMLTABLE X
/
select extractValue(value(x),/PurchaseOrder/Reference)
from XMLTABLE X, SCOTT.EMP
where extractValue(value(x),/PurchaseOrder/User) = EMP.ENAME
and EMP.EMPNO = 7876
/
--
-- extract() operations
--
set long 10000
select extract(value(X),
/PurchaseOrder/LineItems/LineItem/Description)
from XMLTABLE X
/
select extract(value(X),
/PurchaseOrder/LineItems/LineItem[1])
from XMLTABLE X
/
Example Setup Scripts
G-6 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
set long 10000
set feedback on
select extractValue(value(t),/Description)
from XMLTABLE X,
table ( xmlsequence (
extract(value(X),
/PurchaseOrder/LineItems/LineItem/Description)
)
) t
/
update XMLTABLE t
set value(t) = updateXML(value(t),
/PurchaseOrder/Reference/text(),
MILLER-200203311200000000PST)
where existsNode(value(t),
/PurchaseOrder[Reference="ADAMS-20011127121040988PST"]) = 1
/
select value(t)
from XMLTABLE t
/
update XMLTABLE t
set value(t) =
updateXML(value(t),
/PurchaseOrder/LineItems/LineItem[2],
xmltype(<LineItem ItemNumber="4">
<Description>Andrei Rublev</Description>
<Part Id="715515009928" UnitPrice="39.95"
Quantity="2"/>
</LineItem>
)
)
where existsNode(value(t),
/PurchaseOrder[Reference="MILLER-200203311200000000PST"]
) = 1
/
select value(t)
from XMLTABLE t
where existsNode(value(t),
/PurchaseOrder[Reference="MILLER-200203311200000000PST"]
) = 1
/
select value(t).transform(xmltype(getDocument(purchaseOrder.xsl)))
from XMLTABLE t
where existsNode(value(t),
/PurchaseOrder[Reference="MILLER-200203311200000000PST"]
Example Setup Scripts
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-7
) = 1
/
begin
dbms_xmlschema.registerSchema(
http://www.oracle.com/xsd/purchaseOrder.xsd,
getDocument(purchaseOrder.xsd),
TRUE, TRUE, FALSE, FALSE
);
end;
/
create table XML_PURCHASEORDER of XMLType
XMLSCHEMA "http://www.oracle.com/xsd/purchaseOrder.xsd"
ELEMENT "PurchaseOrder"
/
describe XML_PURCHASEORDER
insert into XML_PURCHASEORDER
values (xmltype(getDocument(Invoice.xml)))
/
alter table XML_PURCHASEORDER
add constraint VALID_PURCHASEORDER
check (XMLIsValid(sys_nc_rowinfo$)=1)
/
insert into XML_PURCHASEORDER
values (xmltype(getDocument(InvalidPurchaseOrder.xml)))
/
alter table XML_PURCHASEORDER
drop constraint VALID_PURCHASEORDER
/
create trigger VALIDATE_PURCHASEORDER
before insert on XML_PURCHASEORDER
for each row
declare
XMLDATA xmltype;
begin
XMLDATA := :new.sys_nc_rowinfo$;
xmltype.schemavalidate(XMLDATA);
end;
/
insert into XML_PURCHASEORDER
values (xmltype(getDocument(InvalidPurchaseOrder.xml)))
/
drop table XML_PURCHASEORDER;
begin
dbms_xmlSchema.deleteSchema(http://www.oracle.com/xsd/purchaseOrder.xsd,4);
end;
Example Setup Scripts
G-8 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
/
begin
dbms_xmlschema.registerSchema(
http://www.oracle.com/xsd/purchaseOrder.xsd,
getDocument(purchaseOrder1.xsd),
TRUE, TRUE, FALSE, FALSE
);
end;
/
describe XML_PURCHASEORDER_TYPE
drop table XML_PURCHASEORDER;
begin
dbms_xmlSchema.deleteSchema(http://www.oracle.com/xsd/purchaseOrder.xsd,4);
end;
/
begin
dbms_xmlschema.registerSchema(
http://www.oracle.com/xsd/purchaseOrder.xsd,
getDocument(purchaseOrder2.xsd),
TRUE, TRUE, FALSE, FALSE
);
end;
/
describe XML_PURCHASEORDER_TYPE
quit
Loading Files
set echo on
connect &1/&2
declare
result boolean;
begin
result := dbms_xdb.createResource(/public/&3/&4,
getFileContent(bfilename(DIR,&4)));
end;
/
commit;
quit
Chapter 3 Examples Script: invoice.xml
<Invoice
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Example Setup Scripts
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-9
xsi:noNamespaceSchemaLocation="http://www.oracle.com/xsd/purchaseOrder.xsd">
<Reference>ADAMS-20011127121040988PST</Reference>
<Actions>
<Action>
<User>SCOTT</User>
<Date xsi:nil="true"/>
</Action>
</Actions>
<Reject/>
<Requestor>Julie P. Adams</Requestor>
<CostCenter>R20</CostCenter>
<ShippingInstructions>
<name>Julie P. Adams</name>
<address>300 Oracle Parkway, Redwood Shores, CA 94065</address>
<telephone>650 506 7300</telephone>
</ShippingInstructions>
<SpecialInstructions>Ground</SpecialInstructions>
<LineItems>
<LineItem ItemNumber="1">
<Description>The Ruling Class</Description>
<Part Id="715515012423" UnitPrice="39.95" Quantity="2"/>
</LineItem>
<LineItem ItemNumber="2">
<Description>Diabolique</Description>
<Part Id="037429135020" UnitPrice="29.95" Quantity="3"/>
</LineItem>
<LineItem ItemNumber="3">
<Description>8 1/2</Description>
<Part Id="037429135624" UnitPrice="39.95" Quantity="4"/>
</LineItem>
</LineItems>
</Invoice>
Chapter 3 Examples Script: PurchaseOrder.xml
<PurchaseOrder
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.oracle.com/xdb/po.xsd">
<Reference>ADAMS-20011127121040988PST</Reference>
<Actions>
<Action>
<User>SCOTT</User>
<Date xsi:nil="true"/>
</Action>
</Actions>
Example Setup Scripts
G-10 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<Reject/>
<Requestor>Julie P. Adams</Requestor>
<User>ADAMS</User>
<CostCenter>R20</CostCenter>
<ShippingInstructions>
<name>Julie P. Adams</name>
<address>300 Oracle Parkway, Redwood Shores, CA 94065</address>
<telephone>650 506 7300</telephone>
</ShippingInstructions>
<SpecialInstructions>Ground</SpecialInstructions>
<LineItems>
<LineItem ItemNumber="1">
<Description>The Ruling Class</Description>
<Part Id="715515012423" UnitPrice="39.95" Quantity="2"/>
</LineItem>
<LineItem ItemNumber="2">
<Description>Diabolique</Description>
<Part Id="037429135020" UnitPrice="29.95" Quantity="3"/>
</LineItem>
<LineItem ItemNumber="3">
<Description>8 1/2</Description>
<Part Id="037429135624" UnitPrice="39.95" Quantity="4"/>
</LineItem>
</LineItems>
</PurchaseOrder>
Chapter 3 Examples Script: FTP Script
#! /usr/bin/ksh
TESTDIR=$1
TESTFILENAME=$2
. ./config.sh
SCRIPTFILE=date +%Y%m%d%H%M%S
SCRIPTFILE=/tmp/$SCRIPTFILE.cmd
mkdir /tmp/$TESTDIR
Note:
I The example XML schema, "XML Schema Example,
PurchaseOrder.xsd" is located in Appendix B, "XML Schema
Primer".
I The example XSL le, "XSL Stylesheet Example,
PurchaseOrder.xsl" is located in Appendix D, "XSLT Primer".
Example Setup Scripts
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-11
echo "open $ORAHOSTNAME $ORAFTPPORT" > $SCRIPTFILE
echo "user $ORASQLUSER $ORASQLPASSWORD" >> $SCRIPTFILE
echo "cd public" >> $SCRIPTFILE
echo "cd $TESTDIR" >> $SCRIPTFILE
echo "put $TESTFILENAME" >> $SCRIPTFILE
echo "ls -l" >> $SCRIPTFILE
echo "get $TESTFILENAME /tmp/$TESTDIR/$TESTFILENAME" >> $SCRIPTFILE
echo "quit" >> $SCRIPTFILE
ftp -v -n < $SCRIPTFILE
rm $SCRIPTFILE
echo "Diff Results for $TESTFILENAME"
diff -b $TESTFILENAME /tmp/$TESTDIR/$TESTFILENAME
rm -rf /tmp/$TESTDIR
Chapter 3 Examples Script: Conguring FTP and HTTP Ports
#! /usr/bin/ksh
ORAHOSTNAME=hostname
ORAFTPPORT=2100
ORAHTTPPORT=8080
if [ "$LOGNAME" = "oracle2" ]
then
ORAFTPPORT=2122
ORAHTTPPORT=8088
fi
echo "FTP Port = $ORAFTPPORT"
echo "HTTP Port = $ORAHTTPPORT"
ORASQLUSER=DOC92
ORASQLPASSWORD=DOC92
RESOURCE_VIEW and PATH_VIEW Database and XML Schema
G-12 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
RESOURCE_VIEW and PATH_VIEW Database and XML Schema
The following describes the RESOURCE_VIEW and PATH_VIEW structures.
Resource View Denition and Structure
The RESOURCE_VIEW contains one row for each resource in the Repository. The
following describes its structure:
Column Datatype Description
------ -------- -------------------------------------------------------
RES XMLTYPE A resource in Oracle XML Repository
ANY_PATH VARCHAR2 A path that can be used to access the resource in the
Repository
PATH_VIW Denition and Structure
The PATH_VIEW contains one row for each unique path in the Repository. The
following describes its structure:
Column Datatype Description
------ -------- -----------------------------
PATH VARCHAR2 Path name of a resource
RES XMLTYPE The resource referred by PATH
LINK XMLTYPE Link property
XDBResource.xsd: XML Schema for Representing Oracle XML DB
Resources
Here is the listing for the XML schema, XDBResource.xsd, used to represent
Oracle XML DB resources.
XDBResource.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://xmlns.oracle.com/xdb/XDBResource.xsd"
version="1.0" elementFormDefault="qualified"
xmlns:res="http://xmlns.oracle.com/xdb/XDBResource.xsd">
<simpleType name="OracleUserName">
See Also: Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
See Also: Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
XDBResource.xsd: XML Schema for Representing Oracle XML DB Resources
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-13
<restriction base="string">
<minLength value="1" fixed="false"/>
<maxLength value="4000" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="ResMetaStr">
<restriction base="string">
<minLength value="1" fixed="false"/>
<maxLength value="128" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="SchElemType">
<restriction base="string">
<minLength value="1" fixed="false"/>
<maxLength value="4000" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="GUID">
<restriction base="hexBinary">
<minLength value="8" fixed="false"/>
<maxLength value="32" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="LocksRaw">
<restriction base="hexBinary">
<minLength value="0" fixed="false"/>
<maxLength value="2000" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="LockScopeType">
<restriction base="string">
<enumeration value="Exclusive" fixed="false"/>
<enumeration value="Shared" fixed="false"/>
</restriction>
</simpleType>
<complexType name="LockType" mixed="false">
<sequence>
<element name="owner" type="string"/>
<element name="expires" type="dateTime"/>
XDBResource.xsd: XML Schema for Representing Oracle XML DB Resources
G-14 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<element name="lockToken" type="hexBinary"/>
</sequence>
<attribute name="LockScope" type="res:LockScopeType" />
</complexType>
<complexType name="ResContentsType" mixed="false">
<sequence >
<any name="ContentsAny" />
</sequence>
</complexType>
<complexType name="ResAclType" mixed="false">
<sequence >
<any name="ACLAny"/>
</sequence>
</complexType>
<complexType name="ResourceType" mixed="false">
<sequence >
<element name="CreationDate" type="dateTime"/>
<element name="ModificationDate" type="dateTime"/>
<element name="Author" type="res:ResMetaStr"/>
<element name="DisplayName" type="res:ResMetaStr"/>
<element name="Comment" type="res:ResMetaStr"/>
<element name="Language" type="res:ResMetaStr"/>
<element name="CharacterSet" type="res:ResMetaStr"/>
<element name="ContentType" type="res:ResMetaStr"/>
<element name="RefCount" type="nonNegativeInteger"/>
<element name="Lock" type="res:LocksRaw"/>
<element pname="ACL" type="res:ResAclType" minOccurs="0" maxOccurs="1"/>
<element name="Owner" type="res:OracleUserName" minOccurs="0"
maxOccurs="1"/>
<element name="Creator" type="res:OracleUserName" minOccurs="0"
maxOccurs="1"/>
<element name="LastModifier" type="res:OracleUserName" minOccurs="0"
maxOccurs="1"/>
<element name="SchemaElement" type="res:SchElemType" minOccurs="0"
maxOccurs="1"/>
<element name="Contents" type="res:ResContentsType" minOccurs="0"
maxOccurs="1"/>
<element name="VCRUID" type="res:GUID"/>
<element name="Parents" type="hexBinary" minOccurs="0" maxOccurs="1000"/>
<any name="ResExtra" namespace="##other" minOccurs="0" maxOccurs="65535"/>
</sequence>
acl.xsd: XML Schema for Representing Oracle XML DB ACLs
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-15
<attribute name="Hidden" type="boolean"/>
<attribute name="Invalid" type="boolean"/>
<attribute name="VersionID" type="integer"/>
<attribute name="ActivityID" type="integer"/>
<attribute name="Container" type="boolean"/>
<attribute name="CustomRslv" type="boolean"/>
<attribute name="StickyRef" type="boolean"/>
</complexType>
<element name="Resource" type="res:ResourceType"/>
</schema>
acl.xsd: XML Schema for Representing Oracle XML DB ACLs
This section describes the XML schema used to represent Oracle XML DB ACLs:
ACL Representation XML Schema, acl.xsd
Here is XML schema, acl.xsd, used to represent Oracle XML DB ACLs:
acl.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://xmlns.oracle.com/xdb/acl.xsd" version="1.0"
xmlns:xdb="http://xmlns.oracle.com/xdb"
xmlns:xdbacl="http://xmlns.oracle.com/xdb/acl.xsd"
elementFormDefault="qualified">
<annotation>
<documentation>
This XML schema describes the structure of XML DB ACL documents.
Note : The following "systemPrivileges" element lists all supported
system privileges and their aggregations.
See dav.xsd for description of DAV privileges
Note : The elements and attributes marked "hidden" are for
internal use only.
</documentation>
<appinfo>
<xdb:systemPrivileges>
<xdbacl:all>
<xdbacl:read-properties/>
<xdbacl:read-contents/>
acl.xsd: XML Schema for Representing Oracle XML DB ACLs
G-16 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<xdbacl:read-acl/>
<xdbacl:update/>
<xdbacl:link/>
<xdbacl:unlink/>
<xdbacl:unlink-from/>
<xdbacl:write-acl-ref/>
<xdbacl:update-acl/>
<xdbacl:link-to/>
<xdbacl:resolve/>
</xdbacl:all>
</xdb:systemPrivileges>
</appinfo>
</annotation>
<!-- privilegeNameType (this is an emptycontent type) -->
<complexType name = "privilegeNameType"/>
<!-- privilegeName element
All system and user privileges are in the substitutionGroup
of this element.
-->
<element name = "privilegeName" type="xdbacl:privilegeNameType"
xdb:defaultTable=""/>
<!-- all system privileges in the XML DB ACL namespace -->
<element name = "read-properties" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "read-contents" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "read-acl" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "update" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "link" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "unlink" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "unlink-from" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "write-acl-ref" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "update-acl" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "link-to" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
acl.xsd: XML Schema for Representing Oracle XML DB ACLs
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-17
<element name = "resolve" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<element name = "all" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName" xdb:defaultTable=""/>
<!-- privilege element -->
<element name = "privilege" xdb:SQLType = "XDB$PRIV_T" xdb:defaultTable="">
<complexType>
<choice maxOccurs="unbounded">
<any xdb:transient="generated"/>
<!-- HIDDEN ELEMENTS -->
<element name = "privNum" type = "hexBinary" xdb:baseProp="true"
xdb:hidden="true"/>
</choice>
</complexType>
</element>
<!-- ace element -->
<element name = "ace" xdb:SQLType = "XDB$ACE_T" xdb:defaultTable="">
<complexType> <sequence>
<element name = "grant" type = "boolean"/>
<element name = "principal" type = "string"
xdb:transient="generated"/>
<element ref="xdbacl:privilege" minOccurs="1"/>
<!-- HIDDEN ELEMENTS -->
<element name = "principalID" type = "hexBinary" minOccurs="0"
xdb:baseProp="true" xdb:hidden="true"/>
<element name = "flags" type = "unsignedInt" minOccurs="0"
xdb:baseProp="true" xdb:hidden="true"/>
</sequence> </complexType>
</element>
<!-- acl element -->
<element name = "acl" xdb:SQLType = "XDB$ACL_T" xdb:defaultTable = "XDB$ACL">
<complexType>
<sequence>
<element name = "schemaURL" type = "string" minOccurs="0"
xdb:transient="generated"/>
<element name = "elementName" type = "string" minOccurs="0"
xdb:transient="generated"/>
<element ref = "xdbacl:ace" minOccurs="1" maxOccurs = "unbounded"
xdb:SQLCollType="XDB$ACE_LIST_T"/>
<!-- HIDDEN ELEMENTS -->
<element name = "schemaOID" type = "hexBinary" minOccurs="0"
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
G-18 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
xdb:baseProp="true" xdb:hidden="true"/>
<element name = "elementNum" type = "unsignedInt" minOccurs="0"
xdb:baseProp="true" xdb:hidden="true"/>
</sequence>
<attribute name = "shared" type = "boolean" default="true"/>
<attribute name = "description" type = "string"/>
</complexType>
</element>
</schema>';
xdbcong.xsd: XML Schema for Conguring Oracle XML DB
Here is xdbconfig.xsd, the XML schema used to congure Oracle XML DB:
xdbcong.xsd
<schema targetNamespace="http://xmlns.oracle.com/xdb/xdbconfig.xsd"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xdbc="http://xmlns.oracle.com/xdb/xdbconfig.xsd"
xmlns:xdb="http://xmlns.oracle.com/xdb"
version="1.0" elementFormDefault="qualified">
<element name="xdbconfig" xdb:defaultTable="XDB$CONFIG">
<complexType><sequence>
<!-- predefined XML DB properties - these should NOT be changed -->
<element name="sysconfig">
<complexType><sequence>
<!-- generic XML DB properties -->
<element name="acl-max-age" type="unsignedInt" default="1000"/>
<element name="acl-cache-size" type="unsignedInt" default="32"/>
<element name="invalid-pathname-chars" type="string" default=""/>
<element name="case-sensitive" type="boolean" default="true"/>
<element name="call-timeout" type="unsignedInt" default="300"/>
<element name="max-link-queue" type="unsignedInt" default="65536"/>
<element name="max-session-use" type="unsignedInt" default="100"/>
<element name="persistent-sessions" type="boolean" default="false"/>
<element name="default-lock-timeout" type="unsignedInt"
default="3600"/>
<element name="xdbcore-logfile-path" type="string"
default="/sys/log/xdblog.xml"/>
<element name="xdbcore-log-level" type="unsignedInt" default="0"/>
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-19
<element name="resource-view-cache-size" type="unsignedInt"
default="1048576"/>
<element name="case-sensitive-index-clause" type="string"
minOccurs="0"/>
<!-- protocol specific properties -->
<element name="protocolconfig">
<complexType><sequence>
<!-- these apply to all protocols -->
<element name="common">
<complexType><sequence>
<element name="extension-mappings">
<complexType><sequence>
<element name="mime-mappings" type="xdbc:mime-mapping-type"/>
<element name="lang-mappings" type="xdbc:lang-mapping-type"/>
<element name="charset-mappings"
type="xdbc:charset-mapping-type"/>
<element name="encoding-mappings"
type="xdbc:encoding-mapping-type"/>
</sequence></complexType>
</element>
<element name="session-pool-size" type="unsignedInt"
default="50"/>
<element name="session-timeout" type="unsignedInt"
default="6000"/>
</sequence></complexType>
</element>
<!-- FTP specific -->
<element name="ftpconfig">
<complexType><sequence>
<element name="ftp-port" type="unsignedShort" default="2100"/>
<element name="ftp-listener" type="string"/>
<element name="ftp-protocol" type="string"/>
<element name="logfile-path" type="string"
default="/sys/log/ftplog.xml"/>
<element name="log-level" type="unsignedInt" default="0"/>
<element name="session-timeout" type="unsignedInt"
default="6000"/>
<element name="buffer-size" default="8192">
<simpleType>
<restriction base="unsignedInt">
<minInclusive value="1024"/> <!-- 1KB -->
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
G-20 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<maxInclusive value="1048496"/> <!-- 1MB -->
</restriction>
</simpleType>
</element>
</sequence></complexType>
</element>
<!-- HTTP specific -->
<element name="httpconfig">
<complexType><sequence>
<element name="http-port" type="unsignedShort" default="8080"/>
<element name="http-listener" type="string"/>
<element name="http-protocol" type="string"/>
<element name="max-http-headers" type="unsignedInt"
default="64"/>
<element name="max-header-size" type="unsignedInt"
default="4096"/>
<element name="max-request-body" type="unsignedInt"
default="2000000000" minOccurs="1"/>
<element name="session-timeout" type="unsignedInt"
default="6000"/>
<element name="server-name" type="string"/>
<element name="logfile-path" type="string"
default="/sys/log/httplog.xml"/>
<element name="log-level" type="unsignedInt" default="0"/>
<element name="servlet-realm" type="string" minOccurs="0"/>
<element name="webappconfig">
<complexType><sequence>
<element name="welcome-file-list"
type="xdbc:welcome-file-type"/>
<element name="error-pages" type="xdbc:error-page-type"/>
<element name="servletconfig"
type="xdbc:servlet-config-type"/>
</sequence></complexType>
</element>
<element name="default-url-charset" type="string"
minOccurs="0"/>
</sequence></complexType>
</element>
</sequence></complexType>
</element>
</sequence></complexType>
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-21
</element>
<!-- users can add any properties they want here -->
<element name="userconfig" minOccurs="0">
<complexType><sequence>
<any maxOccurs="unbounded" namespace="##other"/>
</sequence></complexType>
</element>
</sequence></complexType>
</element>
<complexType name="welcome-file-type">
<sequence>
<element name="welcome-file" minOccurs="0" maxOccurs="unbounded">
<simpleType>
<restriction base="string">
<pattern value="[^/]*"/>
</restriction>
</simpleType>
</element>
</sequence>
</complexType>
<!-- customized error pages -->
<complexType name="error-page-type">
<sequence>
<element name="error-page" minOccurs="0" maxOccurs="unbounded">
<complexType><sequence>
<choice>
<element name="error-code">
<simpleType>
<restriction base="positiveInteger">
<minInclusive value="100"/>
<maxInclusive value="999"/>
</restriction>
</simpleType>
</element>
<!-- Fully qualified classname of a Java exception type -->
<element name="exception-type" type="string"/>
<element name="OracleError">
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
G-22 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<complexType><sequence>
<element name="facility" type="string" default="ORA"/>
<element name="errnum" type="unsignedInt"/>
</sequence></complexType>
</element>
</choice>
<element name="location" type="anyURI"/>
</sequence></complexType>
</element>
</sequence>
</complexType>
<!-- parameter for a servlet: name, value pair and a description -->
<complexType name="param">
<sequence>
<element name="param-name" type="string"/>
<element name="param-value" type="string"/>
<element name="description" type="string"/>
</sequence>
</complexType>
<complexType name="servlet-config-type">
<sequence>
<element name="servlet-mappings">
<complexType><sequence>
<element name="servlet-mapping" minOccurs="0"
maxOccurs="unbounded">
<complexType><sequence>
<element name="servlet-pattern" type="string"/>
<element name="servlet-name" type="string"/>
</sequence></complexType>
</element>
</sequence></complexType>
</element>
<element name="servlet-list">
<complexType><sequence>
<element name="servlet" minOccurs="0" maxOccurs="unbounded">
<complexType><sequence>
<element name="servlet-name" type="string"/>
<element name="servlet-language">
<simpleType>
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
Example Setup scripts. Oracle XML DB - Supplied XML Schemas G-23
<restriction base="string">
<enumeration value="C"/>
<enumeration value="Java"/>
<enumeration value="PL/SQL"/>
</restriction>
</simpleType>
</element>
<element name="icon" type="string" minOccurs="0"/>
<element name="display-name" type="string"/>
<element name="description" type="string" minOccurs="0"/>
<choice>
<element name="servlet-class" type="string" minOccurs="0"/>
<element name="jsp-file" type="string" minOccurs="0"/>
</choice>
<element name="servlet-schema" type="string" minOccurs="0"/>
<element name="init-param" minOccurs="0"
maxOccurs="unbounded" type="xdbc:param"/>
<element name="load-on-startup" type="string" minOccurs="0"/>
<element name="security-role-ref" minOccurs="0"
maxOccurs="unbounded">
<complexType><sequence>
<element name="description" type="string" minOccurs="0"/>
<element name="role-name" type="string"/>
<element name="role-link" type="string"/>
</sequence></complexType>
</element>
</sequence></complexType>
</element>
</sequence></complexType>
</element>
</sequence>
</complexType>
<complexType name="lang-mapping-type"><sequence>
<element name="lang-mapping" minOccurs="0" maxOccurs="unbounded">
<complexType><sequence>
<element name="extension" type="xdbc:exttype"/>
<element name="lang" type="string"/>
</sequence></complexType>
</element></sequence>
</complexType>
<complexType name="charset-mapping-type"><sequence>
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
G-24 Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2.0.2)
<element name="charset-mapping" minOccurs="0" maxOccurs="unbounded">
<complexType><sequence>
<element name="extension" type="xdbc:exttype"/>
<element name="charset" type="string"/>
</sequence></complexType>
</element></sequence>
</complexType>
<complexType name="encoding-mapping-type"><sequence>
<element name="encoding-mapping" minOccurs="0" maxOccurs="unbounded">
<complexType><sequence>
<element name="extension" type="xdbc:exttype"/>
<element name="encoding" type="string"/>
</sequence></complexType>
</element></sequence>
</complexType>
<complexType name="mime-mapping-type"><sequence>
<element name="mime-mapping" minOccurs="0" maxOccurs="unbounded">
<complexType><sequence>
<element name="extension" type="xdbc:exttype"/>
<element name="mime-type" type="string"/>
</sequence></complexType>
</element></sequence>
</complexType>
<simpleType name="exttype">
<restriction base="string">
<pattern value="[^\*\./]*"/>
</restriction>
</simpleType>
</schema>
Glossary-1
Glossary
Access control entry (ACE)
An entry in the access control list that grants or denies access to a given principal.
access control list (ACL)
A list of access control entries that determines which principals have access to a
given resource or resources.
ACE
Access Control Entry. See access control entry.
ACL
Access Control List. See access control list.
API
Application Program Interface. See application program interface.
application program interface (API)
A set of public programmatic interfaces that consist of a language and message
format to communicate with an operating system or other programmatic
environment, such as databases, Web servers, JVMs, and so forth. These messages
typically call functions and methods available for application development.
application server
A server designed to host applications and their environments, permitting server
applications to run. A typical example is Oracle9iAS, which is able to host Java, C,
C++, and PL/SQL applications in cases where a remote client controls the interface.
See also Oracle Application Server.
Glossary-2
attribute
A property of an element that consists of a name and a value separated by an equals
sign and contained within the start-tags after the element name. In this example,
<Price units=USD>5</Price>, units is the attribute and USD is its value,
which must be in single or double quotes. Attributes may reside in the document or
DTD. Elements may have many attributes but their retrieval order is not dened.
BC4J
Business Components for Java, a J2EE application development framework that
comes with JDeveloper. BC4J is an object-relational mapping tool that implements
J2EE Design Patterns.
BFILES
External binary les that exist outside the database tablespaces residing in the
operating system. BFILES are referenced from the database semantics, and are also
known as External LOBs.
Binary Large Object (BLOB)
A Large Object datatype whose content consists of binary data. Additionally, this
data is considered raw as its structure is not recognized by the database.
BLOB
See Binary Large Object.
Business-to-Business (B2B)
A term describing the communication between businesses in the selling of goods
and services to each other. The software infrastructure to enable this is referred to as
an exchange.
Business-to-Consumer (B2C)
A term describing the communication between businesses and consumers in the
selling of goods and services.
callback
A programmatic technique in which one process starts another and then continues.
The second process then calls the rst as a result of an action, value, or other event.
This technique is used in most programs that have a user interface to allow
continuous interaction.
Glossary-3
cartridge
A stored program in Java or PL/SQL that adds the necessary functionality for the
database to understand and manipulate a new datatype. Cartridges interface
through the Extensibility Framework within Oracle8 or later. Oracle Text is such a
cartridge, adding support for reading, writing, and searching text documents stored
within the database.
Cascading Style Sheets
A simple mechanism for adding style (fonts, colors, spacing, and so on) to Web
documents.
CDATA
See character data.
CDF
Channel Denition Format. Provides a way to exchange information about channels
on the internet.
CGI
See Common Gateway Interface.
character data (CDATA)
Text in a document that should not be parsed is put within a CDATA section. This
allows for the inclusion of characters that would otherwise have special functions,
such as &, <, >, and so on. CDATA sections can be used in the content of an element
or in attributes.
child element
An element that is wholly contained within another, which is referred to as its
parent element. For example <Parent><Child></Child></Parent> illustrates a
child element nested within its parent element.
Class Generator
A utility that accepts an input le and creates a set of output classes that have
corresponding functionality. In the case of the XML Class Generator, the input le is
a DTD and the output is a series of classes that can be used to create XML
documents conforming with the DTD.
Glossary-4
CLASSPATH
The operating systemenvironmental variable that the JVMuses to nd the classes it
needs to run applications.
client/server
The term used to describe the application architecture where the actual application
runs on the client but accesses data or other external processes on a server across a
network.
Character Large Object (CLOB)
The LOB datatype whose value is composed of character data corresponding to the
database character set. A CLOB may be indexed and searched by the Oracle Text
search engine.
CLOB
See Character Large Object.
command line
The interface method in which the user enters in commands at the command
interpreters prompt.
Common Gateway Interface (CGI)
The programming interfaces enabling Web servers to execute other programs and
pass their output to HTML pages, graphics, audio, and video sent to browsers.
Common Object Request Broker API (CORBA)
An Object Management Group standard for communicating between distributed
objects across a network. These self-contained software modules can be used by
applications running on different platforms or operating systems. CORBA objects
and their data formats and functions are dened in the Interface Denition
Language (IDL), which can be compiled in a variety of languages including Java, C,
C++, Smalltalk and COBOL.
Common Oracle Runtime Environment (CORE)
The library of functions written in C that provides developers the ability to create
code that can be easily ported to virtually any platform and operating system.
Content
The body of a resource in Oracle XML DB and what you get when you treat the
resource like a le and ask for its contents. Content is always an XMLType.
Glossary-5
CORBA
See Common Object Request Broker API.
CSS
See Cascading Style Sheets.
Database Access Descriptor (DAD)
A DAD is a named set of conguration values used for database access. A DAD
species information such as the database name or the Oracle Net service name, the
ORACLE_HOME directory, and Globalization Support conguration information
such as language, sort type, and date language.
datagram
A text fragment, which may be in XML format, that is returned to the requester
embedded in an HTML page from a SQL query processed by the XSQL Servlet.
DBURITYPE
The Oracle9i datatype used for storing instances of the datatype that permits
XPath-based navigation of database schemas.
DOCTYPE
The term used as the tag name designating the DTD or its reference within an XML
document. For example, <!DOCTYPE person SYSTEM "person.dtd"> declares
the root element name as person and an external DTD as person.dtd in the le
system. Internal DTDs are declared within the DOCTYPE declaration.
Document Object Model (DOM)
An in-memory tree-based object representation of an XML document that enables
programmatic access to its elements and attributes. The DOM object and its
interface is a W3C recommendation. It species the Document Object Model of an
XML Document including the APIs for programmatic access. DOM views the
parsed document as a tree of objects.
Document Type Denition (DTD)
A set of rules that dene the allowable structure of an XML document. DTDs are
text les that derive their format from SGML and can either be included in an XML
document by using the DOCTYPE element or by using an external le through a
DOCTYPE reference.
Glossary-6
DOM
See Document Object Model.
DOM delity
To assure the integrity and accuracy of this data, for example, when regenerating
XML documents stored in Oracle XML DB, Oracle XML DB uses a data integrity
mechanism, called DOM delity. DOM delity refers to when the returned XML
documents are identical to the original XML document, particularly for purposes of
DOM traversals. Oracle XML DB assures DOM delity by using a binary attribute,
SYS_XDBPD$.
DTD
See Document Type Denition.
EDI
Electronic Data Interchange.
element
The basic logical unit of an XML document that can serve as a container for other
elements such as children, data, and attributes and their values. Elements are
identied by start-tags, such as <name>, and end-tags, such as </name>, or in the
case of empty elements, <name/>.
empty element
An element without text content or child elements. It can only contain attributes
and their values. Empty elements are of the form<name/> or <name></name>,
where there is no space between the tags.
Enterprise Java Bean
An independent program module that runs within a JVM on the server. CORBA
provides the infrastructure for Enterprise Java Beans, and a container layer provides
security, transaction support, and other common functions on any supported server.
entity
A string of characters that may represent either another string of characters or
special characters that are not part of the documents character set. Entities and the
text that is substituted for them by the parser are declared in the DTD.
Glossary-7
existnode
The SQL operator that returns a TRUE or FALSE based upon the existence of an
XPath within an XMLType.
eXtensible Markup Language (XML)
An open standard for describing data developed by the World Wide Web
Consortium (W3C) using a subset of the SGML syntax and designed for Internet
use.
eXtensible Stylesheet Language Formatting Object (XSLFO)
The W3C standard specication that denes an XML vocabulary for specifying
formatting semantics. See FOP.
eXtensible Stylesheet Language Transformation (XSLT)
Also written as XSL-T. The XSL W3C standard specication that denes a
transformation language to convert one XML document into another.
eXtensible Stylesheet Language (XSL)
The language used within stylesheets to transform or render XML documents.
There are two W3C recommendations covering XSL stylesheetsXSL
Transformations (XSLT) and XSL Formatting Objects (XSLFO).
(W3C) eXtensible Stylesheet Language. XSL consists of two W3C recommendations:
XSL Transformations for transforming one XML document into another and XSL
Formatting Objects for specifying the presentation of an XML document. XSL is a
language for expressing stylesheets. It consists of two parts:
I A language for transforming XML documents (XSLT), and
I An XML vocabulary for specifying formatting semantics (XSLFO).
An XSL stylesheet species the presentation of a class of XML documents by
describing how an instance of the class is transformed into an XML document that
uses the formatting vocabulary.
extract
The SQL operator that retrieves fragments of XML documents stored as XMLType.
Folder
A directory or node in the Oracle XML DB repository that contains or can contain a
resource. A folder is also a resource.
Glossary-8
Foldering
A feature in Oracle XML DB that allows content to be stored in a hierarchical
structure of resources.
FOP
Print formatter driven by XSL formatting objects. It is a Java application that reads a
formatting object tree and then renders the resulting pages to a specied output.
Output formats currently supported are PDF, PCL, PS, SVG, XML (area tree
representation), Print, AWT, MIF and TXT. The primary output target is PDF.
function-based index
A database index that, when created, permits the results of known queries to be
returned much more quickly.
HASPATH
The SQL operator that is part of Oracle Text and used for querying XMLType
datatypes for the existence of a specic XPath.
hierarchical indexing
The data relating a folder to its children is managed by the Oracle XML DB
hierarchical index, which provides a fast mechanism for evaluating path names
similar to the directory mechanisms used by operating system lesystems. Any
path name-based access will normally use the Oracle XML DB hierarchical index.
HTML
See Hypertext Markup Language.
HTTP
See Hypertext Transport Protocol.
HTTPURITYPE
The datatype used for storing instances of the datatype that permits XPath-based
navigation of database schemas in remote databases.
hypertext
The method of creating and publishing text documents in which users can navigate
between other documents or graphics by selecting words or phrases designated as
hyperlinks.
Glossary-9
Hypertext Markup Language (HTML)
The markup language used to create the les sent to Web browsers and that serves
as the basis of the World Wide Web. The next version of HTML will be called
xHTML and will be an XML application.
Hypertext Transport Protocol (HTTP)
The protocol used for transporting HTML les across the Internet between Web
servers and browsers.
iAS
See Oracle9iAS.
IDE
See Integrated Development Environment.
INPATH
The SQL operator that is part of Oracle Text and is used for querying XMLType
datatypes for searching for specic text within a specic XPath.
instantiate
A term used in object-based languages such as Java and C++ to refer to the creation
of an object of a specic class.
Integrated Development Environment (IDE)
A set of programs designed to aide in the development of software run from a
single user interface. JDeveloper is an IDE for Java development as it includes an
editor, compiler, debugger, syntax checker, help system, and so on, to permit Java
software development through a single user interface.
interMedia
The collection of complex datatypes and their access in Oracle. These include text,
video, time-series, and spatial data.
Internet Inter-ORB Protocol (IIOP)
The protocol used by CORBA to exchange messages on a TCP/IP network such as
the Internet.
J2EE
See Java 2 Platform, Enterprise Edition.
Glossary-10
Java
A high-level programming language developed and maintained by Sun
Microsystems where applications run in a virtual machine known as a JVM. The
JVM is responsible for all interfaces to the operating system. This architecture
permits developers to create Java applications and applets that can run on any
operating system or platform that has a JVM.
Java 2 Platform, Enterprise Edition (J2EE)
The Java platform (Sun Microsystems) that denes multitier enterprise computing.
Java API for XML Processing (JAXP)
Enables applications to parse and transform XML documents using an API that is
independent of a particular XML processor implementation.
JavaBean
An independent program module that runs within a JVM, typically for creating
user interfaces on the client. Also known as Java Bean. The server equivalent is
called an Enterprise JavaBean. See also Enterprise JavaBean.
Java Database Connectivity (JDBC)
The programming API that enables Java applications to access a database through
the SQL language. JDBC drivers are written in Java for platform independence but
are specic to each database.
Java Developers Kit (JDK)
The collection of Java classes, runtime, compiler, debugger, and usually source code
for a version of Java that makes up a Java development environment. JDKs are
designated by versions, and Java 2 is used to designate versions from 1.2 onward.
Java Naming and Directory Interface
A programming interface from Sun for connecting Java programs to naming and
directory services such as DNS, LDAP and NDS. Oracle XML DB Resource API for
Java/JNDI supports JNDI.
Java Runtime Environment (JRE)
The collection of complied classes that make up the Java virtual machine on a
platform. JREs are designated by versions, and Java 2 is used to designate versions
from 1.2 onward.
Glossary-11
Java Server Page (JSP)
An extension to the servlet functionality that enables a simple programmatic
interface to Web pages. JSPs are HTML pages with special tags and embedded Java
code that is executed on the Web server or application server providing dynamic
functionality to HTML pages. JSPs are actually compiled into servlets when rst
requested and run in the servers JVM.
Java Virtual Machine (JVM)
The Java interpreter that converts the compiled Java bytecode into the machine
language of the platform and runs it. JVMs can run on a client, in a browser, in a
middle tier, on an intranet, on an application server such as Oracle9iAS, or in a
database server such as Oracle.
JAXP
See Java API for XML Processing.
JDBC
See Java Database Connectivity.
JDeveloper
Oracles Java IDE that enables application, applet, and servlet development and
includes an editor, compiler, debugger, syntax checker, help system, an integrated
UML class modeler, and so on. JDeveloper has been enhanced to support
XML-based development by including the Oracle XDK for Java, integrated for easy
use along with XML support, in its editor.
JDK
See Java Developers Kit.
JNDI
JServer
The Java Virtual Machine that runs within the memory space of the Oracle
database. In Oracle8i Release 1 the JVM was Java 1.1 compatible while Release 2 is
Java 1.2 compatible.
JVM
See Java virtual machine.
Glossary-12
LAN
See local area network.
Large Object (LOB)
The class of SQL data type that is further divided into Internal LOBs and External
LOBs. Internal LOBs include BLOBs, CLOBS, and NCLOBs while External LOBs
include BFILES. See also BFILES, Binary Large Object, Character Large Object.
lazy type conversions
A mechanism used by Oracle XML DB to only convert the XML data for Java when
the Java application rst asks for it. This saves typical type conversion bottlenecks
with JDBC.
listener
A separate application process that monitors the input process.
LOB
See Large Object.
local area network (LAN)
A computer communication network that serves users within a restricted
geographical area. LANs consist of servers, workstations, communications
hardware (routers, bridges, network cards, and so on) and a network operating
system.
name-level locking
Oracle XML DB provides for name-level locking rather than collection-level locking.
When a name is added to a collection, an exclusive write lock is not placed on the
collection, only that name within the collection is locked. The name modication is
put on a queue, and the collection is locked and modied only at commit time.
namespace
The term to describe a set of related element names or attributes within an XML
document. The namespace syntax and its usage is dened by a W3C
Recommendation. For example, the <xsl:apply-templates/ > element is identied as
part of the XSL namespace. Namespaces are declared in the XML document or DTD
before they are used be using the following attribute syntax:
xmlns:xsl="http://www.w3.org/TR/WD-xsl".
Glossary-13
national Character Large Object (NCLOB)
The LOB datatype whose value is composed of character data corresponding to the
database national character set.
NCLOB
See National Character Large Object.
node
In XML, the term used to denote each addressable entity in the DOM tree.
Notation Attribute Declaration
In XML, the declaration of a content type that is not part of those understood by the
parser. These types include audio, video, and other multimedia.
N-tier
The designation for a computer communication network architecture that consists
of one or more tiers made up of clients and servers. Typically two-tier systems are
made up of one client level and one server level. A three-tier system utilizes two
server tiers, typically a database server as one and a Web or application server along
with a client tier.
OAG
Open Applications Group.
OAI
Oracle Applications Integrator. Runtime with Oracle iStudio development tool that
provides a way for CRM applications to integrate with other ERP systems besides
Oracle ERP. Specic APIs must be "message-enabled." It uses standard extensibility
hooks to generate or parse XML streams exchanged with other application systems.
In development.
OASIS
See Organization for the Advancement of Structured Information.
object-relational
The termto describe a relational database systemthat can also store and manipulate
higher-order data types, such as text documents, audio, video les, and
user-dened objects.
Glossary-14
Object Request Broker (ORB)
Software that manages message communication between requesting programs on
clients and between objects on servers. ORBs pass the action request and its
parameters to the object and return the results back. Common implementations are
JCORB and Enterprise Bean. See also CORBA.
Object View
A tailored presentation of the data contained in one or more object tables or other
views. The output of an Object View query is treated as a table. Object Views can be
used in most places where a table is used.
OC4J
Oracle9iAS Containers for J2EE, a J2EE deployment tool that comes with
JDeveloper.
OCT
See Ordered Collection in Tables.
OE
Oracle Exchange.
OIS
See Oracle Integration Server.
Oracle9iAS (iAS)
The Oracle application server that integrates all the core services and features
required for building, deploying, and managing high-performance, n-tier,
transaction-oriented Web applications within an open standards framework.
Oracle9iFS
The Oracle le system and Java-based development environment that either runs
inside the database or on a middle tier and provides a means of creating, storing,
and managing multiple types of documents in a single database repository.
ORACLE_HOME
The operating system environmental variable that identies the location of the
Oracle database installation for use by applications.
Glossary-15
Ordered Collection in Tables (OCT)
When elements of a VARRAY are stored in a separate table, they are referred to as
an Ordered Collection in Tables.
Oracle Text
An Oracle tool that provides full-text indexing of documents and the capability to
do SQL queries over documents, along with XPath-like searching.
Oracle XML DB
A high-performance XML storage and retrieval technology provided with Oracle
database server. It is based on the W3C XML data model.
ORB
See Object Request Broker.
Organization for the Advancement of Structured Information (OASIS)
An organization of members chartered with promoting public information
standards through conferences, seminars, exhibits, and other educational events.
XML is a standard that OASIS is actively promoting as it is doing with SGML.
parent element
An element that surrounds another element, which is referred to as its child
element. For example, <Parent><Child></Child></Parent> illustrates a parent
element wrapping its child element.
Parsed Character Data (PCDATA)
The element content consisting of text that should be parsed but is not part of a tag
or nonparsed data.
parser
In XML, a software program that accepts as input an XML document and
determines whether it is well-formed and, optionally, valid. The Oracle XML Parser
supports both SAX and DOM interfaces.
path name
The name of a resource that reects its location in the repository hierarchy. A path
name is composed of a root element (the rst /), element separators (/) and various
sub-elements (or path elements). A path element may be composed of any character
in the database character set except ("\", "/" ). These characters have a special
Glossary-16
meaning for Oracle XML DB. Forward slash is the default name separator in a path
name and backward slash may be used to escape characters.
PCDATA
See Parsed Character Data.
PDA
Personal Digital Assistant, such as a Palm Pilot.
PL/SQL
The Oracle procedural database language that extends SQL. It is used to create
programs that can be run within the database.
principal
An entity that may be granted access control privileges to an Oracle XML DB
resource. Oracle XML DB supports as principals:
I Database users.
I Database roles. A database role can be understood as a group, for example, the
DBA role represents the DBA group of all the users granted the DBA role.
Users and roles imported from an LDAP server are also supported as a part of the
database's general authentication model.
prolog
The opening part of an XML document containing the XML declaration and any
DTD or other declarations needed to process the document.
PUBLIC
The term used to specify the location on the Internet of the reference that follows.
RDF
Resource Denition Framework.
renderer
A software processor that outputs a document in a specied format.
Glossary-17
repository
The set of database objects, in any schema, that are mapped to path names. There is
one root to the repository ("/") which contains a set of resources, each with a path
name.
resource
An object in the repository hierarchy.
resource name
The name of a resource within its parent folder. Resource names must be unique
(potentially subject to case-insensitivity) within a folder. Resource names are always
in the UTF8 character set (NVARCHAR).
result set
The output of a SQL query consisting of one or more rows of data.
root element
The element that encloses all the other elements in an XML document and is
between the optional prolog and epilog. An XML document is only permitted to
have one root element.
SAX
See Simple API for XML.
schema
The denition of the structure and data types within a database. It can also be used
to refer to an XML document that support the XML Schema W3C recommendation.
Secure Sockets Layer (SSL)
The primary security protocol on the Internet; it utilizes a public key /private key
form of encryption between browsers and servers.
Server-Side Include (SSI)
The HTML command used to place data or other content into a Web page before
sending it to the requesting browser.
servlet
A Java application that runs in a server, typically a Web or application server, and
performs processing on that server. Servlets are the Java equivalent to CGI scripts.
Glossary-18
session
The active connection between two tiers.
SGML
See Structured Generalized Markup Language.
Simple API for XML (SAX)
An XML standard interface provided by XML parsers and used by event-based
applications.
Simple Object Access Protocol (SOAP)
An XML-based protocol for exchanging information in a decentralized, distributed
environment.
SOAP
See Simple Object Access Protocol.
SQL
See Structured Query Language.
SSI
See Server-Side Include.
SSL
See Secure Sockets Layer.
Structured Generalized Markup Language (SGML)
An ISO standard for dening the format of a text document implemented using
markup and DTDs.
Structured Query Language (SQL)
The standard language used to access and process data in a relational database.
Stylesheet
In XML, the term used to describe an XML document that consists of XSL
processing instructions used by an XSL processor to transform or format an input
XML document into an output one.
Glossary-19
SYSTEM
Species the location on the host operating system of the reference that follows.
SYS_XMLAGG
The term used to specify the location on the host operating system of the reference
that follows.
SYS_XMLGEN
The native SQL function that returns as an XML document the results of a passed-in
SQKL query. This can also be used to instantiate an XMLType.
tag
A single piece of XML markup that delimits the start or end of an element. Tags
start with < and end with >. In XML, there are start-tags (<name>), end-tags
(</name>), and empty tags (<name/>).
TCP/IP
See Transmission Control Protocol/Internet Protocol.
thread
In programming, a single message or process execution path within an operating
system that supports concurrent execution (multithreading).
Transmission Control Protocol/Internet Protocol (TCP/IP)
The communications network protocol that consists of the TCP which controls the
transport functions and IP which provides the routing mechanism. It is the standard
for Internet communications.
Transviewer
The Oracle term used to describe the Oracle XML JavaBeans included in the XDK
for Java.
TransXUtility
TransXUtility is a Java API that simplies the loading of translated seed data and
messages into a database.
UDDI
See Universal Description, Discovery and Integration.
Glossary-20
UIX
See User Interface XML.
Uniform Resource Identier (URI)
The address syntax that is used to create URLs and XPaths.
Uniform Resource Locator (URL)
The address that denes the location and route to a le on the Internet. URLs are
used by browsers to navigate the World Wide Web and consist of a protocol prex,
port number, domain name, directory and subdirectory names, and the le name.
For example http://technet.oracle.com:80/tech/xml/index.htm species the
location and path a browser will travel to nd OTNs XML site on the World Wide
Web.
Universal Description, Discovery and Integration (UDDI)
This specication provides a platform-independent framework using XML to
describe services, discover businesses, and integrate business services on the
Internet.
URI
See Uniform Resource Identier.
URL
See Uniform Resource Locator.
user interface (UI)
The combination of menus, screens, keyboard commands, mouse clicks, and
command language that denes how a user interacts with a software application.
User Interface XML (UIX)
A set of technologies that constitute a framework for building web applications.
valid
The term used to refer to an XML document when its structure and element content
is consistent with that declared in its referenced or included DTD.
W3C
See World Wide Web Consortium (W3C).
Glossary-21
WAN
See wide area network.
WebDAV
See World Wide Web distributed authoring and versioning.
Web Request Broker
The cartridge within OAS that processes URLs and sends them to the appropriate
cartridge.
Web Services Description Language (WSDL)
A general purpose XML language for describing the interface, protocol bindings,
and deployment details of Web services.
well-formed
The termused to refer to an XML document that conforms to the syntax of the XML
version declared in its XML declaration. This includes having a single root element,
properly nested tags, and so forth.
wide area network (WAN)
A computer communication network that serves users within a wide geographic
area, such as a state or country. WANs consist of servers, workstations,
communications hardware (routers, bridges, network cards, and so on), and a
network operating system.
Working Group (WG)
The committee within the W3C that is made up of industry members that
implement the recommendation process in specic Internet technology areas.
World Wide Web Consortium (W3C)
An international industry consortium started in 1994 to develop standards for the
World Wide Web. It is located at www.w3c.org.
World Wide Web Distributed Authoring and Versioning (WebDAV)
The Internet Engineering Task Force (IETF) standard for collaborative authoring on
the Web. Oracle XML DB Foldering and Security features are WebDAV-compliant.
Glossary-22
Wrapper
The term describing a data structure or software that wraps around other data or
software, typically to provide a generic or object interface.
WSDL
See Web Services Description Language.
XDBbinary
An XML element dened by the Oracle XML DB schema that contains binary data.
XDBbinary elements are stored in the repository when completely unstructured
binary data is uploaded into Oracle XML DB.
XDK
See XML Developers Kit.
XLink
The XML Linking language consisting of the rules governing the use of hyperlinks
in XML documents. These rules are being developed by the XML Linking Group
under the W3C recommendation process. This is one of the three languages XML
supports to manage document presentation and hyperlinks (XLink, XPointer, and
XPath).
XML
See eXtensible Markup Language.
XML Developers Kits (XDKs)
The set of libraries, components, and utilities that provide software developers with
the standards-based functionality to XML-enable their applications. In the case of
the Oracle XDK for Java, the kit contains an XML parser, an XSLT processor, the
XML Class Generator, the Transviewer JavaBeans, and the XSQL Servlet.
XML Gateway
A set of services that allows for easy integration with the Oracle e-Business Suite to
create and consume XML messages triggered by business events.
XML Query
The W3Cs effort to create a standard for the language and syntax to query XML
documents.
Glossary-23
XML Schema
The W3Cs effort to create a standard to express simple data types and complex
structures within an XML document. It addresses areas currently lacking in DTDs,
including the denition and validation of data types. Oracle XML Schema Processor
automatically ensures validity of XML documents and data used in e-business
applications, including online exchanges. It adds simple and complex datatypes to
XML documents and replaces DTD functionality with an XML Schema denition
XML document.
XMLType
An XMLType column stores XML data using an underlying CLOB column in the
database.
XMLType views
Oracle XML DB provides a way to wrap existing relational and object-relational
data in XML format. This is especially useful if, for example, your legacy data is not
in XML but you need to migrate it to an XML format.
XPath
The open standard syntax for addressing elements within a document used by XSL
and XPointer. XPath is currently a W3C recommendation. It species the data
model and grammar for navigating an XML document utilized by XSLT, XLink and
XML Query.
XPointer
The term and W3C recommendation to describe a reference to an XML document
fragment. An XPointer can be used at the end of an XPath-formatted URI. It
species the identication of individual entities or fragments within an XML
document using XPath navigation.
XSL
See eXtensible Stylesheet Language.
XSLFO
See eXtensible Stylesheet Language Formatting Object.
XSLT
See eXtensible Stylesheet Language Transformation.
Glossary-24
XSQL
The designation used by the Oracle Servlet providing the ability to produce
dynamic XML documents from one or more SQL queries and optionally transform
the document in the server using an XSL stylesheet.
Index-1
Index
A
access control entries (ACEs), 18-10
elements in, 18-6
access control lists (ACLs), 18-2
bootstrap, 18-4
concurrency resolution, 18-5
default, 18-4
defined, 13-5
features, 18-5
managing, 18-12
managing from Enterprise Manager, 21-22
restrictions, 18-13
security, row-level, 18-14
setting the resource property, 18-12
summary, 1-11
term explained, 1-29
updating, 18-11
using, 18-10
accessing
using XDBUriType, 3-44
with JDBC, 9-3
XML documents using Java, 9-2
adding
XMLType columns, 4-8
Advanced Queuing (AQ)
definition, 24-2
enqueuing, 24-10
hub-and-spoke architecture support, 24-4
IDAP, 24-7
message management support, 24-4
messaging scenarios, 24-2
point-to-point support, 24-2
publish/subscribe support, 24-2
XML servlet, 24-13
XMLType queue payloads, 24-8
aggregating
XSQL and XMLAgg, 10-52
ALTER INDEX, using sections, 7-10
any, 13-6
attributes
collection, 5-37
columnProps, 5-70
Container, 13-7
defaultTable, 5-70
for root element, 3-21
in elements, 5-25
maintainDOM, 5-22
maintainOrder, 5-37
mapping any, 5-45
maxOccurs, 5-37
namespaces, 5-5
noNameSpaceSchemaLocation, 3-22
of XMLFormat, 10-44
passing to SYS_DBURIGEN, 12-30
REF, 5-38, 5-47
schemaLocation, 3-22, 5-10
setting to NULL, 4-36
SQLInLine, 5-37, 5-38
SQLName, 5-24
SQLSchema, 5-24
SQLType, 5-24, 5-28, 5-39
storeVarrayAsTable, 5-71
SYS_XDBPD$, 5-57
tableProps, 5-70
xdb.defaultTable, 3-40
xdb.SQLType, 3-31
XMLAttributes in XMLElement, 10-7
Index-2
XMLDATA, 4-13, 5-50
XMLType, in AQ, 24-8
xsi.NamespaceSchemaLocation, 5-5
xsi.noNamespaceSchemaLocation, 11-9
authenticatedUser
DBuri security, 12-37
AUTO_SECTION_GROUP
using, 7-10
B
B*Tree, 1-11, 4-6, 5-51
indexing, 3-26
bootstrap ACL, 18-4
C
CASCADE mode, 5-14
cascading style sheets, see CSS, D-5
catalog views, F-19
cfg_get, 16-9, A-14
cfg_refresh, A-15
character sets
importing and exporting XML data, 23-6
Korean, 3-4
CharacterData, 8-23
CLOB storage of XMLType, 4-5
collection attribute, 5-37
collection index, 5-60
collections, 3-32, 18-6
columnProps attribute, 5-70
complexType
collections, 3-32
cycling, 5-48
cycling between, 5-46
elements, B-3
handling inheritance, 5-41
in XML schema, explained, B-35
mapping any and any attributes, 5-45
mapping to SQL, 5-37
restrictions, 5-41
concatenating
elements using XMLConcat, 10-16
configuring
API, A-14
protocol server in Oracle XML DB, 19-4
servlet, example, 20-12
servlets in Oracle XML DB, 20-4
using Enterprise Manager, 21-7
constraints
on XMLType columns, 5-51
structured storage, 3-33
using with XMLType tables, 3-23
CONTAINS, 4-39, 7-6
compared against existsNode, 7-38
compared to existsNode(),extract(), 4-42
contents, element, 13-6
CREATE TABLE
XMLType storage, 5-50
createFolder(), 16-3
createXML
inserting with CLOB, example, 4-15
inserting with string, 4-16
summarized, 3-17
creating
XML schema-based tables, columns, 5-22
XMLType columns, 4-8
XMLType table, 4-7
CSS and XSL, D-5
CTX_DDL.Add_Field_Section, 7-26
CTXAPP
role, 7-6
CTXSYS.PATH_SECTION_GROUP, 7-36
CTXXPATH, 4-41
indexes, 7-45
storage preferences, 7-47
cycling in complexTypes
self-referencing, 5-48
D
data integrity
in structured, unstructured storage, 3-27
Oracle XML DB, 3-33
date
format conversion in updateXML(), 5-70
format conversions for XML, 5-62
mapping to SQL, 5-35
DBMS_METADATA, 12-5
DBMS_XDB, F-20
Index-3
AclCheckPrivileges, database objects, 18-13
cfg_get, A-14
cfg_refresh, A-15
changePrivilege, 18-13
checkPrivileges, 18-13
configuration management, 16-8
getAclDocument, 18-13
Link, 16-2
LockResource, 16-2
overview, 16-2
rebuilding hierarchical index, 16-11
security, 16-5
DBMS_XDB_VERSION, 14-2, F-25
subprograms, 14-9
DBMS_XDBT, F-27
DBMS_XMLDOM, 8-5, 8-11, F-6
DBMS_XMLGEN, 10-21, F-23
generating complex XML, 10-30
generating XML, 10-2
DBMS_XMLPARSER, 8-26, F-14
DBMS_XMLSCHEMA, 5-8, F-16
deleteSchema, 5-8
generateSchema() function, 5-17
generateSchemas() function, 5-17
mapping of types, 5-31
registerSchema, 5-8
DBMS_XSLPROCESSOR, 8-30, F-15
dbmsxsch.sql, F-16
DBUri, 12-10
and object references, 12-18
identifying a row, 12-16
identifying a target column, 12-16
retrieving column text value, 12-17
retrieving the whole table, 12-15
security, 12-37
servlet, 12-34
servlet, installation, 12-36
syntax guidelines, 12-13
URL specification, 12-13
XPath expressions in, 12-14
DBUri-refs, 12-10
HTTP access, 12-34
where it can be used, 12-18
DBUriType
defined, 12-2
examples, 12-25
notation for fragments, 12-13
stores references to data, 12-6
default table
creating, 5-70
defining a, 3-40
defaultTable attribute, 5-70
deleting
resources, 3-39, 15-13
rows using extract(), 4-38
rows with XMLType columns, 4-38
using extract(), 4-38
XML schema using DBMS_XMLSCHEMA, 5-13
DEPTH, 15-11
dequeuing
with AQ XML servlet, 24-13
document
fidelity, explained, 1-4
no order, 5-64
no order with extract(), 5-68
order, 5-62
order with extract(), 5-67
order, query rewrites with collection, 5-60
ordering preserved in mapping, 5-68
DOM
differences, and SAX, 8-6
explained, 1-27
fidelity, 5-21
fidelity, default, 5-56
fidelity, in structured storage, 4-5
fidelity, structured or unstructured
storage, 3-27
fidelity, summarized, 1-4
fidelity, SYS_XDBPD$, 5-21
introduced, 8-5
Java API, 9-2
Java API features, 9-15
Java API, XMLType classes, 9-17
NodeList, 8-22
non-supported, 8-5
DOM API for PL/SQL, 8-5
DOMDocument, 9-18
dropping
XMLType columns, 4-9
DTD
Index-4
limitations, B-33
E
elementFormDefault, 5-61
elements
access control entries (ACEs), 18-6
any, 13-6
complexType, B-3
Contents, Resource index, 13-6
simpleType, B-3
XDBBinary, 13-11
XML, 8-4
enqueuing
adding new recipients after, 24-15
using AQ XML servlet, 24-10
EQUALS_PATH
summary, 15-6
syntax, 15-9
existsNode
and CONTAINS, querying, 7-38
dequeing messages, 2-10
finding XML elements, nodes, 4-20
indexing with CTXXPATH, 7-45
query rewrite, 5-51
XPath rewrites, 5-62
exporting XML table, 23-3
extract, 5-67
deleting, 4-38
dequeing messages, 2-10
mapping, 5-68
query rewrite, 5-51
querying XMLType, 4-26
rewrite in XPath expressions, 5-67
extracting
data from XML, 4-27
extractValue, 4-24
creating indexes, query rewrite, 5-66
query rewrite, 5-51
rewrites in XPath expressions, 5-65
F
factory method, 12-26
folder, defined, 13-4
foldering
explained, 13-2
summary, 1-11
FORCE mode option, 5-14
Frequently Asked Questions (FAQs)
AQ and XML, 24-14
Oracle Text, 7-65
versioning, 14-12
FTP
configuration parameters, Oracle XMl DB, 19-5
creating default tables, 5-70
protocol server, features, 19-7
protocol server, using, 3-45
function-based index
creating in Enterprise Manager, 21-42
creating on extract or existsNode, 4-39
functions
createXML, 4-15
DBUriType, 12-19
isSchemaValid, 6-10
isSchemaValidated, 6-9
schemaValidate, 6-9
setSchemaValidated, 6-10
SYS_DBURIGEN, 12-29
SYS_XMLAgg, 10-51
SYS_XMLGEN, 10-42
transform, 6-2
updateXML, 5-69
XMLAgg, 10-17
XMLColAttVal, 10-20
XMLConcat, 10-15
XMLElement, 10-5
XMLForest, 10-9
XMLSequence, 10-11, 10-13
XMLTransform, 6-2
XMLType, 4-7
G
generating
DBUriType using SYS_DBURIGEN, 12-29
generating XML
DBMS_XMLGEN example, 10-30
element forest
XMLColAttVal, 10-20
Index-5
from SQL, DBMS_XMLGEN, 10-21
one document from another, 10-12
SQL, SYS_XMLGEN, 10-42
SYS_XMLAgg, 10-51
using SQL functions, 10-2
XML SQL Utility (XSU), 10-54
XMLAgg, 10-17
XMLConcat, 10-15
XMLElement, 10-5
XMLForest, 10-9
XMLSequence, 10-11
XSQL, 10-52
getClobVal
summarized, 3-18
getNameSpace
summarized, 3-18
getRootElement
summarized, 3-18
getXMLType, 9-17
global XML schema, 5-12
groups, 18-6
H
HASPATH, 4-40, 7-10
operator, 7-12
path existence searching, 7-20
path searching, 7-19
highlighting
XML documents with Oracle Text, 7-49
HTTP
access for DBUri-refs, 12-34
accessing Java servlet or XMLType, 20-3
accessing Repository resources, 13-11
configuration parameters, WebDAV, 19-5
creating default tables, 5-70
HttpUriType, DBUriType, 12-23
improved performance, 19-2
Oracle XML DB servlets, 20-8
protocol server, features, 19-9
requests, 20-8
servlets, 20-4
UriFactory, 12-38
using UriRefs to store pointers, 12-7
HttpUriType
accesses remote pages, 12-6
defined, 12-2
hub-and-spoke architecture, enabled by AQ, 24-4
I
IDAP
architecture, 24-7
transmitted over Internet, 24-7
XML schema, 24-14
IMPORT/EXPORT
in XML DB, 23-2
index
collection, 5-60
Index Organized Table (IOT), 5-71
indexing
B*Tree, 3-26
function-based on existsNode(), 4-39
in structured, unstructured storage, 3-26
Oracle Text, CTXXPATH, 7-45
Oracle Text, XMLType, 7-35
XMLType, 4-39
Information Set
W3C introducing XML, C-26
inheritance
in XML schema, restrictions in
complexTypes, 5-43
INPATH, 4-40, 7-10
operator, 7-13
INPATH operator, 7-12
inserting
into XMLType, 4-9
new instances, 5-51
XML data into XMLType columns, 4-15
installing
from scratch, Oracle XML DB, A-2
manually without DBCA, A-4
instance document
specifying root element namespace, 5-5
XML, described, B-36
Internet Data Access Presentation (IDAP)
SOAP specification for AQ, 24-7
isFragment
summarized, 3-18
isSchemaValid, 6-10
Index-6
isSchemaValidated, 6-9
J
Java
Oracle XML DB guidelines, 20-3
using JDBC to access XMLType objects, 20-3
writing Oracle XML DB applications, 20-2
Java DOM API for XMLType, E-2
JDBC
accessing documents, 9-3
manipulating data, 9-5
using SQL to determine object properties, 17-3
JNDI, 9-2
using Resource API, 17-2
L
lazy manifestation, 8-4
Lazy Manifestation (LM), 3-26
LDAP
Oracle XML DB, in, 18-5
Least Recently Used (LRU), 3-26
Link, 16-2
LOBs
mapping XML fragments to, 5-39
location path, C-5
LockResource, 16-2
M
maintainDOM, 5-64
maintainOrder attribute, 5-37
mapping
collection predicates, 5-59
complexType any, 5-45
complexTypes to SQL, 5-37
overriding using SQLType attribute, 5-32
predicates, 5-58
scalar nodes, 5-58
simpleContent to object types, 5-44
simpleType XML string to VARCHAR2, 5-36
simpleTypes, 5-33
type, setting element, 5-31
maxOccurs, 5-37
MIME
overriding with DBUri servlet, 12-35
modes
CASCADE, 5-14
FORCE, 5-14
MULTISET operator
using with SYS_XMLGEN selects, 10-47
N
NamedNodeMap object, 8-22
namespace
defining, 3-29
handling in query rewrites, 5-61
handling in XPath, 5-61
W3C introducing, C-18
XDBResource, 13-17
XML schema URL, 5-5
xmlns, D-4
XMLSchema-Instance, 3-21
naming SQL objects
SQLName, SQLType attributes, 5-24
navigational access, 13-9
nested
generating nested XML using DBMS_
XMLGEN, 10-32
object tables, 3-32
sections in Oracle Text, 7-55
XML, generating with XMLElement, 10-7
XMLAgg functions and XSQL, 10-52
newDOMDocument, 8-22
NodeList object, 8-22
NULL
mapping to in XPath, 5-60
O
object references and DBUri, 12-18
operators
CONTAINS, 4-39, 7-6
CONTAINS compared, 4-42
DEPTH, 15-11
EQUALS_PATH, 15-9
HASPATH, 7-12
INPATH, 7-12, 7-13
Index-7
MULTISET and SYS_XMLGEN, 10-47
PATH, 15-9
UNDER_PATH, 15-7
WITHIN, 7-8, 7-11
XMLIsValid, 6-9
Oracle Enterprise Manager
configuring Oracle XML DB, 21-7
console, 21-7
creating a view based on XML schema, 21-39
creating function-based index, 21-42
creating resources, 21-12
features, 21-3
granting privileges, XML Tab, 21-23
managing security, 21-22
managing XML schema, 21-27
Oracle Net Services, 1-11
Oracle Text
advanced techniques, 7-45, 7-49
ALTER INDEX, 7-10
attribute sections, constraints, 7-54
building query applications, 7-21
comparing CONTAINS and existsNode, 7-38
conference Proceedings example, 7-57
CONTAINS and XMLType, 4-39
CONTAINS operator, 7-6
creating index on XMLType columns, 4-12
creating on XMLType columns, 4-40
CTXSYS, 7-5
CTXXPATH, 7-45
DBMS_XDBT, F-27
installing, 7-4
Oracle XML DB, and, 7-37
querying, 7-6
querying within attribute sections, 7-30
searching data with, 7-3
searching XML in CLOBs, 1-23
section_group, deciding which to use, 7-23
users and roles, 7-5
XMLType, 7-4
XMLType indexing, 7-35
Oracle XML DB, 3-5
access models, 2-7
advanced queueing, 1-23
application language, 2-8
architecture, 1-7
benefits, 1-3
configuring with Enterprise Manager, 21-7
designing, 2-3
features, 1-4
foldering, 13-2
installation, A-2
installing, 2-2
installing manually, A-4
introducing, 1-2
Java applications, 20-2
processing models, 2-9
Repository, 1-6, 3-35, 13-4
storage models, 2-10
storing XMLType, 4-4
upgrading, A-5
using XSL/XSLT with, 3-16
versioning, 14-2
when to use, 2-2
Oracle XML DB Resource API for Java/JNDI
examples, 17-3
using, 17-2
oracle.xdb, E-2
oracle.xdb.dom, E-2
oracle.xdb.spi, E-6
XDBResource.getContent(), E-9
XDBResource.getContentType, E-9
XDBResource.getCreateDate, E-9
XDBResource.getDisplayName, E-9
XDBResource.getLanguage(), E-9
XDBResource.getLastModDate, E-9
XDBResource.getOwnerId, E-9
XDBResource.setACL, E-9
XDBResource.setAuthor, E-9
XDBResource.setComment, E-9
XDBResource.setContent, E-9
XDBResource.setContentType, E-10
XDBResource.setCreateDate, E-10
XDBResource.setDisplayName, E-10
XDBResource.setInheritedACL, E-10
XDBResource.setLanguage, E-10
XDBResource.setLastModDate, E-10
XDBResource.setOwnerId, E-10
oracle.xdb.XMLType, 9-17
ora.contains
creating a policy for, 7-42
Index-8
XPath full-text searches, 7-40
ordered collections in tables (OCTs), 5-71
default storage of VARRAY, 5-37
rewriting collection index, 5-60
P
PATH, 15-9
PATH_SECTION_GROUP
using, 7-10
PATH_VIEW, 3-38
structure, 15-4
Path-based access
explained, 13-9
pathname
resolution, 13-7
performance
improved using Java writeToStream, 13-12
improvement for structured storage, 3-25
piecewise update, 1-5
PL/SQL DOM
examples, 8-24
methods, 8-11
PL/SQL Parser for XMLType, F-14
PL/SQL XSLT Processor for XMLType, F-15
point-to-point
support in AQ, 24-2
Positional Descriptor (PD), 5-21
predicates, 5-58
collection, mapping of, 5-59
principals, 18-6
privileges
aggregate, 18-9
atomic, 18-8
granting from Oracle Enterprise Manager, 21-23
processXSL, 8-33
protocol server
architecture, 19-3
configuration parameters, 19-4
event-based logging, 19-7
FTP, 19-7
FTP configuration parameters, 19-5
HTTP, 19-9
HTTP/WebDAV configuration
parameters, 19-5
Oracle XML DB, 19-2
using, 3-44
WebDAV, 19-11
protocols
access calling sequence, 13-11
access to Repository resources, 13-10
retrieving resource data, 13-11
storing resource data, 13-11
publish/subscribe
support in AQ, 24-2
purchase order
XML, 3-6
purchaseorder.xsl, D-6
Q
query access
using RESOURCE_VIEW and PATH_
VIEW, 15-2
query results
presenting, 7-21, 7-34
query rewrite, 5-51
query-based access
using SQL, 13-12
querying
resources, 3-38
XML data, 4-17
XMLType, 4-18
XMLType,transient data, 4-27
R
rebuilding hierarchical indexes, 16-11
REF attribute, 5-38, 5-47
registerHandler, 12-27
Reinstalling
Oracle XML DB
reinstalling, A-4
Repository, 3-35, 13-4
based on WebDAV, 3-35
hierarchy explained, 3-35
query-based access, 3-37
where is the data stored, 13-6
resource id
new version, 14-5
Index-9
RESOURCE_VIEW
explained, 15-2
PATH_VIEW differences, 15-5
querying resource documents, 3-38
structure, 15-3
resources
access using UNDER_PATH, 15-11
accessing Repository, 13-8
accessing with protocols, 19-6
changing privileges, 18-13
configuration management, 16-8
controlling access to, 18-7
creating from Enterprise Manager, 21-12
defined, 13-4
deleting, 13-7
deleting non-empty containers, 15-13
deleting using DELETE, 15-13
extending metadata properties, 13-17
inserting data using RESOURCE_VIEW, 15-11
management using DBMS_XDB, 16-2
managing, 18-12
multiple simultaneous operations, 15-15
required privileges for operations, 18-9
retrieving access control lists (ACLs), 18-13
setting property in access control lists
(ACLs), 18-12
storage options, 3-40
updating, 15-14
ResourceType
extending, 13-17
S
scalar nodes, mapping, 5-58
scalar value
converting to XML document using SYS_
XMLGEN, 10-46
schemaLocation, 5-10
schemaValidate, 3-24, 6-9
method, 5-15
searching CLOBs, 1-23
security
access control entries (ACEs), 18-6
aggregate privileges, 18-9
DBUri, 12-37
management using DBMS_XDB, 16-5
management with Enterprise Manager, 21-22
user and group access, 18-6
servlets
accessing Repository data, 13-13
and session pooling, 20-9
APIs, 20-10
AQ XML, 24-13
configuring, 20-12
configuring Oracle XML DB, 20-4
DBUri, URL into a query, 12-34
example, 20-10
explained, 1-29
installing, 20-11
session pooling, 20-9
session pooling and Oracle XML DB, 19-2
testing the, 20-12
writing Oracle XML DB HTTP, 20-4
XML manipulation, with, 20-3
session pooling, 20-9
protocol server, 19-2
setSchemaValidated, 6-10
Simple Object Access Protocol (SOAP) and
IDAP, 24-7
simpleContent
mapping to object types, 5-44
simpleType
elements, B-3
mapping to SQL, 5-33
mapping to VARCHAR2, 5-36
SOAP
access through Advanced Queueing, 1-11
and IDAP, 24-7
space
requirements in structured, unstructured
storage, 3-27
SQL functions
existsNode, 4-20
extractValue, 4-24
SQL*Loader, 22-2
SQLInLine attribute, 5-37
SQLName, 5-24
SQLType, 5-24, 5-28
attribute, 5-39
SQLX
Index-10
generating XML, 10-5
generating XML, for, 10-2
operators, explained, 1-5
Oracle extensions, 10-2
storage
of complex types, 3-32
options for resources, 3-40
structured, 3-33
XMLDATA, 4-13
structured or unstructured, 3-24
structured, query rewrite, 5-51
VARRAYs and OCT, 5-71
XML-schema-based, 5-20
XMLType CREATE TABLE, 5-50
storeVarrayAsTable attribute, 5-71
substitution
creating columns by inserting
HttpUriType, 12-25
/sys, restrictions, 13-3
SYS_DBURIGEN, 12-29
examples, 12-31
inserting database references, 12-31
passing columns or attributes, 12-30
retrieving object URLs, 12-33
returning partial results, 12-32
returning Uri-refs, 12-33
text function, 12-31
SYS_REFCURSOR
generating a document for each row, 10-13
SYS_XDBPD$, 5-21, 5-64
in query rewrites, 5-57
suppressing, 5-22
SYS_XMLAgg, 10-51
SYS_XMLGEN, 10-42
converting a UDT to XML, 10-47
converting XMLType instances, 10-48
generating XML in SQL queries, 4-12
inserting, 4-17
object views, 10-49
static member function create, 10-45
using with object views, 10-49
XMLFormat attributes, 10-44
XMLGenFormatType object, 10-44
T
tableProps attribute, 5-70
tablespace
do not drop, A-2
transform, 6-2
triggers
BEFORE INSERT trigger, 3-24
BEFORE INSERT, using with XMLType, 3-23
creating XMLType, 4-38
using with XMLType, 4-38
U
UDT
generating an element from, 10-9
generating an element using XMLForest, 10-10
UNDER_PATH, 3-38, 15-7
summary, 15-6
updateXML, 5-69
creating views, 4-35
mapping NULL values, 4-36
replacing contents of node tree, 3-14
updating text node value, 3-13
updating
resources, 3-38, 15-14
same node more than once, 4-37
upgrading
existing installation, A-5
URI
base, C-28
UriFactory, 12-26
configuring to handle DBUri-ref, 12-38
factory method, 12-26
generating UriType instances, 12-26
registering ecom protocol, 12-27
registering new UriType subtypes, 12-26
registerURLHandler, 12-27
Uri-ref, see also Uri-reference, 12-4
Uri-reference
database and session, 12-18
datatypes, 12-6
DBUri, 12-10
DBUri and object references, 12-18
DBUri syntax guidelines, 12-13
Index-11
DBUri-ref, 12-10
DBUri-ref uses, 12-18
DBUriType examples, 12-25
explained, 12-4
HTTP access for DBUri-ref, 12-34
UriFactory package, 12-26
UriType examples, 12-24
UriTypes, 12-23
UriTypes, 12-23
benefits, 12-7
creating Oracle Text index on column, 7-37
examples, 12-24
subtypes, advantages, 12-29
URL
identifying XML schema, for, 5-5
V
validating
examples, 6-10
isSchemaValid, 6-10
isSchemaValidated, 6-9
schemaValidate, 6-9
SetSchemaValidated, 6-10
with XML schema, 5-7
VARRAYS
inline, 3-32
storage using OCT, 5-71
VCR, 14-4, 14-6
access control and security, 14-8
version-controlled resource (VCR), 14-4, 14-6
versioning, 1-10, 14-2
FAQs, 14-12
views
RESOURCE and PATH, 15-2
W
W3C DOM Recommendation, 8-9
WebDAV
protocol server, features, 19-11
standard introduced, 3-35
WebFolder
creating in Windows 2000, 19-12
WITHIN
in Oracle Text, 7-8
limitations, 7-11
syntax, 7-11
writeToStream, 13-12
X
XDB$RESOURCE table, 13-18
XDBBinary, 13-5, 13-11
explained, 1-28
xdbconfig.xml, 19-2
XDBResource
namespace, 13-17
xsd, 13-17
XDBSchema.xsd, 5-19
XDBUri, 12-5
XDBUriType
accessing non-schema content, 3-44
accessing Repository content, 3-44
defined, 12-2
stores references to Repository, 12-6
XDK for PL/SQL, backward compatibility, 8-2
XML
binary datatypes, 5-34
fragments, mapping to LOBs, 5-39
primitive datatypes, 5-36
primitive numeric types, 5-34
XML DB Resource API for Java/JNDI, 17-2
XML DB, Oracle, 3-5
XML schema
and Oracle XML DB, 1-7, 5-5
benefits, 5-6
compared to DTD, B-31
complexType declarations, 5-41
creating default tables during registration, 5-70
cyclical references, 5-74
cyclical references between, 5-71
DTD limitations, B-33
elementFormDefault, 5-61
Enterprise Manager, managing them
from, 21-27
features, B-34
global, 5-12
inheritance in, complexType restrictions, 5-43
key feature explained, 1-5
Index-12
local, 5-11
local and global, 5-11
managing and storing, 5-19
mapping to SQL object types, 8-10
navigating in Enterprise Manager, 21-28
registering, 5-8
registering using DBMS_XMLSCHEMA, 5-9
root, 5-19
SQL mapping, 5-28
storage and access, 5-13
storage of XMLType, 3-28
unsupported constructs in query rewrites, 5-54
updateXML(), 5-69
URLs, 5-16
validating an XML document, 3-22
W3C Recommendation, 3-18, 5-3
xdb.SQLType, 3-31
XMLType methods, 5-19
XML schema, creating a view in Enterprise
Manager, 21-39
XML Schema, introducing W3C, B-2
XML SQL Utility
generating XML, 10-54
XML SQL Utility (XSU)
generating XML, 10-3
XML storage, 3-24
XML_SECTION_GROUP
using, 7-8
XMLAgg, 10-17
XMLAttributes, 10-7
XMLColAttVal, 10-20
XMLConcat, 10-15
concatenating XML elements in
argument, 10-16
returning XML elements by
concatenating, 10-16
XMLDATA
column, 5-58
optimizing updates, 5-69
parameter, F-3
pseudo-attribute of XMLType, 5-50
structured storage, 4-13
XMLElement, 10-5
attribute, 10-7
generating elements from DTD, 10-9
using namespaces to create XML
document, 10-8
XMLForest, 10-9
generating elements, 10-10
generating elements from DTD, 10-10
XMLFormat
XMLAgg, 10-17
XMLFormat object type
SYS_XMLGEN
XMLFormatType object, 10-44
XMLGenFormatType object, 10-44
XMLIsValid
validating
XMLIsValid, 6-9
XMLSequence, 10-11
extracting description nodes, 3-12
generating an XML document for each
row, 10-13
generating one document from another, 10-12
unnesting collections in XML to SQL, 10-14
XMLTransform, 4-37, 6-2
XMLType, 4-2
adding columns, 4-8
API, F-2
benefits, 4-3
CLOB storage, 4-5
column, 3-3
constraints, specifying, 4-14
CONTAINS operator, 4-39
CREATE TABLE, 5-50
creating columns, 4-8
creating columns, example, 4-8
creating Oracle Text index, 4-12
deleting a row containing, 4-10
deleting rows, 4-38
deleting using extract(), 4-38
dropping columns, 4-9
extracting data, 4-27
functions, 4-7
guidelines for using, 4-11
how to use, 4-7
indexing, 7-35
indexing columns, 4-39
inserting into, 4-9
inserting with createXML() using string, 4-16
Index-13
inserting with SYS_XMLGEN(), 4-17
inserting XML data, 4-15
instances, PL/SQL APIs, 8-2
Java
writeToStream, 13-12
loading data, 22-2
manipulating data in columns, 4-14
Oracle Text support, 7-4
querying, 4-17, 4-18
querying transient data, 4-27
querying with extract() and existsNode(), 4-26
querying XMLType columns, 4-27
queue payloads, 24-8
storage architecture, 1-11
storage characteristics, 4-12
storing data in Oracle XML DB, 4-4
summarized, 1-4
table, 3-3
table storage, 1-9
table, querying with JDBC, 9-3
tables, storing, 5-23
tables, views, columns, 5-15
triggers, 4-38
updating column, example, 4-10
using in SQL SELECT statement, 4-9
views,access with PL/SQL DOM APIs, 8-11
when to use, 4-4
Xpath support, 4-39
XMLType, loading with SQL*Loader, 22-2
XPath
basics, D-5
explained, 1-27
expressions, mapping, 5-57
mapping for extract(), 5-67
mapping for extract() without document
order, 5-68
mapping for extractValue(), 5-65
mapping to NULL in, 5-60
mapping, simple, 5-57
rewrites for existNode(), 5-62
rewriting expressions, 5-53
support, 4-39
text(), 5-58
unsupported constructs in query rewrites, 5-54
use for searching data, 1-5
using with Oracle XML DB, 3-5
W3C introducing, C-2
XPath expressions
supported, 5-54
xsi.noNamespaceSchemaLocation, 5-5
XSL
and CSS, D-5
basics, D-2
defined, 1-27
XSL stylesheet, example, D-6
XSLT, 8-11
1.1 specification, D-5
explained, D-5
xsql
include-xml
aggregating results into one XML, 10-52
generating XML from database, 10-53
XSQL Pages Publishing Framework
generating XML, 10-3, 10-52
Index-14

You might also like