XML Database Developer's Guide - Oracle XML DB
XML Database Developer's Guide - Oracle XML DB
Release 2 (9.2)
March 2002
Part No. A96620-01
Oracle9i XML Database Developer’s Guide - Oracle XML DB, Release 2 (9.2)
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, 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, Priya Vennapusa, James Warner
Contributors: Harish Akali, Deanna Bradshaw, Paul Brandenstein, Lisa Eldridge, 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 specified by law, is prohibited.
The information contained in this document is subject to change without notice. If you find 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, On Oracle, Oracle Store,
Oracle Press, ConText, and PL/SQL are trademarks or registered trademarks of Oracle Corporation.
Other names may be trademarks of their respective owners.
Contents
Preface........................................................................................................................................................ xxix
Audience .............................................................................................................................................. xxx
Organization........................................................................................................................................ xxx
Related Documentation ................................................................................................................... xxxv
Conventions...................................................................................................................................... xxxvi
Documentation Accessibility ......................................................................................................... xxxix
iii
Oracle XML DB and XML Schema .................................................................................................. 1-7
Oracle XML DB Architecture............................................................................................................ 1-8
XMLType Tables and Views Storage....................................................................................... 1-10
Oracle XML DB Repository ....................................................................................................... 1-11
XMLType Storage Architecture ...................................................................................................... 1-12
Cached XML Object Management Architecture .................................................................... 1-15
XML Repository Architecture ................................................................................................... 1-16
Why Use Oracle XML DB? .............................................................................................................. 1-17
Unifying Data and Content with Oracle XML DB ................................................................. 1-18
Oracle XML DB Offers Faster Storage and Retrieval of Complex XML Documents........ 1-21
Oracle XML DB Helps You Integrate Applications............................................................... 1-22
When Your Data Is Not XML You Can Use XMLType Views............................................. 1-22
Searching XML Data Stored in CLOBs Using Oracle Text ....................................................... 1-24
Building Oracle XML DB XML Messaging Applications with Advanced Queueing......... 1-24
Managing Oracle XML DB Applications with Oracle Enterprise Manager.......................... 1-25
Requirements for Running Oracle XML DB ............................................................................... 1-26
Standards Supported by Oracle XML DB .................................................................................... 1-26
Oracle XML DB Technical Support ............................................................................................... 1-27
Terminology Used in This Manual................................................................................................ 1-27
Oracle XML DB Examples Used in This Manual ....................................................................... 1-30
iv
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
v
Storage Options for Resources ....................................................................................................... 3-40
Defining Your Own Default Table Storage for XML Schema-Based Documents ................ 3-40
Accessing XML Schema-Based Content ....................................................................................... 3-43
Accessing Non-Schema-Based Content With XDBUriType ..................................................... 3-44
Oracle XML DB Protocol Servers................................................................................................... 3-44
Using FTP Protocol Server......................................................................................................... 3-44
Using HTTP/WebDAV Protocol Server ................................................................................. 3-49
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-9
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
Using XPath Expressions for Searching XML Documents ................................................... 4-18
vi
Querying XML Data Using XMLType Member Functions .................................................. 4-19
existsNode Function................................................................................................................... 4-20
extract () Function....................................................................................................................... 4-21
extractValue() Function ............................................................................................................. 4-23
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
updateXML() and NULL Values.............................................................................................. 4-35
Updating the Same XML Node More Than Once.................................................................. 4-36
XMLTransform() Function ........................................................................................................ 4-36
Deleting XML Data........................................................................................................................... 4-37
Using XMLType In Triggers............................................................................................................ 4-37
Indexing XMLType Columns ......................................................................................................... 4-38
Creating Function-Based Indexes on XMLType Columns ................................................... 4-38
Creating Oracle Text Indexes on XMLType Columns .......................................................... 4-39
vii
Java Bean Generation During XML Schema Registration........................................................ 5-17
Generating XML Schema Using DBMS_XMLSCHEMA.generateSchema() ........................ 5-18
XML Schema-Related Methods of XMLType .............................................................................. 5-20
Managing and Storing XML Schema ............................................................................................ 5-20
Root XML Schema, XDBSchema.xsd ....................................................................................... 5-20
How Are XML Schema-Based XMLType Structures Stored? .............................................. 5-21
DOM Fidelity..................................................................................................................................... 5-21
How Oracle XML DB Ensures DOM Fidelity with XML Schema ....................................... 5-22
DOM Fidelity and SYS_XDBPD$ ............................................................................................. 5-22
Creating XMLType Tables and Columns Based on XML Schema........................................... 5-23
SQL Object-Relational Types Store XML Schema-Based XMLType Tables....................... 5-24
Specifying SQL Object Type Names with SQLName, SQLType Attributes......................... 5-25
SQL Mapping Is Specified in the XML Schema During Registration ................................. 5-29
Mapping of Types Using DBMS_XMLSCHEMA ...................................................................... 5-32
Setting Attribute Mapping Type Information ........................................................................ 5-32
Setting Element Mapping Type Information.......................................................................... 5-32
XML Schema: Mapping SimpleTypes to SQL............................................................................. 5-34
simpleType: Mapping XML Strings to SQL VARCHAR2 Versus CLOBs ......................... 5-37
XML Schema: Mapping complexTypes to SQL .......................................................................... 5-38
Setting the SQLInLine Attribute to FALSE for Out-of-Line Storage................................... 5-38
Mapping XML Fragments to Large Objects (LOBs) .............................................................. 5-40
Oracle XML DB complexType Extensions and Restrictions..................................................... 5-42
complexType Declarations in XML Schema: Handling Inheritance ................................... 5-42
Mapping complexType: simpleContent to Object Types ..................................................... 5-45
Mapping complexType: Any and AnyAttributes.................................................................. 5-46
Handling Cycling Between complexTypes in XML Schema................................................ 5-47
Further Guidelines for Creating XML Schema-Based XML Tables ........................................ 5-50
Specifying Storage Clauses in XMLType CREATE TABLE Statements ............................. 5-51
Inserting New Instances into XMLType Columns ................................................................ 5-52
Query Rewrite with XML Schema-Based Structured Storage ................................................. 5-52
What Is Query Rewrite?............................................................................................................. 5-52
When Does Query Rewrite Occur? .......................................................................................... 5-53
What XPath Expressions Are Rewritten?................................................................................ 5-54
How are the XPaths Rewritten?................................................................................................ 5-56
Rewriting XPath Expressions: Mapping Types and Issues .................................................. 5-58
viii
XPath Expression Rewrites for existsNode().......................................................................... 5-63
Rewrite for extractValue() ......................................................................................................... 5-66
Rewrite for extract().................................................................................................................... 5-68
Optimizing Updates Using updateXML() .............................................................................. 5-70
Creating Default Tables During XML Schema Registration.................................................... 5-71
Ordered Collections in Tables (OCTs).......................................................................................... 5-72
Using OCT for VARRAY Storage............................................................................................. 5-72
Cyclical References Between XML Schemas............................................................................... 5-72
ix
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 Preference’s 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-34
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 a UriType Column .......................................................... 7-37
Querying XML Data: Use CONTAINS or existsNode()?...................................................... 7-38
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
Distinguishing Tags Across DocTypes.................................................................................... 7-49
Specifying Doctype Limiters to Distinguish Between Tags ................................................. 7-50
x
Doctype-Limited and Unlimited Tags in a Section Group................................................... 7-50
XML_SECTION_GROUP Attribute Sections ......................................................................... 7-50
Constraints for Querying Attribute Sections.......................................................................... 7-52
Repeated Zone Sections ............................................................................................................. 7-53
Overlapping Zone Sections ....................................................................................................... 7-54
Nested Sections ........................................................................................................................... 7-54
Using Table CTX_OBJECTS and CTX_OBJECT_ATTRIBUTES View................................ 7-55
Case Study: Searching XML-Based Conference Proceedings .................................................. 7-56
Searching for Content and Structure in XML Documents.................................................... 7-56
Searching XML-Based Conference Proceedings Using Oracle Text ................................... 7-56
Searching Conference Proceedings Example: jsp .................................................................. 7-60
Frequently Asked Questions About Oracle Text........................................................................ 7-64
FAQs: General Questions About Oracle Text.............................................................................. 7-64
Can I Use a CONTAINS() Query with an XML Function to Extract an
XML Fragment? ......................................................................................................................... 7-64
Can XML Documents Be Queried Like Table Data? ............................................................. 7-64
Can I Edit Individual XML Elements?..................................................................................... 7-65
How Are XML Files Locked in CLOBs and BLOBs?............................................................. 7-65
How Can I Search XML Documents and Return a Zone? .................................................... 7-65
How Do I Load XML Documents into the Database?........................................................... 7-66
How Do I Search XML Documents with Oracle Text?.......................................................... 7-66
How Do I Search XML Using the WITHIN Operator? ......................................................... 7-66
Where Can I Find Examples of Using Oracle Text to Search XML? ................................... 7-67
Does Oracle Text Automatically Recognize XML Tags? ...................................................... 7-67
Can I Do Range Searching with Oracle Text?......................................................................... 7-68
Can Oracle Text Do Section Extraction?.................................................................................. 7-68
Can I Create a Text Index on Three Columns?....................................................................... 7-68
How Fast Is Oracle9i at Indexing Text? Can I Just Enable Boolean Searches? .................. 7-69
FAQs: Searching Attribute Values with Oracle Text.................................................................. 7-69
Can I Build Text Indexes on Attribute Values?...................................................................... 7-69
FAQs: Searching XML Documents in CLOBs Using Oracle Text............................................ 7-70
How Can I Search Different XML Documents Stored in CLOBs?....................................... 7-70
How Do I Store an XML Document in a CLOB Using Oracle Text?................................... 7-71
Is Storing XML in CLOBs Affected by Character Set? .......................................................... 7-72
Can I Only Insert Structured Data When the Table is Created?.......................................... 7-72
Can I Break an XML Document Without Creating a Custom Development?................... 7-72
xi
What Is the Syntax for Creating a Substring Index with XML_SECTION_GROUP?....... 7-73
Why Does the XML Search for Topic X with Relevance Y Give Wrong Results?............. 7-74
xii
9 Java and Java Bean APIs for XMLType
Introducing Java DOM and Java Bean APIs for XMLType ........................................................ 9-2
Java DOM API for XMLType............................................................................................................ 9-2
Accessing XML Documents Stored in Oracle9i Database (Java) ........................................... 9-3
Using JDBC to Manipulate XML Documents Stored in a Database...................................... 9-6
Java DOM API for XMLType Features ......................................................................................... 9-16
Java DOM API for XMLType Classes ........................................................................................... 9-18
Java DOM API for XMLType: Calling Sequence ................................................................... 9-19
Java Bean API for XMLType ........................................................................................................... 9-20
Guidelines for Using Java Bean API for XMLType.................................................................... 9-21
xiii
SYS_XMLGEN() Function............................................................................................................. 10-41
Using XMLFormat Object Type.............................................................................................. 10-43
SYS_XMLAGG() Function ............................................................................................................ 10-50
Generating XML Using XSQL Pages Publishing Framework ............................................... 10-51
Generating XML Using XML SQL Utility (XSU)...................................................................... 10-54
11 XMLType Views
What Are XMLType Views? ............................................................................................................ 11-2
Creating Non-Schema-Based XMLType Views........................................................................... 11-2
Creating XML Schema-Based XMLType Views .......................................................................... 11-4
Using Multiple Namespaces ..................................................................................................... 11-9
Creating XMLType Views by Transforming XMLType Tables .............................................. 11-14
Referencing XMLType View Objects Using REF()................................................................... 11-15
DML (Data Manipulation Language) on XMLType Views .................................................... 11-15
Query Rewrite on XMLType Views............................................................................................. 11-17
Query Rewrite on XML Schema-Based Views ..................................................................... 11-17
Query Rewrite on Non-Schema-Based Views ...................................................................... 11-17
Ad-Hoc Generation of XML Schema-Based XML .................................................................... 11-19
Validating User-Specified Information....................................................................................... 11-20
xiv
Some Common DBUri Scenarios................................................................................................. 12-14
Identifying the Whole Table ................................................................................................... 12-14
Identifying a Particular Row of the Table ............................................................................. 12-15
Identifying a Target Column .................................................................................................. 12-16
Retrieving the Text Value of a Column ................................................................................. 12-16
How DBUris Differ from Object References......................................................................... 12-17
DBUri Applies to a Database and Session ............................................................................ 12-17
Where Can DBUri Be Used? ................................................................................................... 12-17
DBUriType Functions .................................................................................................................... 12-18
XDBUriType..................................................................................................................................... 12-20
How to Create an Instance of XDBUriType.......................................................................... 12-21
Creating Oracle Text Indexes on UriType Columns ................................................................ 12-22
Using UriType Objects .................................................................................................................. 12-22
Storing Pointers to Documents with UriType ...................................................................... 12-23
Using HttpUriType and DBUriType ..................................................................................... 12-25
Creating Instances of UriType Objects with the UriFactory Package .................................. 12-25
Registering New UriType Subtypes with the UriFactory Package................................... 12-26
Why Define New Subtypes of UriType? .................................................................................... 12-28
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
xv
Pathname Resolution ................................................................................................................. 13-7
Deleting Resources ..................................................................................................................... 13-7
Accessing Oracle XML DB Repository Resources...................................................................... 13-8
Navigational or Path Access............................................................................................................ 13-9
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-17
Extending Resource Metadata Properties .................................................................................. 13-17
xvi
EQUALS_PATH................................................................................................................................. 15-8
PATH ................................................................................................................................................... 15-8
DEPTH ................................................................................................................................................ 15-8
Using the Resource View and Path View API............................................................................. 15-9
Accessing Paths and Repository Resources: Examples......................................................... 15-9
Inserting Data into a Repository Resource: Examples ........................................................ 15-10
Deleting Repository Resources: Examples............................................................................ 15-10
Updating Repository Resources: Examples.......................................................................... 15-11
Working with Multiple Oracle XML DB Resources Simultaneously .................................. 15-12
xvii
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
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-7
Aggregate Privileges .................................................................................................................. 18-8
ACL Evaluation Rules...................................................................................................................... 18-9
Using Oracle XML DB ACLs .......................................................................................................... 18-9
Updating the Default ACL on a Folder ................................................................................. 18-10
ACL and Resource Management.................................................................................................. 18-11
How to Set Resource Property ACLs..................................................................................... 18-11
Default Assignment of ACLs .................................................................................................. 18-12
Retrieving ACLs for a Resource ............................................................................................. 18-12
Changing Privileges on a Given Resource ............................................................................ 18-12
Restrictions for Operations on ACLs ..................................................................................... 18-12
Using DBMS_XDB to Check Privileges ..................................................................................... 18-13
Row-Level Security for Access Control Security ................................................................. 18-13
xviii
Using HTTP and Oracle XML DB Protocol Server .................................................................... 19-8
Oracle XML DB Protocol Server: HTTP Features .................................................................. 19-8
Using WebDAV and Oracle XML DB ......................................................................................... 19-10
Oracle XML DB WebDav Features......................................................................................... 19-10
Using Oracle XML DB and WebDAV: Creating a WebFolder in Windows 2000 ........... 19-11
xix
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
Configuring 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
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
xx
Enqueue Using AQ XML Servlet................................................................................................... 23-9
Dequeue Using AQ XML Servlet ................................................................................................ 23-11
IDAP and AQ XML Schemas ....................................................................................................... 23-12
Frequently Asked Questions (FAQs): XML and Advanced Queuing .................................. 23-13
Can I Store AQ XML Messages with Many PDFs as One Record? ................................... 23-13
Do I Specify Payload Type as CLOB First, Then Enqueue and Store? ............................. 23-13
Can I Add New Recipients After Messages Are Enqueued? ............................................. 23-14
How Does Oracle Enqueue and Dequeue and Process XML Messages?......................... 23-14
How Can I Parse Messages with XML Content from AQ Queues?.................................. 23-15
Can I Prevent the Listener from Stopping Until the XML Document Is Processed?...... 23-15
How Can I Use HTTPS with AQ? .......................................................................................... 23-16
What Are the Options for Storing XML in AQ Message Payloads? ................................. 23-16
Can We Compare IDAP and SOAP? ..................................................................................... 23-16
xxi
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 Definitions ....................................................................................................... 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
XML Schema Example, PurchaseOrder.xsd ................................................................................ B-37
xxii
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
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-5
XSL Transformation (XSLT) .............................................................................................................. D-5
XSLT 1.1 Specification.................................................................................................................. D-5
XML Path Language (Xpath)............................................................................................................. D-6
CSS Versus XSL................................................................................................................................... D-7
XSL Stylesheet Example, PurchaseOrder.xsl................................................................................. D-7
xxiii
E Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI:
Quick Reference
Java DOM API For XMLType ........................................................................................................... E-2
Java Bean API for XMLType ............................................................................................................. E-6
Oracle XML DB Resource API for Java/JNDI................................................................................ E-7
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-13
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR) ....................................... F-14
DBMS_XMLSCHEMA..................................................................................................................... F-15
Oracle XML DB XML Schema Catalog Views............................................................................. F-18
Resource API for PL/SQL (DBMS_XDB) ..................................................................................... F-19
DBMS_XMLGEN.............................................................................................................................. F-22
RESOURCE_VIEW, PATH_VIEW ................................................................................................. F-23
DBMS_XDB_VERSION .................................................................................................................. F-24
DBMS_XDBT..................................................................................................................................... F-25
xxiv
acl.xsd: XML Schema for Representing Oracle XML DBACLs............................................... G-15
ACL Representation XML Schema, acl.xsd ........................................................................... G-15
acl.xsd .......................................................................................................................................... G-15
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB .............................................. G-18
xdbconfig.xsd ............................................................................................................................. G-18
Glossary
Index
xxv
xxvi
Send Us Your Comments
Oracle9i XML Database Developer’s Guide - Oracle XML DB, Release 2 (9.2)
Part No. A96620-01
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.
■ Did you find any errors?
■ Is the information clearly presented?
■ Do you need more information? If so, where?
■ Are the examples correct? Do you need more examples?
■ What features did you like most?
If you find 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:
■ Electronic mail: infodev_us@oracle.com
■ FAX: (650) 506-7227 Attn: Server Technologies Documentation Manager
■ 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.
xxvii
xxviii
Preface
This manual describes Oracle XML DB, the Oracle9i XML database. It describes
how XML 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:
■ Audience
■ Organization
■ Related Documentation
■ Conventions
■ Documentation Accessibility
xxix
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:
xxx
Chapter 4, "Using XMLType"
Describes how to create XMLType tables and manipulate and query XML data for
non-schema-based XMLType tables and columns.
xxxi
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.
xxxii
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.
xxxiii
Chapter 23, "Exchanging XML Data Using Advanced Queueing (AQ)"
Introduces how you can use Advancd Queueing to exchange XML data. It describes
Internet Data Access Presentation (IDAP), using AQ XML Servlet to enquue and
dequeue messages, using IDAP and AQ XML schemas.
Appendix E, "Java DOM and Java Bean API for XMLType, Resource API for
Java/JNDI: Quick Reference"
Provies a quick reference for the Oracle XML DB Java APIs.
xxxiv
Glossary
Related Documentation
For more information, see these Oracle resources:
■ Oracle9i Database New Features for information about the differences between
Oracle9i and the Oracle9i Enterprise Edition and the available features and
options. That book also describes all the features that are new in Oracle9i
Release 2 (9.2).
■ Oracle9i XML Developer’s Kits Guide - XDK
■ Oracle9i XML Case Studies and Applications (contains XDK examples, no
Oracle XML DB examples for this release)
■ Oracle9i XML Developer’s Kits Guide - XDK
■ Oracle9i Database Error Messages
■ Oracle Text Application Developer’s Guide
■ Oracle Text Reference
■ Oracle9i Database Concepts.
■ Oracle9i Java Developer’s Guide
■ Oracle9i Application Developer’s Guide - Fundamentals
■ Oracle9i Application Developer’s Guide - Advanced Queuing
■ 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.
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/
xxxv
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
Conventions
This section describes the conventions used in the text and code examples of this
documentation set. It describes:
■ Conventions in Text
■ 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.
xxxvi
Convention Meaning Example
UPPERCASE Uppercase monospace typeface indicates You can specify this clause only for a NUMBER
monospace elements supplied by the system. Such column.
(fixed-width) elements include parameters, privileges,
You can back up the database by using the
font datatypes, RMAN keywords, SQL
BACKUP command.
keywords, SQL*Plus or utility commands,
packages and methods, as well as Query the TABLE_NAME column in the USER_
system-supplied column names, database TABLES data dictionary view.
objects and structures, usernames, and
Use the DBMS_STATS.GENERATE_STATS
roles.
procedure.
lowercase Lowercase monospace typeface indicates Enter sqlplus to open SQL*Plus.
monospace executables, filenames, directory names,
The password is specified in the orapwd file.
(fixed-width) and sample user-supplied elements. Such
font elements include computer and database Back up the datafiles and control files in the
names, net service names, and connect /disk1/oracle/dbs directory.
identifiers, as well as user-supplied
The department_id, department_name,
database objects and structures, column
and location_id columns are in the
names, packages and classes, usernames
hr.departments table.
and roles, program units, and parameter
values. Set the QUERY_REWRITE_ENABLED
initialization parameter to true.
Note: Some programmatic elements use a
mixture of UPPERCASE and lowercase. Connect as oe user.
Enter these elements as shown.
The JRepUtil class implements these
methods.
lowercase Lowercase italic monospace font You can specify the parallel_clause.
italic represents placeholders or variables.
Run Uold_release.SQL where old_
monospace
release refers to the release you installed
(fixed-width)
prior to upgrading.
font
The following table describes typographic conventions used in code examples and
provides examples of their use.
xxxvii
Convention Meaning Example
[] Brackets enclose one or more optional DECIMAL (digits [ , precision ])
items. Do not enter the brackets.
{} Braces enclose two or more items, one of {ENABLE | DISABLE}
which is required. Do not enter the braces.
| A vertical bar represents a choice of two {ENABLE | DISABLE}
or more options within brackets or braces.
[COMPRESS | NOCOMPRESS]
Enter one of the options. Do not enter the
vertical bar.
... Horizontal ellipsis points indicate either:
■ That we have omitted parts of the CREATE TABLE... AS subquery;
code that are not directly related to
the example
SELECT col1, col2,... , coln FROM
■ That you can repeat a portion of the
employees;
code
. 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 acctbal NUMBER(11,2);
brackets, braces, vertical bars, and ellipsis
acct CONSTANT NUMBER(4) := 3;
points as shown.
Italics Italicized text indicates placeholders or CONNECT SYSTEM/system_password
variables for which you must supply
DB_NAME = database_name
particular values.
UPPERCASE Uppercase typeface indicates elements SELECT last_name, employee_id FROM
supplied by the system. We show these employees;
terms in uppercase in order to distinguish
SELECT * FROM USER_TABLES;
them from terms you define. Unless terms
appear in brackets, enter them in the DROP TABLE hr.employees;
order and with the spelling shown.
However, because these terms are not
case sensitive, you can enter them in
lowercase.
lowercase Lowercase typeface indicates SELECT last_name, employee_id FROM
programmatic elements that you supply. employees;
For example, lowercase indicates names
sqlplus hr/hr
of tables, columns, or files.
CREATE USER mjones IDENTIFIED BY ty3MU9;
Note: Some programmatic elements use a
mixture of UPPERCASE and lowercase.
Enter these elements as shown.
xxxviii
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/
xxxix
xl
What’s 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).
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
XMLType Tables
Datatype XMLType can now be used to create tables of XMLType. This gives you the
flexibility 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-defined constructors.
xli
■ 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 definitions.
■ Register annotated XML schema using the DBMS_XMLSCHEMA package, to
share storage and type definitions. Registered XML schema can be shared
across all database users to allow for instance wide common document
definition. The registration process optionally creates Java beans and
default tables. With XML schema annotationyou can specify various
objects such as, SQL types, default storage tables, and so on.
■ 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.
■ Automatically validate XML documents or instances against W3C XML
Schema when the XML documents or instances are added to Oracle XML
DB.
■ Explicitly validate XML documents and instances against XML schema
using XMLIsSchemaValid() method on XMLType.
■ Use datatype -aware extraction of part of an XML document using the
extractValue operator.
xlii
■ extract(), existsNode(), and extractValue() now allow for a
namespace-based operation.
■ extract(), existsNode(), and extractValue() support the full
XPath function set, including axis operators.
■ 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".
xliii
■ Viewing the database and its content as a file system containing resources,
typically referred to as files and folders.
■ Access and manipulation of resources through path name-based SQL and
Java API.
■ Access and manipulation of resources through built-in native Protocol
Servers for FTP, HTTP, and WebDAV.
■ ACL-based security for Oracle XML DB resources.
xliv
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".
xlv
See:
■ Chapter 23, "Exchanging XML Data Using Advanced Queueing
(AQ)"
■ Oracle9i Application Developer’s Guide - Advanced Queuing
See:
■ "Generating XML Using XSQL Pages Publishing Framework"
on page 10-51. and "Generating XML Using XML SQL Utility
(XSU)" on page 10-54
■ Oracle9i XML Developer’s Kits Guide - XDK
xlvi
Part I
Introducing Oracle XML DB
Part I of this manual introduces Oracle XML DB. It contains the following chapters:
■ Chapter 1, "Introducing Oracle XML DB"
■ Chapter 2, "Getting Started with Oracle XML DB"
■ Chapter 3, "Using Oracle XML DB"
1
Introducing Oracle XML DB
This chapter introduces you to Oracle XML DB by describing the Oracle XML DB
benefits, features, and architecture. This chapter contains the following sections:
■ Introducing Oracle XML DB
■ Benefits of Oracle XML DB
■ Key Features of Oracle XML DB
■ Oracle XML DB and XML Schema
■ Oracle XML DB Architecture
■ XMLType Storage Architecture
■ Why Use Oracle XML DB?
■ Searching XML Data Stored in CLOBs Using Oracle Text
■ Building Oracle XML DB XML Messaging Applications with Advanced
Queueing
■ Managing Oracle XML DB Applications with Oracle Enterprise Manager
■ Requirements for Running Oracle XML DB
■ Oracle XML DB Technical Support
■ Terminology Used in This Manual
■ Oracle XML DB Examples Used in This Manual
See Also: Oracle9i XML Developer’s Kits Guide - XDK. for more
information about XDK
DB. This is a required step before storing XML schema-based instance documents.
Once registered, the XML schema can be referenced using its URL.
Browser
or other
UI
Direct Oracle
Net WebDAV FTP
HTTP Services Access Access
Access Access
AQ and
Oracle9i
Streams
Access
Oracle9i Database
Gateways
to external Oracle XML DB
sources
Oracle XML DB
XMLType Tables Repository
and Views
The contents of Oracle XML DB Repository are referred to as resources. These can be
either containers (or directories / folders) or files. All resources are identified 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 defined by the user.
■ 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".
new versions being created while the data corresponding to the previous
versions is retained.
■ 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.
■ Foldering. XML Repository’s 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.
See Also:
■ Part II. Storing and Retrieving XML Data in Oracle XML DB
■ Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
■ Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
■ Chapter 23, "Exchanging XML Data Using Advanced Queueing
(AQ)"
Figure 1–2 Oracle XML DB: XMLType Storage and Retrieval Architecture
JDBC
AQ
Access
Oracle9i
Database
Oracle XML DB
HTTP DAV, FTP
SQL Protocol
Protocol
Handler Engine Handlers
XML Schemas
Native Remote
CLOB Structured Local Tables
Storage Tables DBLinks
XML Accessed
Storage via DBLinks
Dynamic Static
Java Java (Bean)
Access Access
Cached XML
Object
Management Compile-time
Calculated
Offsets
XML
Schemas Cache
Virtual
DOM
See Also:
■ Chapter 13, "Oracle XML DB Foldering"
■ Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
Table
Name ACL Property 1 Property N Property N
abc
Oracle9i Database
LOB
FTP
WebDAV Tables or
B*Tree Text Hierarchical
Index Index Index Views
of XML
■ When Your Data Is Not XML You Can Use XMLType Views
Figure 1–5 Unifying Data and Content: Some Common XML Architectures
Non-Native XML Processing Separate Data and Content Servers Oracle XML DB
File
System
Multimedia and Structured Data Multimedia, Document Structured Data Multimedia and
Document Content and Metadata Content and XML, Document Content,
Metadata Structured Data,
XML, Metadata
Organizations today typically manage their structured data and unstructured data
differently:
■ Unstructured data, in tables, makes document access transparent and table
access complex
■ 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:
■ XML operations on object-relational (such as table) data
■ SQL operations on XML documents
This makes the database much more accessible to XML-shaped data content.
See Also:
■ Chapter 9, "Java and Java Bean APIs for XMLType"
■ Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
■ Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
■ Storage Independence: 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".
■ 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:
■ Chapter 6, "Transforming and Validating XMLType Data".
■ Chapter 10, "Generating XML Data from the Database".
■ Chapter 11, "XMLType Views".
■ Oracle9i XML Developer’s Kits Guide - XDK, in the chapter, “XSQL Pages
Publishing Framework”. It includes XMLType examples.
■ Ease of Interchange: 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 fidelity in the storage/retrieval
process, Oracle XML DB enables a clean interchange. See:
■ Chapter 6, "Transforming and Validating XMLType Data"
■ 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:
■ Native XMLType. See Chapter 4, "Using XMLType".
■ The lazily evaluated virtual DOM support. See Chapter 8, "PL/SQL API for
XMLType".
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 first register an XML schema with annotations
that represent the bi-directional mapping from XML 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 1–6 summarizes the Oracle XML DB advantages.
Oracle
XML DB
indexing, searching
updating, transaction processing
manages constraints
multiple data views
speeds up XML storage, retrieval
supports standards for storing,
modifying, retrieving data
See Also:
■ Chapter 7, "Searching XML Data with Oracle Text"
■ Oracle Text Application Developer’s Guide
■ Oracle Text Reference
See Also:
■ Oracle9i Application Developer’s Guide - Advanced Queuing for
information about using XMLType with Oracle Advanced
Queuing
■ Chapter 23, "Exchanging XML Data Using Advanced Queueing
(AQ)"
See:
■ http://otn.oracle.com/tech/xml for the latest news
and white papers on Oracle XML DB
■ Chapter 2, "Getting Started with Oracle XML DB"
currently supported, and stateful servlets are not supported). See Chapter 20,
"Writing Oracle XML DB Applications in Java".
■ Simple Object Access Protocol (SOAP). You can access XML stored in the server
from SOAP requests. You can build, publish, or find Web Services using Oracle
XML DB and Oracle9iAS, using WSDL and UDDI. You can use Oracle
Advanced Queuing IDAP, the SOAP specification for queuing operations, on
XML stored in Oracle9i database. See Chapter 23, "Exchanging XML Data Using
Advanced Queueing (AQ)" and Oracle9i Application Developer’s Guide - Advanced
Queuing.
This chapter provides some preliminary design criteria for consideration when
planning your Oracle XML DB solution. It contains the following sections:
■ Getting Started with Oracle XML DB
■ When to Use the Oracle XML DB
■ Designing Your XML Application
■ Oracle XML DB Design Issues: Introduction
■ Oracle XML DB Application Design: a. How Structured Is Your Data?
■ Oracle XML DB Application Design: b. Access Models
■ Oracle XML DB Application Design: c. Application Language
■ Oracle XML DB Application Design: d. Processing Models
■ Oracle XML DB Design: Storage Models
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.
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 23,
"Exchanging XML Data Using Advanced Queueing (AQ)".
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.
a b c d
Data Access? Language? Processing and
Structure? • Java Data
Repository • JDBC Manipulation?
Path Access • PL/SQL • DOM
• JNDI • SQL inserts /
updates
SQL • XSLT
Query Access • Queriability
• Updatability
Storage Options ?
– 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.
■ 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 files in Repository folders. With this
design you have many access options including path- and query-based access
through Resource Views.
How Structured is
Your Data?
Semi-structured
Structured Unstructured
Psudo-structured
Data Data
Data
Use either: Store as: Use either: Store as: Store as:
CLOB or • CLOB in • CLOB • CLOB in • CLOB in
Structured XMLType • Structured XMLType XMLType
Storage Table • Hybrid Table Table
• File in Storage • File in • File in
Repository (semi- Repository Repository
Folder structured Folder Folder
Views storage) Views Views
• Access • Access • Access
through through through
Resource Resource Resource
APIs APIs APIs
Figure 2–3 Data Access Models: How Will Users or Applications Access the Data?
Oracle XML DB
Data Access Options
Query-based Path-based
Access Access
See Also:
■ Chapter 9, "Java and Java Bean APIs for XMLType"
■ Chapter 17, "Oracle XML DB Resource API for Java/JNDI"
■ Chapter 20, "Writing Oracle XML DB Applications in Java"
■ Appendix E, "Java DOM and Java Bean API for XMLType,
Resource API for Java/JNDI: Quick Reference"
■ PLSQL
See Also:
■ Chapter 8, "PL/SQL API for XMLType"
■ Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
■ Appendix F, "Oracle XML DB XMLType API, PL/SQL and
Resource PL/SQL APIs: Quick Reference"
without rewriting the entire document. This is more efficient, 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 defining Oracle
objects with XMLType attributes, you can do the following:
■ Store more than one type of XML document in the same queue. The documents
are stored internally as CLOBs.
■ Selectively dequeue messages with XMLType attributes using the operators
existsNode(), extract(), and so on.
■ Define transformations to convert Oracle objects to XMLType.
■ Define rule-based subscribers that query message content using XMLType
operators such as existsNode() and extract().
See Also:
■ Chapter 23, "Exchanging XML Data Using Advanced Queueing
(AQ)"
■ Oracle9i Application Developer’s Guide - Advanced Queuing
CLOBs, when the XML documents are retrieved there will be no data loss. Data
integrity is high, and the cost of regeneration is low.
■ Structured storage? Structured storage loses whitespace information but
maintains fidelity to the XML DOM, namely DOM stored = DOM retrieved.
This provides:
– Better SQL ’queriability’ with improved performance
– Piece-wise updatability
■ 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:
■ Data queryability and updatability, namely, how and how often the data is
queried and updated.
■ How your data is accessed. This is determined by your application processing
requirements.
■ What language(s) your application uses. This is also determined by your
application processing requirements.
See Also:
■ "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"
■ Chapter 4, "Using XMLType","Storing XMLType Data in Oracle
XML DB" on page 4-4
■ Chapter 5, "Structured Mapping of XMLType", "DOM Fidelity"
on page 5-21
Relational
Tables
Relational
Tables
This chapter describes where and how you 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 how you can define a default XML table for storing XML
schema-based documents and using XDBUriType to access non-schema-based
content.
It contains the following sections:
■ Storing Data in an XMLType Column or XMLType Table
■ Accessing Data in XMLType Columns or XMLType Tables
■ Using XPath with Oracle XML DB
■ Updating XML Documents with updateXML()
■ Introducing the W3C XSLT Recommendation
■ Using XSL/XSLT with Oracle XML DB
■ Other XMLType Methods
■ Introducing the W3C XML Schema Recommendation
■ Validating an XML Document Using an XML Schema
■ Storing XML: Structured or Unstructured Storage
■ Structured Storage: XML Schema-Based Storage of XMLType
■ Oracle XML DB Repository
Example 3–3 To Store an XML Document First Create an XMLType Instance Using
getDocument()
To store an XML document in an XMLType table or column the XML document
must first 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 getDocument() with the following signature:
FUNCTION getDocument RETURNS CLOB
dbms_lob.createtemporary(xclob,TRUE,dbms_lob.session);
dbms_lob.loadfromfile(xclob,xbfile, dbms_lob.getlength(xbfile));
dbms_lob.close(xbfile);
return xclob;
end;
/
-- you can use getDocument() to generate a CLOB from a file containing an XML
-- document. For example, the following statement inserts a row into the
-- XMLType table Example2 created earlier:
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.
See Also:
■ Chapter 4, "Using XMLType"
■ Chapter 10, "Generating XML Data from the Database"
</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">
<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 3–1.
, namespace
EXISTSNODE ( XMLType_instance , XPath_string )
Example 3–4 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;
Example 3–5 existsNode() Examples That Do Not Find a Node that Matches the XPath
Expression
The following existsNode() operations do not find 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.
Using extractValue()
The extractValue() syntax is shown in Figure 3–2.
, value_expr
EXTRACTVALUE ( XMLType_instance , XPath_string )
SELECT extractValue(value(x),
'/PurchaseOrder/LineItems/LineItem[2]/Part/@Id')
FROM XMLTABLE X;
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 first example the XPath expression matches three nodes in the document, in the
second example the Xpath expression identifies a nodetree, not a text node or
attribute value.
-- FROM XMLTABLE X;
-- *
-- ERROR at line 3:
-- ORA-19025: EXTRACTVALUE returns value of only one node
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
-- This returns:
-- EXTRACTVALUE(VALUE(X),’/PURCHASEORDER/REFERENCE’)
-- --------------------------------------------------
-- ADAMS-20011127121040988PST
Using extract()
The extract() syntax is shown in Figure 3–3.
, namespace
EXTRACT ( XMLType_instance , XPath_string )
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 datatype’s extract() method.
Note: In this case the XML is not well formed as it contains more
than one root node.
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 3–11 Using extract() to Return a Node Tree that Matches an XPath
Expression
In this example extract() returns the node tree that matches the specified 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 3–4.
XMLType_instance
XMLSEQUENCE ( , fmt )
sys_refcursor_instance
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 3–12 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
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 identified 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 3–13 Using updateXML() to Update a Text Node Value Identified by an XPath
Expression
This example uses updateXML() to update the value of the text node identified 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>
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;
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/>
...
<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>
See Also: Appendix D, "XSLT Primer" for the full listing of this
XSL stylesheet.
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>
</xs:schema>
--This returns:
-- PL/SQL procedure successfully completed.
DESCRIBE XML_PURCHASEORDER
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 defined
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
identified by adding the appropriate attributes to the opening tag for the root
element of the document. These attributes are defined by W3C XML Schema
recommendation and are part of the W3C XMLSchema-Instance namespace.
Consequently in order to define these attributes the document must first declare the
XMLSchema-instance namespace. This namespace is declared as follows:
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance:
Once the XMLSchema-instance namespace has been declared and given a
namespace prefix 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 prefix for the
XMLSchema-instance namespace was defined as xsi.
Example 3–20 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 defined as
storing documents which conform to the PurchaseOrder Schema
INSERT INTO XML_PURCHASEORDER
values (xmltype(getDocument('Invoice.xml')))
values (xmltype(getDocument('Invoice.xml')))
*
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:
■ A table level CHECK constraint
■ A PL/SQL BEFORE INSERT trigger
-- This returns:
-- Table altered
values (xmltype(getDocument(’InvalidPurchaseOrder.xml’)));
INSERT INTO XML_PURCHASEORDER;
*
-- This returns:
-- ERROR at line 1:
-- ORA-02290: check constraint (DOC92.VALID_PURCHASEORDER) violated
Example 3–22 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 specified schema
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;
/
-- This returns:
-- Trigger created.
-- 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:
■ Table CHECK Constraint. The TABLE constraint approach’s advantage is that
it is simpler to code. Its disadvantage is that, since it is based on the
of SQL objects by annotating the schema. To annotate an XML schema, you must
first include the Oracle XML DB namespace in the XMLSchema tag, defined 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 defined, the annotations defined by
Oracle XML DB can be used.
Example 3–23 Defining the Name of SQL Objects Generated from complexTypes
This example uses xdb:SQLType to define the name of the SQL object generated
from complexType 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"/>
<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>
Example 3–24 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="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>
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
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.
This returns:
ERROR at line 1:
ORA-00001: unique constraint (DOC92.REFERENCE_IS_UNQIUE) violated
defines 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 files 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.
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>
</Resource>
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 definition of the RESOURCE_VIEW is as follows:
SQL> describe RESOURCE_VIEW
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 definition of the PATH_VIEW is as
follows:
SQL> describe PATH_VIEW
3 begin
4 result := dbms_xdb.createFolder('/public/testFolder');
5 end;
6 /
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 /
Updating Resources
You can update Resources using updateXML().
-- 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.
call dbms_xdb.deleteResource('/public/testFolder/testFile.xml')
/
Call completed.
call dbms_xdb.deleteResource('/public/testFolder')
/
Call completed.
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 3–31 Adding the xdb:defaultTable Attribute to the XML Schema’s Element
Definition
The following example shows the result of adding an xdb:defaultTable
attribute to the XML schema definition’s 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>
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 /
Example 3–32 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
result := dbms_xdb.createResource(
’/public/testFolder/purchaseOrder1.xml’,
getDocument(’purchaseOrder1.xml’)
);
end;
/
commit;
-- Commit complete.
Results in:
COUNT(*)
----------
1
Example 3–33 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
SQL> commit;
Commit complete.
default table. This reference can be used to perform join operations between the
resource and it’s content. This can be seen in the following example.
See Also: Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
■ Command line clients, such as the command line clients supplied with Unix
and Windows Command Prompt
■ Graphical clients, such as WS-FTP
■ Web Browsers that support the FTP protocol
Figure 3–6, Figure 3–7, Figure 3–8, and Figure 3–9 show examples of how you can
access the root level of the Repository using various of standard FTP clients.
Figure 3–6 Accessing the Repository Root Level from the Command Prompt Command Line
Figure 3–7 Accessing the Repository Root Level fro m IE Browser Web Folder Menu
Figure 3–8 Accessing the Repository Root Level fro m WS_FTP95LE FTP Interface Program
Figure 3–9 Accessing the Repository Root Level from a Telnet Session
Figure 3–10 Accessing the Repository Using HTTP/WebDAV from Microsoft Windows Explorer
Figure 3–11 Accessing the Repository Using HTTP/WebDAV Protocol Server from Microsoft Web
Folders Client
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:
■ Chapter 4, "Using XMLType"
■ Chapter 5, "Structured Mapping of XMLType"
■ Chapter 6, "Transforming and Validating XMLType Data"
■ Chapter 7, "Searching XML Data with Oracle Text"
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:
■ What Is XMLType?
■ When to Use XMLType
■ Storing XMLType Data in Oracle XML DB
■ XMLType Member Functions
■ How to Use the XMLType API
■ Guidelines for Using XMLType Tables and Columns
■ Manipulating XML Data in XMLType Columns/Tables
■ Inserting XML Data into XMLType Columns/Tables
■ Selecting and Querying XML Data
■ Updating XML Instances and Data in Tables and Columns
■ Deleting XML Data
■ Using XMLType In Triggers
■ Indexing XMLType Columns
Note:
■ 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.
■ 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?
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:
■ XMLType can be used in PL/SQL stored procedures as parameters, return
values, and variables.
■ XMLType can represent an XML document as an instance (of XMLType) in SQL.
■ 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.
■ 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).
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 specific node(s) from an XMLType instance.
You can use XMLType in SQL queries in the same way as any other user-defined
datatypes in the system.
See Also:
■ "Oracle XML DB Offers Faster Storage and Retrieval of
Complex XML Documents" on page 1-21
■ Oracle9i SQL Reference Appendix D, “Using XML in SQL
Statements”
■ Indexing. 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.
See Also: Chapter 10, "Generating XML Data from the Database"
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 specification, 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.
■ In Structured storage (in tables and views). Structured storage maintains DOM
(Document Object Model) fidelity. Here the XML documents are ’broken up
(decomposed)’ into object- relational tables or views. XMLType achieves DOM
fidelity by maintaining information that SQL or Java objects normally do not
provide for, such as:
■ Ordering of child elements and attributes.
■ Distinguishing between elements and attributes.
■ Unstructured content declared in the schema. For example,
content="mixed” or <any> declarations.
■ Undeclared data in instance documents, such as processing instructions,
comments, and namespace declarations.
■ Support for basic XML datatypes not available in SQL (Boolean, QName,
and so on).
■ 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 fit 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 benefits.
See Also:
■ Chapter 2, "Getting Started with Oracle XML DB"
■ Chapter 3, "Using Oracle XML DB", "Storing XML: Structured
or Unstructured Storage" on page 3-24
■ Chapter 10, "Generating XML Data from the Database", for
information on how to generate XMLType data.
See Also:
■ Appendix F, "Oracle XML DB XMLType API, PL/SQL and
Resource PL/SQL APIs: Quick Reference"
■ Oracle9i XML API Reference - XDK and Oracle XML DB for a list
of all XMLType and member functions, their syntax, and
descriptions.
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.
schema .
CREATE TABLE table OF XMLTYPE
This section shows some simple examples of how to create an XMLType column and
use it in a SQL statement, and how to create XMLType tables.
CREATE TABLE po_xtab of XMLType; -- this creates a table of XMLType. The default
-- is CLOB based storage.
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.
Owned
This example created an XMLType instance from a string literal and updates column
warehouse_spec with the new value.
See Also:
■ "Selecting XMLType Columns using getClobVal()" on page 4-18
■ "Extracting Fragments from XMLType Using extract()" on
page 4-30
See Also:
■ "Indexing XMLType Columns" on page 4-38
■ Chapter 7, "Searching XML Data with Oracle Text"
■ Chapter 10, "Generating XML Data from the Database"
■ Oracle9i Application Developer’s Guide - Large Objects (LOBs)
STORE AS CLOB (
TABLESPACE lob_seg_ts
STORAGE (INITIAL 4096 NEXT 4096)
CHUNK 4096 NOCACHE LOGGING
);
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 identifies 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.
You can use the XMLDATA attribute in constraints and indexes, in addition to
storage clauses.
Example 4–13 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 define check constraints on XMLType columns. Other default values
are not supported on this datatype.
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.
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.
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>
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.
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 4–2 and also as
follows:
existsNode(XMLType_instance IN XMLType,
XPath_string IN VARCHAR2, namespace_string IN varchar2 := null)
RETURN NUMBER
, namespace
EXISTSNODE ( XMLType_instance , XPath_string )
<STATE>CA</STATE>
</SHIPADDR>
</PO>
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
, namespace
EXTRACT ( XMLType_instance , XPath_string )
extract() on XMLType extracts the node or a set of nodes from the document
identified 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 prefixes
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 identifies 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:
■ /PO/PNAME identifies the fragment <PNAME>PO_1</PNAME>
■ /PO/PNAME/text() identifies the text value “PO_1”
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>
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 4–4.
■ 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.
■ 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 from the 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.
, value_expr
EXTRACTVALUE ( XMLType_instance , XPath_string )
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()
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() Characteristics
extractValue() has the following characteristics:
■ It always returns only scalar content, such as NUMBER...VARCHAR2, and so
on.
■ 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.
■ It always returns VARCHAR2 by default. If the node’s value is bigger than 4K,
a runtime error would occur.
■ 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.
■ If the XPath identifies 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’)
Example 4–23 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
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()
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() finds nodes where “PONO” exists as a child of “PO”.
end;
/
Example 4–26 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)
);
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>
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;
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.
Example 4–27 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
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();
This SQL statement extracts the purchase order name “PNAME” from purchase 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”.
</SHIPADDR>
</PO>')
WHERE e.poDoc.EXTRACT('/PO/PONO/text()').getNumberVal() = 2001;
Note: This will also update the whole document, not just the part
updated.
UPDATE po_xml_tab
SET poDoc = UPDATEXML(poDoc,
’/PO/CUSTNAME/text()’, ’John’);
1 row updated
NEWPO
--------------------------------------------------------------------
<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>John</CUSTNAME>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
This updates all rows that have an employee element with the new values.
Example 4–34 Updating Customer Name in Purchase Order XML Document Using
updateXML()
The following example updates the customer name in the purchase order XML
document, po:
Note: This example only selects the document and the update
occurs on a transient XMLType instance. The original document is
not affected.
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>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
To generate a new document with Joe’s 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;
<EMP>
<EMPNO>412</EMPNO>
<EMPNAME>Jackson</EMPNAME>
<SALARY>40000</SALARY>
</EMP>
</EMPLOYEES>
ensures that users selecting from view, new_emp_view, do not see the SALARY
field for any employee.
NULL Updates When Object Types Are Generated by XML Schema Registration
NULL updates remove the element except when DOM fidelity is not maintained.
The clause:
updateXML(xmlcol,'/PO/shipAddr',null)
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>
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 4–5.
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 from the new
one then make it an invalid PO.
if updating then:
if :OLD.poDoc.extract('//PONO/text()').getNumberVal() !=
: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.
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.
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:
■ INPATH checks if the given word appears within the path specified.
■ HASPATH checks if the given XPath is present in the XML document.
See Also:
■ Chapter 7, "Searching XML Data with Oracle Text"
■ Chapter 10, "Generating XML Data from the Database"
■ Oracle Text Reference
■ Oracle Text Application Developer’s Guide
See Also:
■ Chapter 7, "Searching XML Data with Oracle Text"
■ Chapter 10, "Generating XML Data from the Database"
■ Oracle Text index also supports certain predicate expressions with string
equality, but cannot support numerical and range comparisons.
■ 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>
<E>
</E>
</D>
</A>
the XPath expression - A/B/E falsely matches the preceding XML document.
■ Both the function-based indexes and Oracle Text indexes support navigation.
Thus you can use the Oracle Text index as a primary filter, to filter out all
documents that potentially match the criterion, efficiently, and then apply
secondary filters such as existsNode() or extract() operations on the
remainder of the XML documents.
This chapter introduces XML Schema and explains how XML schema is used in
Oracle XML DB applications. It describes how to register your XML schema, create
storage structures for storing schema-based XML, and generate Java Beans to access
and manipulate data in Java applications.
It explains in detail the mapping from XML to SQL storage types, including
techniques for maintaining the DOM fidelity 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:
■ Introducing XML Schema
■ XML Schema and Oracle XML DB
■ Using Oracle XML DB and XML Schema
■ Introducing DBMS_XMLSCHEMA
■ Registering Your XML Schema Before Using Oracle XML DB
■ Deleting Your XML Schema Using DBMS_XMLSCHEMA
■ Guidelines for Using Registered XML Schemas
■ Java Bean Generation During XML Schema Registration
■ Generating XML Schema Using DBMS_XMLSCHEMA.generateSchema()
■ XML Schema-Related Methods of XMLType
■ Managing and Storing XML Schema
■ DOM Fidelity
</element>
<element name="Price" type="float"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<element name="PurchaseOrder" type="po:PurchaseOrderType"/>
</schema>
Note:
The URL ’http://www.oracle.com/PO.xsd’ used here is
simply a name that uniquely identifies 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 from the XML schema
location URL, that specifies 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 schema’s URL.
An XML instance document must specify both the namespace of
the root element (same as the XML schema’s target namespace) and
the location (URL) of the XML schema that defines this root
element. The location is specified with attribute
xsi:schemaLocation. When the XML schema has no target
namespace, use attribute xsi:noNamespaceSchemaLocation to
specify the XML schema URL.
When using Oracle XML DB, you must first 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:
■ Registering any W3C-compliant XML schemas.
■ 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 flexibility for storing
highly structured or unstructured data.
Introducing DBMS_XMLSCHEMA
Oracle XML DB’s XML schema functionality is available through the PL/SQL
supplied package, DBMS_XMLSCHEMA, a server-side component that handles the
registration of XML schema definitions for use by Oracle XML DB applications.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
<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>
</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
specifies the schema URL:
insert into po_tab values (1,
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>’));
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
/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 file:
/sys/schemas/SCOTT/www.oracle.com/PO.xsd
Such XML schemas are referred to as local. In general, they are usable only by you
to whom they belong.
Note: Typically, only the owner of the XML schema can use it to
define XMLType tables, columns, or views, validate documents, and
so on. However, Oracle supports fully qualified XML schema URLs
which can be specified 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.
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).
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:
■ 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-defined attributes in XML schema documents to control how these object
types are generated.
■ 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.
See Also:
■ "Specifying SQL Object Type Names with SQLName, SQLType
Attributes" on page 5-25
■ Chapter 3, "Using Oracle XML DB"
■ Creating Java beans: Java beans can be optionally generated during XML
schema registration. These Java classes provide accessor and mutator methods
for elements and attributes declared in the schema. Access using Java beans
offers better performance for manipulating XML when the XML schema is well
known. This helps avoid run-time name translation.
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, default tables, and Java beans
as part of a previous call to register schema.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
the chapter on DBMS_XMLSCHEMA.
EXEC dbms_xmlschema.deleteSchema(’http://www.oracle.com/PO.xsd’,
dbms_xmlschema.DELETE_CASCADE_FORCE);
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>’));
if xmldoc.isschemavalidated() = 1 then
dbms_output.put_line(’Data is valid’);
else
dbms_output.put_line(’Data is invalid’);
end if;
end;
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 qualified XML schema URLs. In this form, the name of the
database user owning the XML schema is also specified 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>
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 qualified URL for the global XML schema is:
http://xmlns.oracle.com/xdb/schemas/PUBLIC/www.example.com/po.xsd
Example 5–10 Generating Java Bean Classes During XML Schema Registration
For example, the Java bean class corresponding to the XML schema PO.xsd has the
following accessor and mutator methods:
public class PurchaseOrder extends XMLTypeBean
{
public BigDecimal getPONum()
{
....
}
public void setPONum(BigDecimal val)
{
....
}
public String getCompany()
{
....
}
public void setCompany(String val)
{
....
}
....
}
They can also optionally generate annotated XML schemas that can be used to
register the XML schema with Oracle XML DB.
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 from http://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
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>
See Also:
■ Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
■ Appendix A, "Installing and Configuring Oracle XML DB"
Design criteria for storing XML data are discussed inChapter 2, "Getting Started
with Oracle XML DB" and Chapter 3, "Using Oracle XML DB".
DOM Fidelity
Document Object Model (DOM) fidelity is the concept of retaining the structure of a
retrieved XML document, compared to the original XML document, for DOM
traversals. DOM fidelity is needed to ensure the accuracy and integrity of XML
documents stored in Oracle XML DB.
schema .
CREATE TABLE table OF XMLTYPE
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.
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.
All annotations are in the form of attributes that can be specified within attribute
and element declarations. These attributes belong to the Oracle XML DB
namespace: http://xmlns.oracle.com/xdb
Table 5–2 lists Oracle XML DB attributes that you can specify in element and
attribute declarations.
Table 5–3 Attributes You Can Specify in Elements Declaring Global complexTypes
Attribute Values Default Description
SQLType Any SQL type name Name generated from Specifies the name of the SQL type
element name corresponding to this XML
element declaration.
SQLSchema Any SQL username User registering XML Name of database user owning the type
schema specified by SQLType.
beanClassname Any Java class name Generated from Can be used within element declarations.
element name. 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 specified 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 fidelity
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.
Example 5–14 Capturing SQL Mapping Using SQLType and SQLName Attributes
The following XML schema definition 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>
</sequence>
</complexType>
<element name="PurchaseOrder" type="po:PurchaseOrderType"/>
</schema>’;
begin
dbms_xmlschema.registerSchema(’http://www.oracle.com/PO.xsd’, doc);
end;
Figure 5–2 shows how Oracle XML DB creates XML schema-based XMLType tables
using an XML document and mapping specified in an XML schema. An XMLType
table is first created and depending on how the storage is specified 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.
Figure 5–2 How Oracle XML DB Maps XML Schema-Based XMLType Tables
Here the whole XML document or parts Here the XML elements are mapped
of it are stored in CLOBs in tables. to columns in tables.
An XMLType table is first created and depending on how the storage is specified 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.
■ Local complexType.
.
.
.
<element name = "Resume" type = "string">
.
.
.
Entire resume
value is stored
in the CLOB
.
.
.
<element name = "Addr" xdb : SQLInLine = "false">
.
.
.
</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)
);
Example 5–16 Oracle XML DB XML Schema: complexType Mapping XML Fragments
to LOBs
In the following example, the XML schema specifies that the XML fragment’s
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"
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
);
.
.
.
<element name = "Addr" xdb : SQLType = "CLOB">
.
.
.
CLOB
Street and
city are stored
in the CLOB
because SQL does not support restriction of object types through the
inheritance mechanism. Any constraints are imposed by the restriction in XML
schema.
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;
</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)
);
</sequence>
</complexType>
</schema>’;
begin
dbms_xmlschema.registerSchema(’http://www.oracle.com/emp.xsd’, doc);
end;
<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 definitions. However, they support weak
cycles, that is, cycles involving REF (references) attributes. Therefore, cyclic XML
schema definitions 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;
Figure 5–6 Cross Referencing Between Different complexTypes in the Same 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.
■ XML notation
CREATE TABLE MyPOs P OF XMLTYPE
ELEMENT
"http://www.oracle.com/PO.xsd#PurchaseOrder"(unique(ExtractValue(p,'/ponum')
);
enables the XPath to be evaluated against the XML document without having to
ever construct the XML document in memory.
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.
Here are some examples of statements that get rewritten to use underlying
columns:
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.
Table 5–10 Supported XPath Expressions for Translation to Underlying SQL Queries
XPath Expression for Translation Description
Simple XPath expressions: Involves traversals over object type attributes only, where the attributes
are simple scalar or object types themselves. The only axes supported
/PurchaseOrder/@PurchaseDate
are the child and the attribute axes.
/PurchaseOrder/Company
Collection traversal expressions: Involves traversal of collection expressions. The only axes supported are
child and attribute axes. Collection traversal is not supported if the SQL
/PurchaseOrder/Item/Part
operator is used during CREATE INDEX or updateXML().
Predicates: Predicates in the XPath are rewritten into SQL predicates. Predicates are
not rewritten for updateXML()
[Company="Oracle"]
List indexe: Indexes are rewritten to access the n’th item in a collection. These are
not rewritten for updateXML().
lineitem[1]
Unsupported XPath Constructs The following XPath constructs do not get rewritten:
■ XPath Functions
■ XPath Variable references
■ All axis other than child and attribute axis
■ Wild card and descendant expressions
■ 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:
■ 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 specified in the XPath. any attributes are handled in a similar way.
■ CLOB storage. If the XML schema maps part of the element definitions to an
SQL CLOB, then XPath expressions traversing such elements are not supported.
■ Enumeration types.
■ Substitutable elements.
<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;
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 fidelity. 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.
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.
Mapping for a Simple XPath A rewrite for a simple XPath involves accessing the
attribute corresponding to the XPath expression. Table 5–11 lists the XPath map:
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.
from mypos p
where existsNode(value(p),’/PurchaseOrder[PONum=1001 and Company = "Oracle
Corp"]’) =1;
Document Ordering with Collection Traversals Most of the rewrite preserves the original
document ordering. However, since the SQL system does 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.
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 fixed in future releases.
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.
When performing query rewrite, the namespace for a particular element is matched
with that of the XML schema definition. 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 specification
or by prefixing each node with a namespace prefix).
If the elementFormDefault is unqualified (which is the default), then only the
node that defines the namespace should contain a prefix. For instance if the PO.xsd
had the element form to be unqualified, then the existsNode() function should
be rewritten as:
EXISTSNODE(value(p),’/a:PurchaseOrder/PONum’,
’xmlns:a="http://www.oracle.com/PO.xsd") = 1;
Date Format Conversions The default date formats are different for XML schema and
SQL. Consequently, when rewriting XPath expressions involving comparsions with
dates, you need to use XML formats.
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.
existsNode Mapping with Document Order Maintained Table 5–12 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.
Table 5–12 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 = CASE WHEN XMLData."PONum" = 2100 AND Check_Node_Exists(XMLData.SYS_XDBPD$,
2100]/@PurchaseDate ’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
would become:
SELECT count(*)
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 specifies maintainDOM="false") then NULL
scalar columns map to non-existant scalar elements. Hence you do not need to
check for the node existance using the SYS_XDBPD$ attribute. Table 5–13 shows the
mapping of existsNode() in the absence of the SYS_XDBPD$ attribute.
Table 5–13 XPath Mapping for existsNode Without Document Ordering (Cont.)
XPath Expression Maps to
/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
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.
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;
Extract Mapping with Document Order Maintained Table 5–15 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).
Table 5–15 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)
Table 5–15 XPath Mapping for extract() with Document Ordering Preserved (Cont.)
XPath Maps to
/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 )
Example 5–37 XPath Mapping for extract() with Document Ordering Preserved
Using the mapping in Table 5–15, 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;
Extract Mapping Without Maintaining Document Order If the SYS_XDBPD$ does not exist,
that is, if the XML schema specifies maintainDOM="false", then NULL scalar
columns map to non-existant scalar elements. Hence you do not need to check for
the node existance using the SYS_XDBPD$ attribute. Table 5–16 shows the mapping
of existsNode() in the absence of the SYS_XDBPD$ attribute.
Table 5–16 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 = (SELECT XMLForest(XMLData."PurchaseDate" AS "")
2100]/@PurchaseDate 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 )
■ The XMLType column must have been stored object relationally using Oracle
XML DB’s XML schema mapping.
■ The XPath expressions must not involve any predicates or collection traversals.
■ There must be no duplicate scalar expressions.
■ 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 satisfied, 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 specified for DATE
columns, must match the XML date format and not the SQL DATE format.
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.
Now create the second XML schema with FORCE option. This should also make the
first 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)
The second operation automatically compiles s1.xsd and makes both XML
schemas valid.
See Figure 5–8. The preceding example is illustrated in the lower half of the figure.
S3 S1
XML schema 3, S3
References References
S2
OR
References
S2 S1
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:
■ Transforming XMLType Instances
■ XMLTransform() Examples
■ Validating XMLType Instances
■ Validating XML Data Stored as XMLType: Examples
See Also:
■ Appendix D, "XSLT Primer"
■ Oracle9i XML Developer’s Kits Guide - XDK, the chapter on XSQL
Pages Publishing Framework.
Figure 6–2 shows how XMLTransform() transforms the XML document by using
the XSL stylesheet passed in. It returns the processed output as XML, HTML, and so
on, as specified by the XSL stylesheet. You typically need to use XMLTransform()
when retrieving or generating XML documents stored as XMLType in Oracle9i
database.
XMLType function
XSL stylesheet
XMLtransform() transformed XMLType
XMLType instance (HTML, XML, ...)
(table, cloumn, view)
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"/>
<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}"/>
</restriction>
</simpleType>
</schema>’,
TRUE, TRUE, FALSE);
end;
/
</ipo:purchaseOrder>’));
SELECT XMLTransform(x.xmlcol,
dburiType(’/SCOTT/STYLESHEET_TAB/ROW[ID =
1]/STYLESHEET/text()’).getXML()).getStringVal()
AS result
FROM po_tab x;
SELECT XMLTransform(x.xmlcol,
(select stylesheet from stylesheet_tab where id = 1)).getStringVal()
AS result
FROM po_tab x;
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;
XMLIsValid()
XMLIsValid() is an SQL Operator. It checks if the input instance conforms to a
specified XML schema. It does not change the validation status of the XML instance.
If an XML schema URL is not specified and the XML document is schema-based,
the conformance is checked against the XMLType instance’s own schema. If any of
the arguments are specified 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:
■ XMLType_inst - The XMLType instance to be validated against the specified
XML Schema.
■ schurl - The URL of the XML Schema against which to check conformance.
■ elem - Element of a specified schema, against which to validate. This is useful
when we have a XML Schema which defines more than one top level element,
and we want to check conformance against a specific 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 document’s 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.
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 specified XML schema. It does not change the validation status of the XML
instance. If an XML Schema URL is not specified and the XML document is
schema-based, the conformance is checked against the XMLType instance’s 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 specified schema, against which to validate. This is useful when
we have a XML Schema which defines more than one top level element, and we
want to check conformance against a specific one of these elements.
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;
/
This chapter explains the use of Oracle Text functionality in indexing and querying
XML data. It contains the following sections:
■ Searching XML Data with Oracle Text
■ Introducing Oracle Text
■ Assumptions Made in This Chapter’s Examples
■ Oracle Text Users and Roles
■ Querying with the CONTAINS Operator
■ Using the WITHIN Operator to Narrow Query Down to Document Sections
■ Introducing SECTION_GROUPS
■ INPATH or HASPATH Operators Search Using XPath-Like Expressions
■ Building a Query Application with Oracle Text
■ Step 1. Create a Section Group Preference
■ Step 2. Set the Preference’s Attributes
■ Step 3. Create an Index Using the Section Preference Created in Step 2
■ Step 4. Create Your Query Syntax
■ Presenting the Results of Your Query
■ XMLType Indexing
■ Using Oracle Text with Oracle XML DB
■ Full-Text Search Functions in XPath Using ora:contains
■ Oracle XML DB: Creating a Policy for ora:contains()
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 file system and URLs.
Oracle Text enables the following:
■ Content-based queries, such as, finding text and documents which contain
particular words, using familiar, standard SQL.
■ File-based text applications to use Oracle9i to manage text and documents in an
integrated fashion with traditional relational information.
■ Concept searching of English language documents.
■ Theme analysis of English language documents using the theme/gist package.
■ 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.
■ With Oracle Text 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.
See Also :
■ Oracle Text Reference
■ Oracle Text Application Developer’s Guide
■ http://otn.oracle.com/products/text
See Also:
■ Oracle Text Application Developer’s Guide
■ Oracle Text Reference, for more information on these parameter
types.
User CTXSYS
User CTXSYS is created at install time. Administer Oracle Text users as this user.
User CTXSYS has the following privileges:
■ Modify system-defined preferences
■ Drop and modify other user preferences
■ Call procedures in the CTX_ADM PL/SQL package to start servers and set
system-parameters
■ Start a ctxsrv server
■ Query all system-defined views
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-defined role that enables you to
perform the following tasks:
■ Create and delete Oracle Text preferences
■ Use Oracle Text PL/SQL packages, such as the CTX_DDL package
CONTAINS Syntax
Here is the CONTAINS syntax:
...WHERE CONTAINS([schema.]column,text_query VARCHAR2,[label NUMBER])
where:
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.
Note: You must use the SCORE operator with a label to obtain
this number.
The ’receipts’ parameter of the CONTAINS operator is called the “Text Query
Expression”.
Example 7–2 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 row is 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 specifies
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: This is only true for XML_SECTION_GROUP, but not true for
AUTO_ or PATH_SECTION_GROUP.
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:
■ Zone sections
■ Field sections
■ Attribute section
■ 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
Developer’s Guide.
When you define Zone section as such and index the document set, you can query
the XML chapter Zone section as follows:
'Cities within chapter'
When you define Field section as such and index the document set, you can query
the XML abstract Field section as follows:
'Cities within abstract'
When you define the Attribute section as such and index the document set, you can
query the XML booktitle attribute text as follows:
'Cities within booktitle'
querying on Tale will not work unless qualified with ’WITHIN title@book’.
■ You cannot use Attribute or Field sections in a nested WITHIN query.
■ 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 query’s, “good men”, and ignore the
intervening attribute text.
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.
This searches for expression text within a section. If you are using XML_SECTION_
GROUP the following restrictions apply to the pre-defined zone, field, or attribute
section:
■ If section is a zone, expression can contain one or more WITHIN operators
(nested WITHIN) whose section is a zone or special section.
■ If section is a field or attribute section, expression cannot contain another
WITHIN operator.
You can combine and nest WITHIN clauses. For finer grained searches of XML
sections, you can use WITHIN clauses inside CONTAINS select statements.
Path Indexing
Section searching is enabled by defining 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;
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.
Table 7–2 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”
virginia INPATH (//STATE) appears between <STATE> and </STATE>. The
STATE element can appear at any level of the
document structure.
Case-sensitivity virginia INPATH (STATE) Tags and attribute names in path searching are
virginia INPATH (State) case-sensitive. virginia INPATH STATE -- finds
<STATE>virginia</STATE> but NOT
<State>virginia</State>. To find the latter
you must do virginia INPATH State.
Top-Level Tag virginia INPATH (Legal) Finds all documents where “virginia” appears in a
Searching virginia INPATH (/Legal) 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
For example, the following intervening tags. For example:
query finds Quijote where it <?xml version=”1.0” standalone=”yes”?>
occurs between <order> and
<!-- <?xml-stylesheet type=”text/xsl"
</order>: href="./xsl/vacourtfiling(html).xsl"?> -->
select id from library_catalog where <Legal>
contains(text,'Quijote INPATH(order)') >
<CourtFiling>
0;
<Filing ID="f001" FilingType="Civil">
<LeadDocument>
Here <order> must be the top
level tag. <CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState>VIRGINIA</AddressState>
</Address> ... </Legal>
Table 7–2 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
Any Level Tag virginia INPATH (//Address) 'Virginia' can appear anywhere within an 'Address'
Searching tag, which may appear within any other tags. for
example:
For example,a double slash
indicates "any number of levels" <?xml version="1.0" standalone="yes"?>
down. The following query finds <!-- <?xml-stylesheet type="text/xsl"
Quijote inside a <title> tag that href="./xsl/vacourtfiling(html).xsl"?> -->
occurs at the top level or any <Legal>
lower level:
<CourtFiling>
select id from library_catalog <Filing ID="f001" FilingType="Civil">
where contains(text,'Quijote <LeadDocument>
INPATH(//title)') > 0;
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState> VIRGINIA </AddressState>...
</Legal>
Direct Parentage Path virginia INPATH Finds all documents where “virginia” appears in a
Searching (//CourtInformation/Location) Location element which is a direct child of a
for example: CourtInformation element. For example:
Table 7–2 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
Single-Level Wildcard virginia INPATH(A/*/B) Finds all documents where “virginia” appears in a B
Searching 'virginia INPATH element which is a grandchild of an A element. For
(//CaseCaption/*/Location)' 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/vacourtfiling(html).xsl"?> -->
<Legal>
<CourtFiling>
<Filing ID="f001" FilingType="Civil">
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState>VIRGINIA</AddressState>...
</Legal>
Table 7–2 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
Multi-level Wildcard 'virginia INPATH 'Legal' must be a top-level tag, and there must be
Searching (Legal/*/Filing/*/*/CourtInformation)' 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/vacourtfiling(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 7–2 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
Descendant/Attribute virginia INPATH (A[B]) Finds all documents where “virginia” appears in an
Existence Testing A element which has a B element as a direct child.
You can search for documents ■ virginia INPATH A[.//B] -- Finds all
using the any-level tag documents where “virginia” appears in an A
searching: element which has a B element as a descendant
(any level).
select id from library_catalog where
contains (text,'Quijote ■ virginia INPATH A[@B] -- Finds all documents
INPATH(/order/title)') > 0; where “virginia” appears in an A element
which has a B attribute
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;
Table 7–2 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature Syntax Description
Attribute Value virginia INPATH A[@B = “foo”] Finds all documents where “virginia” appears in an
Testing A element which has a B attribute whose value is
“foo”.
■ Only equality is supported as a test. Range
operators and functions are not supported.
■ The left-hand-side of the equality MUST be an
attribute or tag. Literals here are not allowed.
■ The right-hand-side must be a literal. Tags and
attributes here are not allowed.
Within equality (See "Using INPATH Operator for
Within Equality That means that:
Path Searching in XML Documents" on page 7-12) is
virginia INPATH (A[@B = "pot of used to evaluate the test.
gold”]), would, with the default Whitespace is mainly ignored in text indexing.
lexer and stoplist, match any of Again, lexing is case-independent:
the following:
<A B=”pot_of_gold”>virginia</A>
<A B="POT OF GOLD">virginia</A>
Underscore is a non-alphabetic character, and is not
By default, lexing is a join character by default. As a result, it is treated
case-independent, so “pot” more or less as whitespace and breaks up that string
matches “POT”, <A B="POT into three words.
BLACK GOLD”>virginia</A>
Example:
By default, “of” is a stopword,
and, in a query, would match select id from library_catalog where contains(text,'(Bob the
any word in that position, <A Builder) INPATH(//item[@type="dvd"])') > 0;
B=" Pot OF Gold The following will not return rows:
“>virginia</A>
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]) Predicates can be conjunctively combined.
virginia INPATH (A[B AND @C =
“foo”])...
Combining Path and virginia INPATH (A[@B = “foo”]/C/D) Node tests can be applied to any node in the path.
Node Tests virginia INPATH(A//B[@C]/D[E])...
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.
Only use the HASPATH operator when your index has been created with the PATH_
SECTION_GROUP. The syntax for the HASPATH operator is:
■ WHERE CONTAINS(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;
finds and returns a score of 100 only for the first document, and not the second.
Table 7–4 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 know the layout and structure of Yes -- --
your XML documents, and you can
predefine the sections on which users
are most likely to search.
You do not know which tags users -- Yes --
are most likely to search.
Query performance, in general Fastest Little slower than Little slower than
XML_section_... AUTO_section_...
Indexing performance, in general Fastest Little slower than Little slower than
XML_section_... AUTO_section_...
Index size Smallest Little larger than Little larger than
XML_section_... AUTO_section_...
Other features Mappings can be Simplest. No need to Designed for more
defined so that tags in define mapping, add_ sophisticated XPATH-
one or different DTDs stop_section can be like queries
can be mapped to one used to ignore some
section. Good for DTD sections.
evolution and data
aggregation.
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');
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.
where ’my_tag’ implies opening with <my_tag> and closing with </my_tag>.
add_zone_section Guidelines
add_zone_section guidelines are listed here:
■ Call CTX_DDL.Add_Zone_Section for each tag in your XML document that
you need to search on.
where ’my_tag’ implies opening with <my_tag> and closing with </my_tag>.
Add_Attr_Section Guidelines
Add_Attr_Section guidelines are listed here:
■ 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 defining attributes in XML documents as sections. This
enables searching XML attribute text with the WITHIN operator.
The section_name:
■ Is the name used for WITHIN queries on the attribute text.
Add_Field_Section Guidelines
Add_Field_Section guidelines are listed here:
■ Searches using Field_Sections are faster than those using Zone_Section.
■ 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 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 );
does NOT find 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 find the document, because "jeeves" and "bertram" do not occur
within the SAME attribute text.
■ Attribute section names cannot overlap with zone or field 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>
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.
...
/
/* 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. */
You can define 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 define 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 define the AUTHOR attribute section as such and index the document
set, you can query the XML attribute text as follows:
... WHERE 'England WITHIN authors'
---
--- script to create index on res_xml
---
begin
ctx_ddl.create_preference
(
preference_name => 'my_basic_lexer',
object_name => 'basic_lexer'
);
ctx_ddl.set_attribute
(
Example 7–6 Text Query Using "ABOUT" in the Text Query Expression
Set Define Off
select text
from explain_ex
Note:
■ 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.
■ 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
The Oracle9i datatype for storing XML, XMLType, is a core database feature.
You can create an Oracle Text index on this type, but you need a few database
privileges first:
1. The user creating the index must have Query Rewrite privileges:
GRANT QUERY REWRITE TO <user>
<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 file:
query_rewrite_enabled=true
query_rewrite_integrity=trusted
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.
INDEXTYPE IS ctxsys.context;
ALTER SESSION SET query_rewrite_enabled = true;
ALTER SESSION SET query_rewrite_integrity = trusted;
Table 7–5 lists system parameters used for default preference names for Oracle Text
indexing, when the column type is URIType:
Table 7–5 riType 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
Note: This release does not support theme querying for Oracle
Text CONTAINS() and existsNode() searching.
Table 7–6 lists and compares CONTAINS() and existsNode() features for
searching XMLType data.
Table 7–6 Using CONTAINS() and existsNode() to Search XMLType Data (Cont.)
Feature CONTAINS() existsNode()
■ Attribute searching Y Y
under wildcards. For
example, */@A or ../
■ Uses XML schema or N Y
DTD information
■ Empty elements may Y N
lead to false matches
Synchronous -- --
■ DML N CTXXPath = N
Other indexes = Y
■ 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
■ About Y N
■ Highlighting Y N
Text searching in general Supports full text Supports limited text
searching. searching with
ora:contains.
XPath searching in general Limited XPath Full XPath searching.
searching. Synchronous.
Non-synchronous.
ora:contains Features
The followig lists the ora:contains features:
■ The text search extension functions support most of text query operators such
as stemming, fuzzy matching, and proximity search.
■ These functions do not require a ConText index for their evaluation.
■ 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 fixed to 10. This means that a
score for a word search is the number of occurence 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:
■ string, the first argument is input text value
■ string, the second argument is the text query string
■ string?, the optional third argument is the policy name
■ string?, the optional fourth argument is the policy owner
The contains extension function in the Oracle XML DB namespace, takes the
input text value as the first 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 specified, it defaults to the CTX policy named DEFAULT_
POLICY_ORACONTAINS owned by CTXSYS. If the fourth argument is not specified,
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 7–13 Using ora:contains and extract() to Find a Text Query String
Extract chapters whose body contains the specified 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;
See Also:
■ Oracle Text Application Developer’s Guide
■ Oracle Text Reference
for a description of the Oracle Text preferences.
Table 7–7 describes the CTX_DDL functions for creating, updating, and dropping
policies for use in your XPath searches.
Table 7–7 CTX_DDL Syntax for Creating, Updating, and Dropping Policies
CTX_DDL Function Description
CREATE_POLICY Defines a policy.
CTX_DDL.create_policy(policy_name in varchar2, filter Arguments:
in varchar2 default NULL, section_group in varchar2 default
NULL, lexer n varchar2 default NULL, stoplist in varchar2 policy_name - the name for the new policy
default NULL, wordlist in varchar2 default NULL); filter - the filter 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 Updates a policy by replacing specified preferences.
CTX_DDL.update_policy( policy_name in varchar2, filter Arguments:
in varchar2 default NULL, section_group in varchar2 default
NULL, lexer in varchar2 default NULL, stoplist in varchar2 policy_name - the name for the policy
default NULL, wordlist in varchar2 default NULL); filter - the new filter preference to use (reserved for future
use)
section_group - the new section group to use (currently only
NULL_SECTION_GROUP is supported)
lexer - the new lexer 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 Deletes a policy.
CTX_DDL.drop_policy(policy_name in varchar2); Arguments:
policy_name - the name of the policy
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 defined
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;
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:
■ For the ConText index to be usable as a primary filter for existsNode(),
■ You must create the index using PATH_SECTION_GROUP.
■ You cannot create the index with USER_LEXER or MULTI_LEXER
preference.
■ You must create the index with DIRECT DATASTORE.
■ You must create the index with NULL FILTER.
This limits the linguistic searching capabilities that ConText index type
provides.
■ The ConText index is asynchronous and does not follow the same
transactional semantics as existsNode().
■ The ConText index does not handle namespaces nor user-defined entities.
With all these limitations in mind, CTXXPATH index type was designed specifically
to serve the purpose of existsNode() primary filter 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().
where
paramstring = ’[storage storage_pref] [memory memsize] [populate | nopopulate]’
or
CREATE INDEX xml_idx ON xml_tab(col_xml) indextype is ctxsys.CTXXPATH
PARAMETERS(’storage my_storage memory 40M’);
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’);
See Also:
■ Oracle Text Application Developer’s Guide
■ Oracle Text Reference
This is fine until you have a different kind of document in the same table:
<!DOCTYPE mail>
<mail>
<address>dudeman@radical.com</address>
</mail>
Now your address section, originally intended for street addresses, starts picking
up email addresses, because of tag collision.
Now when 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.
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,
finds documents independent of which tags are used to express the email address.
<comment author="jeeves">
I really like Oracle Text
</comment>
The syntax is similar to other add_section calls. The first 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...’,...)...
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 field section named asec using the tag author:
alter index <indexname> rebuild
parameters ('add field section asec tag author')
This field section would be invisible by default, just like when using ADD_FIELD_
SECTION. To add it as visible field section:
alter index <indexname> rebuild
parameters ('add field section asec tag author visible')
Dynamic add section only modifies 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.
A query on Tale by itself does not produce a hit on the document unless
qualified with WITHIN title@book. This behavior is like field sections when you
set the visible flag set to false.
■ You cannot use attribute sections in a nested WITHIN query.
■ 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 field 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>
This query does not hit the document, because tale and bondage are in different
occurrences of the attribute section book@author.
does not.
Nested Sections
Zone sections can nest, including themselves as follows:
<TD>
<TABLE>
<TD>nested cell</TD>
</TABLE>
</TD>
Using the WITHIN operator, you can write queries to search for text in sections
within sections.
doc2:
<book2> <author>Scott Tiger</author> This is a great book to read.</book2>
...
Describe ctx_object_attributes
SELECT oat_attribute FROM ctx_object_attributes
WHERE oat_object = 'XML_SECTION_GROUP';
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:
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 7–1 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 7–2 shows the search results.
For the .jsp code to build this look-up application, see "Searching Conference
Proceedings Example: jsp" on page 7-60.
See Also:
■ Oracle Text Reference
■ Oracle Text Application Developer’s Guide
■ http://otn.oracle.com/products/text
Figure 7–1 Using Oracle Text to Search for “Libraries” in the Conference Proceedings Abstracts
<%
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>
</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>
</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")+")";
// select p.papers.extract('/paper/authors').getStringVal()
// from oowpapers p
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>
<% } %>
}
} 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>
<%
}
%>
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.
Can value (lee, jumee) be queried by elements, attributes, and the structure of
XML document?
Answer: Using Oracle Text, you can find this document with a queries such as:
lee within first
jumee within second
1111 within name@id
For more information, please read the Oracle Text Technical Overview available on
OTN at http://otn.oracle.com/products/text
■ I can create <Zones> and <Fields> to represent the tags in my XML file Ex.
ctx_ddl.add_zone_section(xmlgroup,”dublincore”, dc);
■ I can search for text within a zone or fieldEx. Select title from mytable where
CONTAINS(textField,”some words WITHIN doubleness”)
How do I return a zone or a field 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.
<childrens>
<child>
<id>1</id>
<name>keren</name>
</child>
</childrens>
</person>
How do I find the person who has a child name keren but not the person's name
keren? This assumes I defined every tag with the add_zone_section that can be
nested and can include themselves.
Answer: Use ’(keren within name) within child’.
2 (8.1.6) or higher, then you also have the option of placing XML tags around
each field prior to concatenation. This gives you the capability of searching
within each field.
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 filters 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:
■ Will Oracle8i or Oracle9i be any faster at indexing text than mySQL?
■ 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 filter documents if they are already in ASCII, HTML, or XML, and most
common expansions, like fuzzy, stemming, and proximity, are done at query time.
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
('section group mygrp');
select * from mytab where contains(mytxtcolumn, 'aorta within keyword')>0;
options:
■ Use XML section group instead of basic section group if your tags have
attributes or you need case-sensitive tag detection.
■ Use zone sections instead of field sections if your sections overlap, or if you
need to distinguish between instances. For instance, if keywords is a field
section, then (aorta and echo cardiogram) within keywords finds
the document. If it is a zone section, then it does not, because they are not in the
SAME instance of keywords.
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.
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.
I need to search on the 'author' zone section by the first letter only. I believe I should
use a substring index but I am unsure of the syntax to create a substring index.
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
becomes
<AUTHORINIT>AIK</AUTHORINIT><AUTHOR>Steven King<AUTHOR>
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.
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);
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');
ENd;
/
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” confidence=”100”/>
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....
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 filter or user
datastore), use zone sections, and nested withins, so that:
<A B="C" D="E">...
became
<A><B>C</B><D>E</D>...
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:
■ Chapter 8, "PL/SQL API for XMLType"
■ Chapter 9, "Java and Java Bean APIs for XMLType"
8
PL/SQL API for XMLType
This chapter describes the use of the APIs for XMLType in PL/SQL. It contains the
following sections:
■ Introducing PL/SQL APIs for XMLType
■ PL/SQL DOM API for XMLType (DBMS_XMLDOM)
■ PL/SQL Parser API for XMLType (DBMS_XMLPARSER)
■ PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
The read-from and write-to files must be on the server file system.
■ PL/SQL XML Parser API for XMLType (package DBMS_XMLPARSER): For
accessing the contents and structure of XML documents.
■ PL/SQL XSLT Processor for XMLType (package DBMS_XSLPROCESSOR): For
transforming XML documents to other formats using XSLT.
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 Developer’s Kits (XDK).
■ PL/SQL APIs 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.
■ Oracle XML XDK for PL/SQL. Use Oracle XDK for PL/SQL for middle-tier and
client-side XML support.
See Also:
■ "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.
■ Chapter 4, "Using XMLType"
■ Oracle9i XML API Reference - XDK and XDB
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 identified by start-tags, as in <name>, and end-tags, as in
</name>, or in the case of empty elements, <name/>.
If you use the PL/SQL DOM API, you can use the NamedNodeMap methods to
retrieve elements from an XML file.
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.
■ 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 briefly describe each level:
■ DOM Level 1.0. The first formal Level of the DOM specifications, completed in
October 1998. Level 1.0 defines support for XML 1.0 and HTML.
■ DOM Level 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).
■ DOM Level 3.0. Currently under development, Level 3.0 will extend Level 2.0
by finishing 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.
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 file systems.
See Also: Chapter 9, "Java and Java Bean APIs for XMLType"
■ XSLT Processor: Transforms or renders XML into other text-based formats such
as HTML.
■ XML Schema Processor: Supports Java, C, and C++, allows use of XML simple
and complex datatypes.
■ XML Class Generator: Automatically generates Java and C++ classes from
DTDs and Schemas to send XML data from Web forms or applications.
■ XML Transviewer Java Beans: Displays and transforms XML documents and
data using Java components.
■ XML SQL Utility: Supports Java, generates XML documents, DTDs and
Schemas from SQL queries.
■ TransXUtility. Loads data encapsulated in XML into the database with
additional functionality useful for installations.
■ XSQL Servlet: Combines XML, SQL, and XSLT in the server to deliver dynamic
web content.
■ 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.
See Also:
■ Oracle9i Supplied PL/SQL Packages and Types Reference
■ Oracle9i XML API Reference - XDK and XDB
Table 8–2 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
Table 8–2 XML and HTML DOM Node Types and Corresponding Children Node Types (Cont.)
Node Type Children Node Types
CDATASection No children
Entity Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
Notation No children
Oracle XML DB DOM API for XMLType also specifies these interfaces:
■ 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
■ A NamedNodeMap interface to handle unordered sets of nodes, referenced by
their name attribute, such as the attributes of an element.
XMLType
newDOMDocument newDOMDocument
(Empty
document)
DOMDocument
makeNode
DOMNode Interface
nodelist dbms_xmldom.DOMNodelist;
buf varchar2(2000);
begin
var := xmltype(’<PERSON> <NAME> ramesh </NAME> </PERSON>’);
dbms_xmldom.writetobuffer(ndoc, buf);
dbms_output.put_line(’Before:’||buf);
-- 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;
/
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;
/
-- 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;
/
newParser
Parser
getDocument
DOMDocument
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. Benefits
include performance improvements and enhanced access and
manipulation options.
The types and methods of PL/SQL XSLT Processor are made available by the
PL/SQL package, DBMS_XSLPROCESSOR.
XSL Document
(DOMDocument)
newProcessor newStylesheet
setParams
ProcessXSL
DOMDocumentFragment Interface
makeNode
DOMNode Interface
declare
indoc VARCHAR2(2000);
xsldoc VARCHAR2(2000);
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);
end;
/
This chapter describes how to use XMLType in Java, including fetching XMLType
data through JDBC and manipulating them using the Java Bean API.
■ Introducing Java DOM and Java Bean APIs for XMLType
■ Java DOM API for XMLType
■ Java DOM API for XMLType Features
■ Java DOM API for XMLType Classes
■ Java Bean API for XMLType
■ Guidelines for Using Java Bean API for XMLType
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
XML DB Repository hierarchy can store both XML schema-based and non-
schema-based documents.
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.
JavaBean support is not available through JDBC because JDBC can work on both
client and server, and the Java Bean API for XMLType is designed to work only in
the server.
while(orset.next())
{
// get the XMLType
XMLType poxml = XMLType.createXML(orset.getOPAQUE(1));
// get the XMLDocument as a string...
Document podoc = (Document)poxml.getDOM();
}
Connection conn =
DriverManager.getConnection("jdbc:oracle:oci8:@", "scott", "tiger");
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"select e.poDoc.getClobVal() poDoc, "+
"e.poDoc.getStringVal() poString "+
" from po_xml_tab e");
while(orset.next())
{
// the first argument is a CLOB
oracle.sql.CLOB clb = orset.getCLOB(1);
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"select e.poDoc from po_xml_tab e");
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"select e.poDoc from po_xml_tab e");
/*
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;
parser.setPreserveWhitespace (true);
parser.parse(new StringReader(xmlTypeStr));
System.out.println("xmlType.getStringVal(): xml String is well-formed");
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");
}
outXML = sw.toString();
System.out.println("qryStr="+ qryStr);
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn =
DriverManager.getConnection("jdbc:oracle:oci8:@", user, pass);
Statement s = conn.createStatement();
OraclePreparedStatement stmt;
while(orset.next()){
conn.commit();
System.out.println("PurchaseOrder 200 Updated!");
}
}
}
----------------------
-- list PurchaseOrders
----------------------
<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>
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.*;
import oracle.xdb.XMLType;
System.out.println();
}
}
try{
// System.out.println("conStr=" + conStr);
System.out.println("user/pass=" + user + "/" +pass );
System.out.println("qryStr="+ qryStr);
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
while(orset.next()){
xml = orset.getOPAQUE(1);
oracle.xdb.XMLType xt = oracle.xdb.XMLType.createXML(xml);
}
catch (SQLException e) {
System.out.println("Got exception: " + e);
}
}
}
catch( Exception e )
{
e.printStackTrace(System.out);
}
}
}
Note: In this release, Java DOM API for XMLType does not
perform type and constraint checks.
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’s JNDI API bind().
The XML document is stored in the appropriate format:
■ As a CLOB or BLOB for non-XML schema-based documents
■ In the format specified by the XML schema for XML schema-based documents
Example 9–8 Java DOM API for XMLType: Creating a DOM Object and Storing It in the
Format Specified 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 specified 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 = ? ");
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.
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 9–1 lists the Java DOM API for XMLType classes and the W3C DOM interfaces
they implement.
Oracle9i
Database
Oracle
XML DB
Oracle
XMLType JDBC XML DB
Tables, XMLType
Columns, Instance
Views
getDOM()
Method
Saved
Java DOM XML DOM
back Tree
in the API
Database
Use the Java Bean API for XMLType for applications that:
■ Execute in the server
■ Use XML schema-based documents
The Java bean source file is stored in your home directory in Oracle XML DB
Repository under the bean/ directory. You can use this source file for the list of
beans generated for the specific XML schema.
Note: You can also generate Java Beans independently using the
generateBean() function in DBMS_XMLSCHEMA package. This
can be done as many times as you wish.
The deleteSchema() PLSQL call removes the Java bean class
files from Oracle XML DB. See Chapter 5, "Structured Mapping of
XMLType".
The Java bean generation process generates the Java bean code and compiles it
into the server where your XML schema resides. A copy of the source file is also
placed in the Oracle XML DB Repository hierarchy in your home directory. This
is needed for you to later compile your source code.
2. The Java bean classes are generated in a package with the name of the XML
schema file. Different XML schema types are mapped to Java types based on
rules specified in the XML schema. See Table 9–3, "Mapping Between XML
Schema, SQL, and Java DataTypes". For example:
– Oracle XML DB for Java Bean API uses the reflection mechanism to
generate class names. For all attributes and children there will be get and
set methods in the API. These get and set methods will be suffixed with the
name of the child.
– For server side applications, Java Bean API for XMLType objects are
accessed using JNDI lookup() API. In this case the XDB_ACCESS_TYPE
flag specifies BEAN as the access type.
3. Java Bean API for XMLType can also be used for creating new schema-based
XML documents. The applications can instantiate bean classes and use the set
methods to set the appropriate data in the document. Similar to DOM, the JNDI
bind() method is Java bean aware and can be used to save the XML schema
document in Oracle XML DB Repository. See also Chapter 17, "Oracle XML DB
Resource API for Java/JNDI".
Figure 9–2 illustrates the Java Bean API for XMLType calling sequence.
Oracle9i
Database
JNDI lookup API Generated
Oracle Java Bean
XML DB
Repository
Java
Application
Saved Manipulates
back (bind / rebind get / set
in the bean) API Object
Database
Processed Bean
Table 9–2 describes the mapping of XML schema entities to the Java bean
classes/methods.
Table 9–2 JavaBeans API for XMLType: Mapping of XML Schema Entities
XML Schema JavaBeans
Entity Classes/Methods Description
Attribute get/setAttribute{attrname}
Complextype get/set{complextype For complex children separate bean classes get
classname}. generated. Extras (processing
instructions/comments).DOMclassesfor
processing-instruction/comments are
returned.
Scalar data get/set{scalar type name} Children with maxoccurs > 1
Get/set List of type of child
Table 9–3 describes the mapping used by Java Bean API For XMLType between
XML schema, SQL, and Java datatypes.
Table 9–3 Mapping Between XML Schema, SQL, and Java DataTypes
XML Schema Data Type SQL DataType Java Data Type
Boolean boolean boolean
Table 9–3 Mapping Between XML Schema, SQL, and Java DataTypes (Cont.)
XML Schema Data Type SQL DataType Java Data Type
String URI reference ID
IDREF ENTITY NOTATION
Language NCName Name
java.lang.String String DECIMAL
INTEGER LONG SHORT
INT POSITIVEINTEGER NONPOSITIVEINTEGER
oracle.sql.Number int FLOAT
DOUBLE oracle.sql.Number float
TIMEDURATION TIMEPERIOD RECURRINGDURATION
DATE TIME MONTH,YEAR
RECURRINGDATE java.sql.Timestamp Time
REF oracle.sql.Ref Ref
BINARY oracle.sql.RAW Byte[]
QNAME java.lang.String String
The generated Java bean for this XML schema looks like this:
public Employee()
{
super(null, 0, 0);
}
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Part IV of this manual introduces you to ways you can view your existing data as
XML. It contains the following chapters:
■ Chapter 10, "Generating XML Data from the Database"
■ Chapter 11, "XMLType Views"
■ Chapter 12, "Creating and Accessing Data Through URLs"
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:
■ Oracle XML DB Options for Generating XML Data From Oracle9i Database
■ Generating XML from the Database Using SQLX Functions
■ XMLElement() Function
■ XMLForest() Function
■ XMLColAttVal() Function
■ XMLSEQUENCE() Function
■ XMLConcat() Function
■ XMLAgg() Function
■ Generating XML from Oracle9i Database Using DBMS_XMLGEN
■ Generating XML Using Oracle-Provided SQL Functions
■ SYS_XMLGEN() Function
■ SYS_XMLAGG() Function
■ Generating XML Using XSQL Pages Publishing Framework
■ Generating XML Using XML SQL Utility (XSU)
Figure 10–1 Oracle XML DB Options for Generating XML from Oracle9i Database
Oracle9i Database
Oracle XML DB
SQLX Functions SQL Functions PL/SQL Package XDK for Java
• XMLElement • SYS_XMLGEN
• XMLForest • SYS_XMLAGG DBMS_XMLGEN XSQL Pages XML SQL
• XMLColAttVal • XMLSequence Publishing Utility
• XMLConcat Framework (XSU)
• XMLAgg
XMLType
Columns or
Tables
Generated XML:
• XMLType instances
• XML as DOM
• XML as String
• XML Document
• Varray of XMLType
Sequences
• Forest of XML
Elements
See Also:
■ Chapter 6, "Transforming and Validating XMLType Data"
■ Chapter 8, "PL/SQL API for XMLType"
■ Chapter 9, "Java and Java Bean APIs for XMLType"
■ Oracle9i XML API Reference - XDK and Oracle XML DB
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 element’s content and returns an instance of type
XMLType. See Figure 10–2. The XML_attributes_clause is described in the following
section.
elements being generated. The fully escaped mapping escapes all non-XML
characters in the SQL identifier name, including the ":" character.
XML_Attributes_Clause
XMLElement() also takes an optional XMLAttributes() clause, which specifies
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 10–3.
AS c_alias
XMLATTRIBUTES ( value_expr )
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 specified, 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.
XMLElement() can also be nested to produce XML data with a nested structure.
Example 10–3 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;
If the name of the element or attribute is being created from the ALIAS specified 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 the 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 ... ;
<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>
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 10–4 describes the XMLForest() syntax.
AS c_alias
XMLFOREST ( value_expr )
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 specified. If the AS clause is specified, 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 10–6 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 employee’s 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;
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 10–5.
XMLType_instance
XMLSEQUENCE ( , fmt )
sys_refcursor_instance
To create a new XML 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;
<EMPNAME>Joe</EMPNAME>
<SALARY>50000</SALARY>
</EMP>
<EMP>
<EMPNO>217</EMPNO>
<EMPNAME>Jane</EMPNAME>
<SALARY>60000</SALARY>
</EMP>
</EMPLOYEES>
Notice how XMLExtract() 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.
<ROW>
<EMPNO>413</EMPNO>
<ENAME>Jane</ENAME>
</ROW>
<ROW>
<EMPNO>968</EMPNO>
<ENAME>Jack</ENAME>
</ROW>
...
The row tag used for each row can be changed using the XMLFormat object.
<Department deptno="200">
<DeptName>Garment</DeptName>
<EmployeeList>
<Employee empno="400">
<Ename>Marlin</Ename>
<Salary>20000</Salary>
</Employee>
</EmployeeList>
</Department>
<Employee empno="300"><Ename>Jack</Ename><Salary>333444</Salary></Employee>
</EmployeeList></Department>’));
3 rows selected
For each row in table dept_xml_tab, the TABLE function is evaluated. Here, the
extract() function creates a new XMLType 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 10–6 shows the XMLConcat() syntax. XMLConcat() has two
forms:
■ The first form takes an XMLSequenceType, which is a VARRAY of XMLType
and returns a single XMLType instance that is the concatenation of all of the
elements of the varray. This form is useful to collapse lists of XMLTypes into a
single instance.
■ 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.
XMLCONCAT ( XMLType_instance )
<first>Mary</first>
<last>Martin</last>
<first>John</first>
<last>Smith</last>
XMLAgg() Function
XMLAgg() function is an aggregate function that produces a forest of XML elements
from a collection of XML elements. Figure 10–7 describes the XMLAgg() syntax. 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.
ORDER BY sort_list
XMLAGG ( XMLType_instance )
<Department name="Shipping">
<emp>Oppenheimer</emp>
<emp>Martin</emp>
</Department>
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>
</Department>
XMLColAttVal() Function
XMLColAttVal() function generates a forest of XML column elements containing
the value of the arguments passed in. Figure 10–8 shows the XMLColAttVal()
syntax.
AS c_alias
XMLCOLATTVAL ( value_expr )
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.
<column name="HIRE">1992-11-15</column>
<column name="department">Standards</column>
</Emp>
<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:
■ Every row of the query result maps to an XML element with the default tag
name ROW.
■ The entire result is enclosed in a ROWSET element. These names are both
configurable, using the setRowTagName() and setRowSetTagName()
procedures in DBMS_XMLGEN.
■ Each column in the SQL query result, maps as a subelement of the ROW element.
■ 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.
User / Browser /
Client /
Application
fetch Generated
XML XML
as DOM
User / Browser
Client /
Application
Generated
close XML
as String
FUNCTION PROTOTYPES Given a query string, generate a new context handle to be used in
subsequent functions.
newContext()
FUNCTION Returns a new context
newContext(queryString IN VARCHAR2) PARAMETERS: queryString (IN)- the query string, the result of which
needs to be converted to XML
RETURNS: Context handle. Call this function first to obtain a handle
that you can use in the getXML() and other functions to get the XML
back from the result.
FUNCTION 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:
newContext(queryString IN SYS_REFCURSOR)
RETURN ctxHandle;
setRowTag() Sets the name of the element separating all the rows. The default name is
ROW.
PROCEDURE PARAMETERS:
setRowTag(ctx IN ctxHandle,rowTag IN ctx (IN) - the context handle obtained from the newContext call,
VARCHAR2); 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 document’s root element. The default name is
ROWSET
getXML() Gets the XML document by fetching the maximum number of rows
specified. It appends the XML document to the CLOB passed in.
PROCEDURE PARAMETERS:
getXML(ctx IN ctxHandle, ctx (IN) - The context handle obtained from the newContext() call,
clobval IN OUT NCOPY clob, clobval (IN/OUT) - the clob to which the XML document is to be
appended,
dtdOrSchema IN number:= NONE);
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 efficient than the next flavor, 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 specified by the setMaxRows call (or the entire result
if not specified) is fetched and converted to XML. Use the
getNumRowsProcessed function to check if any rows were retrieved or
not.
FUNCTION PARAMETERS: ctx (IN) - The context handle obtained from the
newContext() call,
getXML(ctx IN ctxHandle, dtdOrSchema IN
number:= NONE) RETURN clob 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 PARAMETERS: ctx (IN) - The context handle obtained from the
newContext() call,
getXMLType(ctx IN ctxHandle, dtdOrSchema IN
number:= NONE) RETURN XMLTYPE dtdOrSchema (IN) - whether we should generate the DTD or Schema.
This parameter is NOT supported.
RETURNS: An XMLType instance containing the document.
FUNCTION PARAMETERS: queryString (IN)- the query string, the result of which
needs to be converted to XML RETURNS:
getNumRowsProcessed(ctx IN ctxHandle)
This gets the number of SQL rows that were processed in the last call to
RETURN number getXML. You can call this to find 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 PARAMETERS: ctx (IN) - the context handle corresponding to the query
executed,
setMaxRows(ctx IN ctxHandle, maxRows IN
NUMBER); 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 PARAMETERS: ctx (IN) - the context handle corresponding to the query
executed,
setSkipRows(ctx IN ctxHandle,
skipRows (IN) - the number of rows to skip for each call to getXML.
skipRows IN NUMBER);
The skipRows parameter can be used when generating paginated results
for stateless web pages using this utility. For instance when generating
the first 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 first case.
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.
restartQuery() Restarts the query and generate the XML from the first row again.
closeContext() Closes a given context and releases all resources associated with that
context, including the SQL cursor and bind and define buffers, and so
on.
PROCEDURE PARAMETERS: ctx (IN) - the context handle to close. Closes all
closeContext(ctx IN ctxHandle); resources associated with this handle. After this you cannot use
the handle for any other DBMS_XMLGEN function call.
Conversion Functions
FUNCTION Encodes or decodes the passed in XML data string.
convert(xmlData IN varchar2, flag IN NUMBER := ■ Encoding refers to replacing entity references such as '<' to
ENTITY_ENCODE) return varchar2; their escaped equivalent, such as '<'.
■ Decoding refers to the reverse conversion.
FUNCTION Encodes or decodes the passed in XML CLOB data.
convert(xmlData IN CLOB, flag IN NUMBER := ■ Encoding refers to replacing entity references such as '<' to
ENTITY_ENCODE) return CLOB; their escaped equivalent, such as '<'.
■ Decoding refers to the reverse conversion.
DECLARE
qryCtx DBMS_XMLGEN.ctxHandle;
result CLOB;
BEGIN
qryCtx := dbms_xmlgen.newContext('SELECT * from scott.emp');
--close context
DBMS_XMLGEN.closeContext(qryCtx);
END;
/
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>
<JOB>SALESMAN</JOB>
<MGR>7698</MGR>
<HIREDATE>20-FEB-81</HIREDATE>
<SAL>1600</SAL>
<COMM>300</COMM>
<DEPTNO>30</DEPTNO>
</EMPLOYEE>
...
</ROWSET>
declare
qryCtx dbms_xmlgen.ctxHandle;
result CLOB;
begin
loop
-- now get the result
result := dbms_xmlgen.getXML(qryCtx);
end loop;
--close context
dbms_xmlgen.closeContext(qryCtx);
end;
/
qryCtx := dbms_xmlgen.newContext
('SELECT dept_t(department_id, department_name,
CAST(MULTISET
(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);
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-20.
With relational data, the results are a flat non-nested XML document. To obtain
nested XML structures, you can use object-relational data, where the mapping is as
follows:
■ Object types map as an XML element -- see Chapter 5, "Structured Mapping of
XMLType".
■ Attributes of the type, map to sub-elements of the parent element
To generate a hierarchical view of the data, that is, departments with employees in
them, you can define 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.
-- 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);
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.
Street VARCHAR2(200),
City VARCHAR2(200),
State CHAR(2),
Zip VARCHAR2(20)
)
/
--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;
--Stock Table
CREATE TABLE Stock_tab (
StockNo NUMBER constraint stock_uk UNIQUE,
Price NUMBER,
TaxRate NUMBER
);
Quantity NUMBER,
Discount NUMBER,
constraint LI_PK PRIMARY KEY (PONo, LineItemNo)
);
--------------------
-- Populate data
-------------------
-- Establish Inventory
-- Register Customers
-- Place Orders
-------------------------------------------------------
-- 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
loop
-- now get the po in xml format
pxml := dbms_xmlgen.getXMLType(qryCtx);
---------------------------
-- list xml PurchaseOrders
---------------------------
<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>
<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>
page NUMBER := 0;
xmlpage boolean := true;
refcur SYS_REFCURSOR;
BEGIN
OPEN refcur FOR 'select * from emp where rownum < :1' USING ctx1;
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;
/
SYS_XMLGEN() Function
This Oracle specific 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.
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 10–10.
fmt
SYS_XMLGEN ( expr )
SYS_XMLGEN(EMAIL).GETSTRINGVAL()
------------------------------------------------------------------
<EMAIL>SHIGGENS</EMAIL>
Table 10–2 lists the XMLFormat attributes. of the XMLFormat object. The function
that implements this type follows the table.
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.
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 first argument of the operator.
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 SYS_XMLGEN() to
create the XML for the object instance.
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.
<ENAME>Jack</ENAME>
<EMPNO>400</EMPNO>
</EMPLOYEE>
<EMPLOYEE>
<ENAME>Joseph</ENAME>
<EMPNO>300</EMPNO>
</EMPLOYEE>
</DOCUMENT>
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;
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-43.
PONO NUMBER,
Customer Customer_typ,
OrderDate DATE,
ShipDate TIMESTAMP,
LineItems_ntab LineItems_ntabtyp,
ShipToAddr Address_typ
)
/
-------------------------------------------------------
-- 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;
<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_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
fmt
SYS_XMLAGG ( expr )
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;
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 specification. 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.
See Also: Oracle9i XML Developer’s Kits Guide - XDK, the chapter
in "XDK for Java" on XSQL Page Publishing Framework.
You can generate XML on this table using Java with the call:
java OracleXML getXML -user "scott/tiger" -rowTag "Part" "select * from parts"
See Also : Oracle9i XML Developer’s Kits Guide - XDK for more
information on XSU
This chapter describes how to create and use XMLType views. It contains the
following sections:
■ What Are XMLType Views?
■ Creating Non-Schema-Based XMLType Views
■ Creating XML Schema-Based XMLType Views
■ Creating XMLType Views by Transforming XMLType Tables
■ Referencing XMLType View Objects Using REF()
■ DML (Data Manipulation Language) on XMLType Views
■ Query Rewrite on XMLType Views
■ Ad-Hoc Generation of XML Schema-Based XML
■ Validating User-Specified Information
See Also:
■ Chapter 5, "Structured Mapping of XMLType"
■ Appendix B, "XML Schema Primer"
This chapter describes the two main ways you can create XMLType views:
■ Based on XML generation functions
■ Based on object types
See Also: Chapter 10, "Generating XML Data from the Database",
for details on SQLX generation functions.
Example 11–1 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));
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>
empno attribute in the document should become the unique identifier for each row.
SYS_NC_ROWINFO$ is a virtual column that references the row XMLType 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);
The 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.
You can create XML schema-based XMLType views without creating object types.
For this, you can use the SQL XML generation functions or transformation functions
to generate an XML schema conformant XMLType instance. The use of object types
with schemas however, enables Query Rewrite functionality.
Consider the following examples based on the canonical employee -department
relational tables and XML views of this data:
■ Creating Non-Schema-Based XMLType Views
■ XMLType View: View 2, Wrapping Relational Department Data with Nested
Employee Data as XML
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.
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"
This example uses the extractValue() SQL function here in the OBJECT ID clause,
since extractValue() can automatically figure 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 first 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;
Step 4c. Create XMLType View Using the One-Step Process Without Types
You can also create the XMLType views using the SQL XML generation functions
without the need for object types. You can also use XMLTransform() or other SQL
functions which generate XML.The resultant XML must be conformant to the XML
schema specified for the view.
With the one-step process you must create an XMLType view on the relational tables
without having to create and register any object type as follows:
CREATE OR REPLACE VIEW emp_xml OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/emp.xsd" ELEMENT "Employee"
WITH OBJECT ID (extract(sys_nc_rowinfo$,
’/Employee/EmployeeId/text()’).getnumberval()) AS
SELECT XMLElement("Employee",
XMLAttributes( ’http://www.oracle.com/emp.xsd’ AS "xmlns" ,
’http://www.w3.org/2001/XMLSchema-instance’ AS "xmlns:xsi",
’http://www.oracle.com/emp.xsd
http://www.oracle.com/emp.xsd’ AS "xsi:schemaLocation"),
XMLForest(e.empno AS "EmployeeId", e.ename AS "Name",
e.job AS "Job" , e.mgr AS "Manager",
e.hiredate 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;
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 view’s XML
schema.The innermost XMLForest() function creates the department XML
element that is nested inside the Employee element.
The XML generation function simply generate 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.
-- creates the XML instance with the correct namespace, prefixes and target
schema
-- location, and can be used as the query in the view definition:
-- <ipo:Employee xmlns="http://www.oracle.com/emp.xsd"
-- xmlns:xsi="http://www.oracle.com/emp.xsd
-- http://www.oracle.com/emp.xsd">
-- <ipo:EmployeeId>2100</ipo:EmployeeId>
-- <ipo:Name>John</ipo:Name>
-- <ipo:Manager>Mary</ipo:Manager>
-- <ipo:Hiredate>12-Jan-01</ipo:Hiredate>
-- <ipo:Salary>123003</ipo:Salary>
-- <ipo:Dept>
-- <ipo:Deptno>2000</ipo:Deptno>
-- <ipo:DeptName>Sports</ipo:DeptName>
-- <ipo:Location>San Francisco</ipo:Location>
-- </ipo:Dept>
-- </ipo:Employee>
If the XML schema had no target namespace then 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":
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;
/
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",
e.hiredate 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;
Example 11–4 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:
);
/
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 3b. Create XMLType Views on Relational Tables using SQL functions
Create the dept_xml XMLType view from the relational tables without object types:
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(deptno "DeptNo", d.dname "DeptName", d.loc "Location"),
(SELECT XMLAGG(XMLElement("Employee",
XMLType view reference REF() is based on one of the following object IDs:
■ On a system-generated OID — for views on XMLType tables or object views
■ 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.
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"/>
</sequence>
</complexType>
</element>
</schema>’, TRUE, FALSE, FALSE);
END;
/
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;
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);
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-52, for details on query rewrite.
is rewritten to :
SELECT SYS_XMLGEN(empno)
FROM emp e
WHERE e.ename = ’SMITH’;
See Also: Chapter 10, "Generating XML Data from the Database".
If the XML schema information is specified, 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)
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:
■ How Oracle9i Database Works with URLs and URIs
■ URI Concepts
■ UriTypes Store Uri-References
■ HttpUriType Functions
■ DBUri, Intra-Database References
■ XDBUriType
■ Using UriType Objects
■ Creating Instances of UriType Objects with the UriFactory Package
■ Why Define New Subtypes of UriType?
■ SYS_DBURIGEN() SQL Function
■ Turning a URL into a Database Query with DBUri Servlet
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:
■ 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.
■ 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.
■ 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.
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.
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:
■ http://www.w3.org/2002/ws/Activity.html an
explanation of HTTP URL notation
■ http://www.w3.org/TR/xpath for an explanation of the
XML XPath notation
■ http://www.w3.org/TR/xptr/ for an explanation of the
XML XPointer notation
■ http://xml.coverpages.org/xmlMediaMIME.html for a
discussion of MIME types
URI Concepts
This section introduces you to URI concepts.
What Is a URI?
A URI, or Uniform Resource Identifier, is a generalized kind of URL. Like a URL, it
can reference any document, and can reference a specific 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:
■ URL, that identifies the document using the same notation as a regular URL.
■ Fragment, that identifies 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.
■ 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 files 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.
■ Unified 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 unified 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 12–1 lists the UriType member functions.
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 influence the HTTP
fetch using this mechanism. Table 12–2 lists the HttpUriType member functions.
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.
getXML() Function
getXML() function returns XMLType information for the result. If the document is
not valid XML (or XHTML) an error is thrown.
</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>
Figure 12–1 DBUri: Visual or SQL View, XML View, and Associated XPath
Database
<oracle>
<scott>
Table Emp <emp>
Empno Ename Job <row>
XML <EmpNo> 21
. . . Visualization <Ename> John
21 John x </row> URL becomes . . .
33 Mary x /oracle/scott/emp/row/[empno=21]/ename..
x x x </emp>
</scott>
</oracle>
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:
■ 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.
■ Table emp shows up as EMP with row element tags. This is the default mapping
for all tables. The same for dept and the customer_obj_tab table under the
jones schema.
■ In this release, null elements are absent
■ There is also a PUBLIC element under which tables and views are accessible
without schema qualification. 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
or
/oradb/SCOTT/EMP/ROW[empno=7263]
you must include the pono predicate along with the ROW node as:
/oradb/scott/purchase_obj_tab/ROW[pono=100]/line_item_list
■ 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.
Note:
■ No XPath axes other than the child axes are supported. The
wild card (*), descendant (//), and other operations are not
valid.
■ Only the text() XPath function is supported. text() is valid
only on a scalar node, not at the row or table level.
The predicates can be defined 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 12–4 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
ADDRESS/STATE=’OR’]/ADDRESS[CITY=’Portland’ OR /ZIPCODE=94404]/CITY
This DBUri identifies the city attribute whose state is either California or Oregon,
or whose city name is Portland, or whose zipcode is 94404.
/oradb/SCOTT/EMP
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>
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>
Example 12–9 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.
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.
Note:
■ A DBUri is not a general purpose XPointer mechanism to XML
data.
■ It is not a replacement for database object references. The
syntax and semantics of references differ from those of
Uri-refs.
■ It does not enforce or create any new security models or
restrictions. Instead, it relies on the underlying security
architecture to enforce privileges.
DBUriType Functions
Table 12–3 lists the DBUriType methods and functions.
Method/Function Description
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.
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:
■ If the DBUri points to a scalar value, where the MIME type is text/plain.
■ 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);
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 new subtype 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 '#'.
The following are examples of ORACLE XML DB URIs:
/home/scott/doc1.xml
/home/scott/doc1.xml#/purchaseOrder/lineItem
where:
■ ’/home/scott’ is a folder in Oracle XML DB Repository
■ doc1.xml is an XML document in this folder
■ The XPath expression /purchaseOrder/lineItem refers to the line item in
this purchase order document.
Table 12–4 lists the XDBUriType methods. These methods do not take any
arguments.
Example 12–11 Creating XDBUriType, Inserting Values Into a Purchase Order Table
and Selecting All the PurchaseOrders
The following is an example of how XDBUriType 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)
);
Example 12–12 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’;
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.
-- In PL/SQL
declare
a SYS.UriType;
begin
-- absolute URL
SELECT poUrl into a from uri_Tab WHERE poName like 'AbsPo%';
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 first row as well as the local DBUri
reference.:
SELECT e.poURL.getclob() FROM uri_tab e;
);
/
-- Now the example inserts this new type of URI into the table.
insert into url_tab values (’ECOM://company1/company2=22/comp’);
DBUriType(’/oradb/SCOTT/EMPLOYEE/ROW[ENAME="Jack"],null); -- a DBUriType
SYS_DBURIGEN(EMPLOYEE_ID,EMAIL)(URL, SPARE)
-------------------------------------------------------------------
DBURITYPE(’/PUBLIC/EMPLOYEES/ROW[EMPLOYEE_ID = "206"]/EMAIL’, NULL)
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 identifies 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.
uses the empno both as the key column and the referenced column, generating
a URL of the form:
/SCOTT/EMP/ROW[EMPNO=7369]/EMPNO,
SYS_DBURIGEN Examples
-- inserts /SCOTT/EMP/ROW[rowid=’xxx’]/EMPNO
INSERT INTO doc_list_tab values(1001,
(select SYS_DBURIGEN(rowid,empno) from emp where empno = 100));
Example 12–19 Returning a Portion of the Results By Creating a View and Using
SYS_DBURIGEN()
Assume that the travel story table is defined as follows:
CREATE TABLE travel_story
(
story_name varchar2(100),
story clob
);
Now, you create a function that returns only the first 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;
/
Now, you create a view that selects out only the first 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;
-----------------------------------------------------------------------------
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.
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;
-- 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()
Example 12–21 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
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.
See Also:
■ Chapter 20, "Writing Oracle XML DB Applications in Java"
■ Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
■ Appendix A, "Installing and Configuring Oracle XML DB"
Notice that the servlet is installed at /oradb/* specified 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.
Security parameters, the servlet display-name, and the description can also be
customized in the xdbconfig.xml configuration file. See Appendix A, "Installing
and Configuring 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 specified in the
configuration file. The roles allowed to access the servlet are specified 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:
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;
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 prefix.
See Also: Oracle9i XML API Reference - XDK and XDB for details
of all functions in DBUriFactory package.
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:
■ Introducing Oracle XML DB Foldering
■ Oracle XML DB Repository
■ Oracle XML DB Resources
■ Accessing Oracle XML DB Repository Resources
■ Navigational or Path Access
■ Query-Based Access
■ Accessing Repository Data Using Servlets
■ Accessing Data Stored in Oracle XML DB Repository Resources
■ Managing and Controlling Access to Resources
■ Extending Resource Metadata Properties
Figure 13–1 A Typical Folder Tree Showing Hierarchical Structures in Oracle XML
Repository
/ Root Node
/home /sys
/acls /log
/SCOTT /XDB /schemas
Oracle
/schemas /PUBLIC XML DB
/acls
folders
/po /acls (containers)
/general /graphics /schemas /xmlns.oracle.com
Directories
/xdb (containers)
Files or Documents
(non-containers)
po_101.xml
po_Jan02.xml XML files
po_Jan03.xml stored in your
XMLType
tables / views
See Also:
■ Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
■ Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
■ Chapter 17, "Oracle XML DB Resource API for Java/JNDI"
■ Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
Repository Terminology
The following lists describes terms used in Oracle XML DB Repository:
■ Resource: A resource is any object or node in the hierarchy. Resources are
identified by URLs. See "Oracle XML DB Resources" on page 6.
■ Folder: A folder is a node (or directory) in the hierarchy that can contain a
collection of resources. A folder is also a resource.
■ Pathname: A hierarchical name composed of a root element (the first /),
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 configuration file xdbconfig.xml also
contains a list of user-defined characters that may not appear within a path
name (<invalid-pathname-chars>).
■ 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).
■ Contents: The body of a resource, what you get when you treat the resource like
a file and ask for its contents. Contents is always an XMLType.
■ XDBBinary: An XML element defined 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.
■ 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 file system hierarchy).
Many terms used by Oracle XML DB have common synonyms used in other
contexts, as shown in Table 13–1.
any Element
The XML schema for a resource also defines an any element, with maxoccurs
unbounded, which allowed to contain any element outside the Oracle XML DB
XML namespace. This way, arbitrary instance-defined properties can be associated
with the resource.
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 file 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:
■ resolve privilege on the folder
■ 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”.
Oracle XML DB
Data Access Options
Query-based Path-based
Access Access
Figure 13–4 Accessing Repository Data Using HTTP/WebDAV and Navigational Access From IE
Browser: Viewing Web Folders
See Also: Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
Query-Based Access
Oracle XML DB provides two Repository views to enable SQL access to Repository
data:
■ PATH_VIEW
■ RESOURCE_VIEW
Table 13–2 summarizes the differences between PATH_VIEW and RESOURCE_VIEW.
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.
See Also:
■ Chapter 15, "RESOURCE_VIEW and PATH_VIEW" for details
on SQL Repository access
■ Chapter 18, "Oracle XML DB Resource Security"
■ Oracle9i XML API Reference - XDK and Oracle XML DB
See Also:
■ Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
■ Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
■ Chapter 17, "Oracle XML DB Resource API for Java/JNDI"
■ Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
■ Oracle9i XML API Reference - XDK and Oracle XML DB
See Also:
■ Chapter 18, "Oracle XML DB Resource Security" for more detail
on using access control on Oracle XML DB folders
■ Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
■ Oracle9i XML API Reference - XDK and Oracle XML DB the
chapters on DBMS_XDB
<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.
■ Option 2: Extending the Resource XML Schema. You can extend the resource
XML schema using the techniques specified by the XML schema specifications,
that is, you can register a new XML schema that extends the ResourceType
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>
This chapter describes how to create and manage versions of Oracle XML DB
resources. It contains the following sections:
■ Introducing Oracle XML DB Versioning
■ Creating a Version-Controlled Resource (VCR)
■ Access Control and Security of VCR
■ Frequently Asked Questions: Oracle XML DB Versioning
resid := DBMS_XDB_VERSION.MakeVersioned(’/home/SCOTT/versample.html’);
-- Obtain the resource
res := DBMS_XDB_VERSION.GetResoureceByResId(resid);
Example 14–3 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’);
Example 14–4 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’);
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>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’;
-- At this point, you can download the first version with the resource object
ID,
-- resid1 and download the second version with resid2.
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:
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.
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.
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.
Version Resource
When a regular resource is makeversioned, the first version resource is created,
and the ACL of this first 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
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.
GetPredsByResId(resid Given a version resource or a VCR, gets the predecessors of the resource by resid
dbms_xdb.resid_type) (resource id.)
RETURN resid_list_type;
FUNCTION Given a version resource or a VCR, gets the successors of the resource by
GetSuccessors pathname, the path name of the resource.
GetSuccessors(pathname return - list of predecessors. Getting successors by resid is more efficient than by
VARCHAR2) RETURN path name. An exception is raised if the resid or path name is illegal.
resid_list_type;
GetSuccsByResId(resid
dbms_xdb.resid_type) Given a version resource or a VCR, get the successors of the resource by resid
RETURN resid_list_type; (resource 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.
Query-based
Access
RESOURCE PATH
VIEW VIEW
SQL SQL
Queries Queries
Oracle XML DB
Repository
Oracle XML DB
Resource Table
Content Properties Access through:
• JNDI
• WebDav
• FTP
• DBMS_XDB
Path-based
Access
The path in the RESOURCE_VIEW is an arbitrary 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 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 some operations, such as creating links to existing resources.
/home
R1
R2
/corp /role
RESOURCE_VIEW Example:
select path(1) from resource_view where under_path(res, '/sys',1);
po_westcoast po_eastcoast displays one path to the resource:
/home/corp/po_westcoast
Target Resource
PATH_VIEW Example:
select path from path_view;
With PATH_VIEW, to acces the target displays all pathnames to the resource:
resource node;You can create a link. /home/corp/po_westcoast
This provides two access paths R1 or R2 /home/role/po_eastcoast
to the target node, for faster access.
See the "Using the Resource View and Path View API" and EQUALS_PATH.
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 efficient, since a much smaller number of links may need to be
traversed. Figure 15–4 shows the UNDER_PATH syntax.
, levels , correlation_integer
UNDER_PATH ( column , path_string )
EQUALS_PATH
The EQUALS_PATH operator is used to find the resource with the specified 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 15–5.
EQUALS_PATH INTEGER EQUALS_PATH( resource_column,pathname);
, correlation_integer
EQUALS_PATH ( column , path_string )
where:
■ resource_column is the column name or column alias of the 'resource' column
in the path_view or resource_view.
■ pathname is the path name to resolve.
PATH
PATH is an ancillary operator that returns the relative path name of the resource
under the specified 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:
■ correlation is an integer that can be used to correlate the UNDER_PATH
operator (a primary operator) with ancillary operators (PATH and DEPTH).
DEPTH
DEPTH is an ancillary operator that returns the folder depth of the resource under
the specified starting path.
DEPTH INTEGER DEPTH( correlation);
where:
Example 15–1 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%’;
Example 15–2 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 15–3 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 15–4 Using UNDER_PATH: Given a Path Name, Get Path and Depth Under a
Specified Path from the PATH_VIEW
select path(1) PATH,depth(1) depth
from path_view
where under_path(RES, 3,'/sys',1)=1
Example 15–5 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 15–6 Using UNDER_PATH: Given a Path Name, Find all the Paths up to a
Certain Number of Levels, Including Links Under a Specified Path from the PATH_VIEW
select path(1) from path_view
where under_path(res, 3,’/sys’, 1) > 0 ;
If only leaf resources are deleted, you can perform a delete using delete from
resource_view where....
</Resource>')
where any_path = '/home/SCOTT/example';
Note: If you need to get all the resources under a directory, you
can use the LIKE operator, as shown in Example 15–1 on page 15-9.
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 15–2 on page 15-9.
The query plan for Example 15–1 will be more optimal than that of
Example 15–2.
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 configuration.
It contains the following sections:
■ Introducing Oracle XML DB Resource API for PL/SQL
■ Overview of DBMS_XDB
■ DBMS_XDB: Oracle XML DB Resource Management
■ DBMS_XDB: Oracle XML DB ACL-Based Security Management
■ DBMS_XDB: Oracle XML DB Configuration Management
■ DBMS_XDB: Rebuilding Oracle XML DB Hierarchical Indexes
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Overview of DBMS_XDB
The DBMS_XDB provides the PL/SQL application developer with an API that
manages:
■ Oracle XML DB Resources
■ Oracle XML DB ACL based Security
■ Oracle XML DB Configuration
■ Oracle XML DB Hierarchical Index Rebuild
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 16–1:
– Link()
– LockResource()
– GetLockToken()
– UnlockResource()
– DeleteResource()
See Example 16–1 for an examples of using DBMS_XDB to manage Repository
resources.
createResource() createFolder()
Available methods:
• link()
• lockResource()
• getLockToken()
• unlockResource()
• deleteResource()
declare
bret boolean;
begin
bret :=
dbms_xdb.createresource(’/public/mydocs/emp_scott.xml’,’<emp_name>scott</emp_
name>’);
commit;
end;
/
declare
bret boolean;
begin
bret :=
dbms_xdb.createresource(’/public/mydocs/emp_david.xml’,’<emp_name>david</emp_
name>’);
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;
Resource Path
Available methods:
• GetAclDocument()
• ACLCheckPrivileges()
• checkPrivileges()
• changePrivileges()
• setAcl()
XMLType instance
or positive integer
or N/A
declare
bret boolean;
begin
bret :=
dbms_xdb.createresource(’/public/mydocs/emp_scott.xml’,’<emp_name>scott</emp_
name>’);
commit;
end;
/
call dbms_xdb.setacl(’/public/mydocs/emp_scott.xml’,
’/sys/acls/all_owner_acl.xml’);
commit;
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;
/
call dbms_xdb.deleteresource(’/public/mydocs/emp_scott.xml’);
call dbms_xdb.deleteresource(’/public/mydocs’);
commit;
New Session
Configuration
Information
cfg_get
cfg_refresh
declare
config xmltype;
begin
config := dbms_xdb.cfg_get();
-- Modify the xdb configuration using updatexml, etc ...
dbms_xdb.cfg_update(config);
end;
/
Remove index
entries from
xdb.xdb$h_index
using: DELETE
commit;
execute dbms_xdb.RebuildHierarchicalIndex;
This chapter describes the Oracle XML DB Resource API for Java. It includes the
JNDI interface for accessing and manipulating the Repository data.
This chapter contains these sections:
■ Introducing Oracle XML DB Resource API for Java/JNDI
■ Using Oracle XML DB Resource API for Java/JNDI
■ Calling Sequence for Oracle XML DB Resource API for Java/JNDI
■ Parameters for Oracle XML DB Resource API for Java/JNDI
■ Oracle XML DB Resource API for Java/JNDI Examples
What Is JNDI?
Oracle XML DB supports Java Naming and Directory Interface (JNDI) as the
standard navigational access Application Program Interface (API). JNDI is a Sun
programming interface. It connects Java programs to naming and directory services
such as Domain Name Server (DNS), Lightweight Directory Access Protocol
(LDAP), and Network Directory Service (NDS). JNDI is most commonly used as a
client interface to LDAP servers and can also be used to access local operating
system files.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
■ The bean also implements DOM interfaces so that dynamic data can be accessed
easily as well. Server access to data is centralized in LDAP servers as well as the
database with the same API. In JNDI, folders are called Contexts. The two terms
are used interchangeably in this chapter.
■ Oracle XML DB Resource API for Java/JNDI supports JNDI Service Provider
Interface (SPI).
oracle.xdb.spi
The application writes to the JNDI API. The directory drivers are written to the
JNDI SPI (Service Provider Interface). Classes in package oracle.xdb.spi
implement service provider drivers.
WebDAV Support
Package oracle.xdb.spi contains Oracle-specific extensions to the JNDI public
standard. oracle.xdb.spi also provides support for WebDAV (Web Distributed
Authoring and Versioning).
See Also: Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
See Also: Chapter 9, "Java and Java Bean APIs for XMLType",
"Java Bean API for XMLType" on page 9-20
Table 17–1 Oracle XML DB Resource API for Java/JNDI: Parameters (Cont.)
Parameter Name Description
XDB_RESOURCE_TYPE Determines what data is returned to the application by default
when a path name is resolved:
■ “Resource”: A resource class will be returned.
■ “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 define a fragment of
the document to load immediately (rather than relying on the
lazy manifest facility).
Oracle XML DB Resource API for Java/JNDI has two main components:
■ Context module. This implements the JNDI Context interface, which accesses
the Oracle XML DB Repository using the lookup, bind, rename, unbind,
move, and list functions.
■ A set of classes/interfaces. These are returned from operations performed on
the Context module. These classes/interfaces are:
– Enumerators. These enumerate name/classname pairs or name/object
pairs.
– Other classes returned by the Context module. These can be:
* A resource. A leaf in Oracle XML DB Repository that implements
methods to modify the properties of the Oracle XML DB resources and
folders.
* XMLType/Bean/org.w3c.Document interface. These operate on XML
documents stored in Oracle XML DB Repository.
Initial Context
The initial context describes the starting point in the Repository hierarchy from
which all name resolutions happens, with the exception of absolute names which
begin with “/”. Oracle XML DB does not differentiate between initialContexts
and Contexts since it stores the initial path of the application in an environment
variable in the class. Thus, initialContextFactory generates an XDBContext
class that implements the Context interface. initialContextFactory also takes
in as parameters the Language and the Country names for Globalization support.
XDBContext class return results in the form of a pointer to the data. The JNI
implementation passes this pointer and other relevant data back to the Java Context
API, which generates the appropriate objects from the pointer and other data. This
information is then returned to the application program, which can further make
calls on these objects. The implementation is very fast.
See Also: Chapter 9, "Java and Java Bean APIs for XMLType"
which explains the XMLType interface and Oracle XML DB’s DOM
support.
A Java bean is a class specific to XML documents for which an XML schema has
been registered. The lookup/list methods that return objects will determine if
the document returned is an XML object for which an XML schema has been
registered.
■ javax.naming.NamingEnumeration: Provides a means for enumerating
the contents of the Oracle XML DB Folder as a name/class name pair. The class
name is one of the following:
■ oracle.xdb.XDBContext (if object is a folder)
■ A bean
■ oracle.xdb.XMLType
The class name is dependent on the document stored and the environment
returned. It also provides a high-level overview of the processing flows and
associated inputs and outputs among the major functional components. It
includes the processing flows to the external sources for the external inputs and
outputs that cross into and out of the system domain.
■ javax.naming.BindingEnumeration: Provides a way to enumerate the
contents of the Oracle XML DB folder as a name/object pair. The object is one
of the following:
■ oracle.xdb.XDBContext (if object is a folder)
■ A bean
■ oracle.xdb.XMLType
The object type is dependent on the document stored and the environment
returned.
Table 17–2 Oracle XML DB Resource API for Java: JNDI Context Input Parameters
JNDI Input Parameters Name Valid Values Description
Context.PROVIDER_URL path string, “/” for example Contains the starting path from
which name resolution is to begin.
Context.INITIAL_CONTEXT_FACTORY The value of the context factory to be
oracle.xdb.spi.XDBContextF used for generating the initial context
actory object.
XDBContext.RETURN_OBJECT_TYPE Resource, contents Determines if the caller is interested
in the resource (the metadata object)
or the actual contents. For example, a
database application which is
interested only in the data might not
be interested in the metadata. The
default is Contents.
XDBContext.COUNTRY The country name string Determines the locale to be used for
error messages. The default is
database locale.
XDBContext.LANGUAGE The language name strings Controls the error message language,
and so on. The default is database
language.
RETURN_OBJECT_TYPE lets you specify the intent of the application, that is, the
kind of data you are interested in.
The purpose of InitialContextFactory()is to generate the initial object from
which the child objects can be obtained.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
JNDI Objects
JNDI objects are constructed on calling various methods on the Context interface.
The Context lookup method generates either of the following:
■ XDBResource class
Example 17–2 Resource API JNDI: Using DOM to Determine Purchase Order
Properties
Here is a JNDI example using DOM for attribute access. The environment setup is
the same as in the previous example and omitted here:
Context ctx = new InitialContext(env);
Document po = (Document)ctx.lookup("/orders/123.xml");
Node n;
n = po.getElementsByTagName("Title").item(1);
String title = n.getNodeValue();
n = po.getElementsByTagName("IsCurrent").item(1);
boolean isCurrent = new Boolean(n.getNodeValue()).booleanValue();
Example 17–3 Resource API Java Beans: Using JNDI to Determine Purchase Order
Properties
Here is a Java Bean version of the DOM example. It uses JNDI to locate the object
with the same setup:
Context ctx = new InitialContext(env);
PurchaseOrder po = ctx.lookup("/orders/123.xml");
Boolean isCurrent = po.isCurrent();
String title = po.getTitle();
Note how simple the Java Bean API is. In this case, the return of lookup() is
simply cast to the corresponding Bean class. The application must already have
knowledge of the datatype at a particular filename or else it must use methods
defined on XMLType to determine what class to cast to.
Example 17–4 Resource JDBC: Using SQL To Determine Purchase Order Properties
Here is an example using SQL instead of JNDI to find the object. This example uses
XMLType to access the resource. JDBC is not as fast as JNDI, but it provides the
power of SQL SELECT potentially using criteria other than path name to find 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();
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:
■ Introducing Oracle XML DB Resource Security and ACLs
■ Access Control List Terminology
■ Oracle XML DB ACL Features
■ Access Control: User and Group Access
■ Oracle XML DB Supported Privileges
■ ACL Evaluation Rules
■ Using Oracle XML DB ACLs
■ ACL and Resource Management
■ Using DBMS_XDB to Check Privileges
Oracle XML DB uses an access control list (ACL) mechanism to 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
specification. 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.
See Also:
■ Chapter 21, "Managing Oracle XML DB Using Oracle
Enterprise Manager"
■ Oracle9i XML API Reference - XDK and Oracle XML DB
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.
■ 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 specifies that the ACL can only be applied to instances of that XML element
and elements in a substitution group with that element.
■ 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
■ 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.
■ 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.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Example 18–1 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>
Atomic Privileges
Table 18–2 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.
Aggregate Privileges
Table 18–3 lists the aggregate privileges defined by Oracle XML DB, along with the
atomic privileges of which they are composed.
Table 18–4 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 18–4 Privileges Needed for Operations on Oracle XML DB Resources (Cont.)
Operation Description Privileges Required
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.
Example 18–2 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:
■ All permissions to the owner
■ 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
conn xdbadmn/xdbadmn
commit;
connect xdbuser/xdbuser
It returns an XMLType instance of <acl> element representing the ACL for the
resource at res_path.
This chapter describes how to access Oracle XML DB Repository using FTP,
HTTP/WebDAV protocols. It contains the following sections:
■ Introducing Oracle XML DB Protocol Server
■ Using FTP and Oracle XML DB Protocol Server
■ Using HTTP and Oracle XML DB Protocol Server
■ Using WebDAV and Oracle XML DB
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.
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.
Figure 19–1 illustrates the Oracle XML DB Protocol Server components and how
they are used to access files in Oracle XML DB XML Repository and other data.
Only the relevant components of the Repository are shown
FTP FTP
Client Server Foldering
Network Protocol
Server
Configuration
Management
HTTP HTTP /
WebDAV WebDAV
Client Server
ACL
Security
For examples of the usage of these parameters, see the configuration file
/xdbconfig.xml, in Oracle XML DB Repository.
See Also:
■ http://rfc.sunsite.dk/rfc/rfc959.html
■ http://256.com/gray/docs/rfc2616/
■ http://www.faqs.org/rfcs/rfc2518.html
files. It is also the default specified by the specification. Structure mount is not
supported.
■ Append.
■ Allocate. This pre-allocates space before file transfer.
■ Account. This uses the insecure Telnet protocol.
■ Abort.
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
configure the Oracle XML DB servlets.
It contains these sections:
■ Introducing Oracle XML DB Java Applications
■ Design Guidelines: Java Inside or Outside the Database?
■ Writing Oracle XML DB HTTP Servlets in Java
■ Configuring Oracle XML DB Servlets
■ HTTP Request Processing for Oracle XML DB Servlets
■ The Session Pool and XML DB Servlets
■ Native XML Stream Support
■ Oracle XML DB Servlet APIs
■ Oracle XML DB Servlet Example
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 20–1 illustrates which Oracle XML DB APIs are
available in each architecture in this release. The “NO” fields will become “YES” in
a forthcoming release.
Oracle XML DB APIs AVailable Inside and Outside Oracle9i Database
Table 20–1 Oracle XML DB APIs Inside and Outside Oracle9i Database
Java Oracle XML DB Inside the Database:Java Outside the Database: Using
APIs Description Servlets/Stored Procedures Thick JDBC (OCI) Drivers
JDBC support for YES YES
XMLType
XMLType class YES YES
Java DOM implementation YES YES
JNDI access to repository YES NO
Java Bean structured XML YES NO
access
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.
Table 20–2 XML Elements Defined for Servlet Deployment Descriptors (Cont.)
XML Element Name Defined By Supported? Description Comment
distributable Java no Indicates whether or not this servlet All servlets running in
can function if all instances are not the Oracle9i database
running in the same Java virtual MUST be
machine distributable.
errnum Oracle yes Oracle error number See Oracle9i Database
Error Messages
error-code Java yes HTTP error code Defined by RFC 2616
error-page Java yes Defines a URL to redirect to if an Can be specified
error is encountered. 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 filename extension used to --
associate with MIME types,
character sets, and so on.
facility Oracle yes Oracle facility code for mapping For example: “ORA”,
error pages “PLS”, and so on.
form-error-page Java no Error page for form login attempts Not yet supported
form-login-config Java no Config 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 Supported for servlets
servlet
init-param Java Yes Initialization parameter for a servlet --
jsp-file Java No Java Server Page file to use for a Not supported
servlet
lang Oracle Yes IANA language name For example: “en-US”
lang-mapping Oracle Yes Specifies a mapping between a --
filename extension and language
content
large-icon Java Yes Large sized icon for icon display --
Table 20–2 XML Elements Defined for Servlet Deployment Descriptors (Cont.)
XML Element Name Defined By Supported? Description Comment
load-on-startup Java Yes Specifies if a servlet is to be loaded --
on startup
location Java Yes Specifies the URL for an error page Can be a local path
name or HTTP URL
login-config Java No Specifies a method for Not yet supported
authentication
mime-mapping Java Yes Specifies a mapping between --
filename extension and the MIME
type of the content
mime-type Java Yes MIME type name for resource For example:
content “text/xml” or
“application/octet-str
eam”
OracleError Oracle Yes Specifies an Oracle error to --
associate with an error page
param-name Java Yes Name of a parameter for a Servlet Supported for servlets
or ServletContext
param-value Java Yes Value of a parameter --
realm-name Java No HTTP realm used for authentication Not yet supported
role-link Java Yes Specifies a role a particular user Refers to a database
must have in order to access a role name. Make sure
servlet 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 Defines 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 Configuration information for a --
servlet
Table 20–2 XML Elements Defined for Servlet Deployment Descriptors (Cont.)
XML Element Name Defined By Supported? Description Comment
servlet-class Java Yes Specifies the classname for the Java --
servlet
servlet-language Oracle Yes Specifies the programming Either “Java”, “C”, or
language in which the servlet is “PL/SQL”. Currently,
written. only Java is supported
for customer-defined
servlets.
servlet-mapping Java Yes Specifies a filename pattern with All of the mappings
which to associate the servlet defined 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 If this is not specified,
Java class is loaded. If not specified, the servlet must be
the schema is searched using the loaded into the SYS
default resolver specification. 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-config Java No Configuration information for an HTTPSession is not
HTTPSession 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 JSPs currently not
file relative to the web.xml file supported
taglib-location Java No Pathname relative to the root of the JSPs currently not
web application where the tag supported
library is stored
url-pattern Java Yes URL pattern to associate with a See Section 10 of Java
servlet Servlet 2.2 spec
Table 20–2 XML Elements Defined for Servlet Deployment Descriptors (Cont.)
XML Element Name Defined By Supported? Description Comment
web-app Java No Configuration for a web application Only one web
application is
currently supported
welcome-file Java Yes Specifies a welcome-file name --
welcome-file-list Java Yes Defines a list of files to display Example:
when a folder is referenced through “index.html”
an HTTP GET
Note:
■ Note 1: The following parameters defined for the web.xml file
by Java are usable only by J2EE-compliant EJB 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
■ Note 2: The following elements are used to define 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 file to generate ACLs
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 file, as specified by the Java Servlet 2.2 specification.
8. The XML DB Servlet Container is invoked in the Java VM inside Oracle. If the
specified 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.
See Also: Chapter 19, "Using FTP, HTTP, and WebDAV Protocols"
try
{
env.put(Context.INITIAL_CONTEXT_FACTORY,
"oracle.xdb.spi.XDBContextFactory");
Context ctx = new InitialContext(env);
String [] docarr = req.getParameterValues("doc");
String doc;
and update the /xdbconfig.xml file 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 file with any WebDAV-capable text editor, or
by using the updateXML() SQL operator.
Part VI of this manual introduces you to Oracle SQL*Loader for loading your 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:
■ Chapter 21, "Managing Oracle XML DB Using Oracle Enterprise Manager"
■ Chapter 22, "Loading XML Data into Oracle XML DB"
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 configure, create and
manage Repository resources, and database objects such as XML schemas and
XMLType tables.
It contains the following sections:
■ Introducing Oracle XML DB and Oracle Enterprise Manager
■ Oracle Enterprise Manager Oracle XML DB Features
■ The Enterprise Manager Console for Oracle XML DB
■ Configuring Oracle XML DB with Enterprise Manager
■ Creating and Managing Oracle XML DB Resources with Enterprise Manager
■ Managing XML Schema and Related Database Objects
See Also:
■ Chapter 2, "Getting Started with Oracle XML DB"
■ Appendix A, "Installing and Configuring Oracle XML DB"
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. Is 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.
See Also:
■ Chapter 3, "Using Oracle XML DB"
■ Chapter 5, "Structured Mapping of XMLType"
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.
Figure 21–1 Managing Oracle XML DB with Enterprise Manager: Main Tasks
This configuration XML schema is registered when Oracle XML DB is installed. The
configuration property sheet has two tabs:
■ For System Configurations. General parameters and FTP and HTTP protocol
specific parameters can be displayed on the System Configurations tab.
■ For User Configurations. Custom parameters can be displayed on the User
Configurations tab.
To configure items in Oracle XML DB, select the Configuration node under XML
Database in the Navigator. See Figure 21–3 and See Figure 21–4.
The XML Database Parameters page displays a list of configuration parameters for
the current XML database. You can also access this page from the XML Database
Management main window > Configure XML Database.
When you click the Configuration 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:
■ Parameter Name -- Lists the name of the parameter.
■ Value -- Displays the current value of the parameter. This is an editable field.
■ Default -- Indicates whether the value is a default value. A check mark indicates
a default value.
■ Dynamic -- Indicates whether or not the value is dynamic. A check mark
indicates dynamic.
■ 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 field for the
parameter and making the change. Click on 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.
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:
■ 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.
■ 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 configured through the TNS listener to listen on arbitrary ports. HTTP listens
on a non-standard, non-protected port.
Category: Generic
■ case-sensitive
Category: FTP
■ ftp-port: Enterprise Manager manages FTP as a Shared Server presentation. It
can be configured using TNS listeners to listen on arbitrary ports.
■ ftp-logfile-path: The file path of the FTP Server log file.
■ ftp-log-level: The level of logging for FTP error and warning conditions.
Category: HTTP
■ http-port: Enterprise Manager manages HTTP as a Shared Server presentation.
It can be configured using TNS listeners to listen on arbitrary ports.
■ session-timeout: The maximum time the server will wait for client responses
before it breaks a connection.
■ server-name: Hostname to use by default in HTTP redirects and servlet API.
■ http-logfile-path: The file path of the HTTP server log file.
■ http-log-level: The level of logging for HTTP error and warning conditions.
■ welcome-file-list: The list of welcome files used by the server.
Figure 21–5 Enterprise Manager: Oracle XML DB Resources Tree Showing Resources
Folder Selected
Security Page
Oracle XML DB Resources Security page changes the ACL associated with the XML
DB resource container or file. Use the ACL files to restrict access to all XML DB
resources. When you change the ACL file for the resource, you change the access
privileges for the resource file. See Figure 21–8.
To specify a new ACL file:
1. Click on the Specify a new ACL File option box and then choose a new ACL
file from the drop down list in the File Name field.
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 field.
Figure 21–8 Enterprise Manager: Individual Oracle XML DB Resource - Security Page
You can perform the following Oracle XML DB tasks from the Enterprise Manager
Content Menu:
Create Resource
Figure 21–10 shows how you can use the Create XML DB Resource dialog box to
create an XML DB resource container or file. From the XML DB Resource dialog you
can name the resource and then either create a new resource container or create a
new resource file, designating the location of the file as either a local file, a file at a
specified URL, or specifying the contents of the file.
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 field, you can change
the location by clicking on the Change Location button to the right of the
Location field.
2. Specify whether the resource you are creating is a container or a file. If you
create a file by choosing Create a new resource file, you can select from one of
three file type location options:
– Local File -- Select Use a file in the local file system to browse for a file
location on your network.
– File at URL -- Select Use a file at the URL to enter the location of the file on
the internet or intranet.
– File Contents -- Select Specify the resource contents here to enter the
contents of a file in the edit box located at the bottom of the Create XML DB
Resource dialog box.
Figure 21–10 Enterprise Manager: Create Oracle XML DB Resource Dialog Box
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.
Show Contents
Figure 21–12 is an example of a Show Contents dialog box. It displays the contents
of the selected resource file.
Figure 21–12 Enterprise Manager: Show Contents Menus of Individual Oracle XML
DB Resource
Show Grantee
Figure 21–11 shows the Show Grantee of XML DB Resource dialog box. It displays
a list of all granted privileges on a specified 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.
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.
Figure 21–14 Adding or Revoking Privileges with Users > user> XML
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.
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 on the up arrow to remove it.
– write-acl-Ref
– update-acl
– linkto
– unlinkfrom
– dav:lock
– dav:unlock
– dav:read-acl
■ Aggregate Privileges
– dav:read (read-properties, read-contents)
– dav:write-acl
– dav:all (dav:read, dav:write, dav:read-acl, dav:write-acl, dav:look,
dav:unlock)
■ 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 21–16 shows top level
elements servlet and LINK. The number and names of these elements are
dictated by the relevant XML schema definition, which in this case is:
http://xmlns.oracle.com/XDBStandard.xsd.
■ 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.
■ 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.
■ 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.
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:
■ Global, that is XML schema is visible to public
■ Local, that is XML schema is visible only to the user creating it
You can obtain the XML schema in one of four ways:
■ By specifying the location of the file in the local file system
■ By specifying the XML Database (Repository) resource where the XML schema
is located
■ By specifying the URL location
■ By cutting and pasting the text form another screen
Options Page
From the Options page you can select the following options:
■ Generate the object types based on this XML schema
■ Generate tables based on this XML schema
■ Generate Java beans based on this XML schema
■ Register this XML schema regardless of any errors
See Figure 21–19. Press Create from either the General Tab or Options Tab to register
this XML schema.
Creating Tables
You have two main options when creating tables:
■ "Creating an XMLType Table" on page 21-35
■ "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.
Figure 21–22 Enterprise Manager: Creating Tables With XMLType Column - General
Page
5. From this screen you can specify for a particular XMLType column, whether it is
XML schema-based or non-schema-based.
■ 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 defined by the XML schema.
* Store as CLOB. When you select CLOB the LOB Storage tab dialog
appears. Here you can customize the CLOB storage.
■ If it is non-schema-based you do not need to change the default settings.
Figure 21–23 Enterprise Manager: Creating Tables With XMLType Column - XMLType
Options
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 Identifier (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".
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 with XMLType columns, first 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.
This chapter describes how XML datacan be loaded into Oracle XML DB using
SQL*Loader.
It contains the following sections:
■ Loading XMLType Data into Oracle9i Database
■ Using SQL*Loader to Load XMLType Columns
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.
Note: You cannot specify an SQL string for LOB fields. This is
true even if you specify LOBFILE_spec.
Because LOBs can be quite large, SQL*Loader is able to load LOB data from either a
primary datafile (in line with the rest of the data) or from LOBFILEs. This section
addresses the following topics:
■ Loading LOB Data from a Primary Datafile
■ Loading LOB Data from an External LOBFILE (BFILE)
■ Loading LOB Data from LOBFILEs
■ Loading LOB Data from a Primary Datafile
To load internal LOBs (BLOBs, CLOBs, and NCLOBs) or XML columns from a
primary datafile, you can use the following standard SQL*Loader formats:
■ A single LOB field into which the entire contents of a file can be read
■ Predetermined size fields (fixed-length fields)
■ Delimited fields (that is, TERMINATED BY or ENCLOSED BY)
■ The clause PRESERVE BLANKS is not applicable to fields read from a
LOBFILE.
■ Length-value pair fields (variable-length fields)--VARRAW, VARCHAR, or
VARCHARC loader datatypes--are used for loading from this type of field.
All of the previously mentioned field types can be used to load XML columns.
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:
■ Chapter 23, "Exchanging XML Data Using Advanced Queueing (AQ)"
23
Exchanging XML Data Using Advanced
Queueing (AQ)
This chapter describes how XML data can be exchanged using Oracle Advanced
Queueing. It contains the following sections:
■ What Is AQ?
■ How Do AQ and XML Complement Each Other?
■ Internet Data Access Presentation (IDAP)
■ IDAP Architecture
■ Enqueue Using AQ XML Servlet
■ Dequeue Using AQ XML Servlet
■ IDAP and AQ XML Schemas
■ Frequently Asked Questions (FAQs): XML and Advanced Queuing
What Is AQ?
Oracle Advanced Queuing (AQ) provides database integrated message queuing
functionality. AQ:
■ Enables and manages asynchronous communication of two or more
applications using messages
■ 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 flows.
Advanced
queues
MQ Series
Internet Internet
Propagation Propagation
(Oracle
Net)
Advanced Advanced
queues queues
Global Agents,
Global Subscriptions,
Global Events
Advantages of Using AQ
AQ provides the flexibility of configuring communication between different
applications.
■ The receiver processes IDAP messages that have correct namespaces; for the
requests with incorrect namespaces, the receiver returns an invalid request
error.
■ The SOAP namespace has the value:
http://schemas.xmlsoap.org/soap/envelope/
■ The IDAP namespace has the value:
http://ns.oracle.com/AQ/schemas/access
IDAP Architecture
Figure 23–2 shows the following components needed to send HTTP messages:
■ 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.
■ The Web server or ServletRunner which hosts the AQ servlet that can
interpret the incoming XML messages, for example, Apache/Jserv or Tomcat.
■ Oracle9i Server/Database. The AQ servlet connects to Oracle9i database to
perform operations on your queues.
XML Oracle9i
Messages Server
over HTTP
AQ
Servlet
AQ Client AQ Queue
Web Server
■ Store more than one type of XML document in the same queue. The documents
are stored internally as CLOBs.
■ Selectively dequeue messages with XMLType attributes using the operators
existsNode(), extract(), and so on.
■ Define transformations to convert Oracle objects to XMLType.
■ Define rule-based subscribers that query message content using XMLType
operators such as existsNode() and extract().
Example 23–1 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',
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 defining transformations that convert the type used by the
Order Entry application to the type used by Overseas shipping, see Oracle9i
Application Developer’s Guide - Advanced Queuing the section on Creating
Transformations in Chapter 8.
begin
dopt.wait := 1;
dopt.consumer_name : = 'Overseas_Shipping';
EXCEPTION
WHEN no_messages THEN
dbms_output.put_line (' ---- NO MORE ORDERS ---- ');
new_orders := FALSE;
END;
END LOOP;
end;
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
queues. At each region, orders in these regional booked orders queues are
processed in the order of the shipping priorities.
EXECUTE dbms_aqadm.create_queue ( \
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>
</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>
</message>
</message_set>
<AQXmlCommit/>
</AQXmlSend>
</Body>
</Envelope>
In the BooksOnline scenario, assume that the East shipping application receives
AQ messages with a correlation identifier 'RUSH' over the Internet.
<AQXmlCommit/>
</AQXmlReceive>
</Body>
</Envelope>
See Also:
■ Oracle9i Application Developer’s Guide - Advanced Queuing,
Chapter 8, for more detail on how to implement structured
message payloads applications using either DBMS_AQADM or
Java (JDBC)
■ Oracle9i Supplied PL/SQL Packages and Types Reference for more
information about DBMS_TRANSFORM.
CREATE TYPE mypayload_type as OBJECT (xmlDataStream CLOB, dtd CLOB, pdf BLOB);
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?
Do I have to use XML SQL Utility (XSU) in order to insert an XML file into a table
before processing it, or can I enqueue an XML file 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
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 notification framework. This
allows you register a PL/SQL callback which is invoked asynchronously when a
message shows up in a queue.
IDAP in addition has the following key properties not defined by SOAP:
■ Transactional behavior. You can perform AQ operations in a transactional
manner. You transaction can span multiple IDAP requests.
■ Security. All the IDAP operations can be done only by authorized and
authenticated users.
This appendix describes the ways you can manage and configure your Oracle XML
DB applications. It contains the following sections:
■ Installing Oracle XML DB
■ Installing or Reinstalling Oracle XML DB from Scratch
■ Upgrading an Existing Oracle XML DB Installation
■ Configuring Oracle XML DB
■ Oracle XML DB Configuration Example
■ Oracle XML DB Configuration API
Post Installation
Oracle XML DB uses dynamic protocol registration to setup FTP and HTTP listener
service with the local listener. So, make certain that the listener is up, when
accessing any 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.
For example:
catqm.sql change_on_install XDB TEMP
Note: Make sure that the database is started with Oracle9i Release
2 (9.2.0) compatibility or higher.
Post Installation
After the manual installation, carry out these tasks:
1. Add the following dispatcher entry to the init.ora file:
dispatchers="(PROTOCOL=TCP) (SERVICE=<sid>XDB)"
each session, the current version of the configuration is bound to that session. The
session will use this configuration for its life, unless you invoke an explicit call to
refresh to the latest configuration.
<sysconfig>
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-specific parameters are grouped inside the <protocolconfig> tag.
<userconfig>
The <userconfig> section contains any parameters that you may want to add.
<protocolconfig>
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 specific parameters under
sections <httpconfig> and <ftpconfig> respectively.
<httpconfig>
Inside <httpconfig> there is a further subsection, <webappconfig> that
corresponds to Web-based applications. It includes Web application specific
parameters, for example, icon name, display name for the application, list of
servlets in Oracle XML DB, and so on.
See Also:
■ Chapter 19, "Using FTP, HTTP, and WebDAV Protocols",
Table 19–1, Table 19–2, and Table 19–3, for a list of protocol
configuration parameters.
■ Chapter 20, "Writing Oracle XML DB Applications in Java",
"Configuring the Oracle XML DB Example Servlet" on
page 20-12.
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>
<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>
<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>
cfg_get() is auto-commit.
Example A–2 Updating the Configuration File Using cfg_update() and cfg_get()
If you have a few parameters to update in the configuration file, 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 updat, the preceding example may prove too
cumbersome. Use instead FTP, HTTP, or Oracle Enterprise Manager.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
the chapter on DBMS_XDB
This appendix includes introductory information about the W3C XML Schema
Recommendation. It contains the following sections:
■ Introducing XML Schema
■ XML Schema Components
■ Simple Types
■ Anonymous Type Definitions
■ Element Content
■ Annotations
■ Building Content Models
■ Attribute Groups
■ Nil Values
■ Building Content Models
■ XML Schema Example, PurchaseOrder.xsd
See Also:
■ http://www.w3.org/TR/xmlschema-0/ Primer
■ http://www.w3.org/TR/xmlschema-1/ Structures
■ http://www.w3.org/TR/xmlschema-2/ Datatypes
■ http://w3.org/XML/Schema
■ http://www.oasis-open.org/cover/schemas.html
■ http://www.xml.com/pub/a/2000/11/29/schemas/part1
.html
</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>
<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"/>
<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>
Prefix xsd:
Each of the elements in the schema has a prefix 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 prefix xsd: is used by convention to denote the XML Schema
namespace, although any prefix can be used. The same prefix, and hence the same
association, also appears on the names of built-in simple types, such as,
xsd:string. This identifies 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 prefix.
Primary Components
The primary components, which may (type definitions) or must (element and
attribute declarations) have names are as follows:
■ Simple type definitions
■ Complex type definitions
■ Attribute declarations
■ Element declarations
Secondary Components
The secondary components, which must have names, are as follows:
■ Attribute group definitions
■ Identity-constraint definitions
■ Model group definitions
■ Notation declarations
Helper Components
Finally, the “helper” components provide small parts of other components; they are
not independent of their context:
■ Annotations
■ Model groups
■ Particles
■ Wildcards
■ Attribute Uses
■ Complex types, allow elements in their content and may carry attributes
■ Simple types, cannot have element content and cannot carry attributes.
There is also a major distinction between the following:
■ Definitions which create new types (both simple and complex)
■ Declarations which enable elements and attributes with specific names and types
(both simple and complex) to appear in document instances
This section defines complex types and declares elements and attributes that appear
within them.
New complex types are defined using the complexType element and such
definitions 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 PurchaseOrderType
In contrast, the PurchaseOrderType definition 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>
global element, on other words, one that has been declared under schema rather
than as part of a complex type definition. 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.
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.
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:
■ Default attribute values apply when attributes are missing
■ Default element values apply when elements are empty
The fixed 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 fixed 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 B–1 summarizes the attribute values used in element and attribute
declarations to constrain their occurrences.
Table B–1 Occurrence Constraints for XML Schema Elements and Attributes
Elements Attributes Notes
(minOccurs, maxOccurs) use, fixed,default
fixed, default
(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
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 definition.
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 Conflicts
The preceding section described how to:
■ Define new complex types, such as, PurchaseOrderType
■ Declare elements, such as, purchaseOrder
■ 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 conflict.
For example:
If the two things are both types, say a complex type called USStates and a simple
type called USStates, there is a conflict.
If the two things are a type and an element or attribute, such as when defining a
complex type called USAddress and declaring an element called USAddress, there
is no conflict.
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 conflict. Such elements are
sometimes called local element declarations.
If the two things are both types and you define one and XML Schema has defined
the other, say you define a simple type called decimal, there is no conflict. 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 B–2 lists all the simple types built
into XML Schema, along with examples of the different types.
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 float formats representing “one hundred”.
However, rules have been established for this type that define 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” prefix signals time periods in the Gregorian calender.
New simple types are defined 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 define 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 definition on the
built-in simple type integer, whose range of values also includes integers less than
10000 and greater than 99999.
To define myInteger, restrict the range of the integer base type by employing two
facets called minInclusive and maxInclusive:
The example shows one particular combination of a base type and two facets used
to define 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 definition. 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}"
that is read “three digits followed by a hyphen followed by two upper-case ASCII
letters”:
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 specified 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 B–3. Atomic types, list types, and the
union types described in the next section are collectively called simple types. The
value of an atomic type is indivisible from XML 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:
■ NMTOKENS
■ IDREFS
■ ENTITIES
In addition to using the built-in list types, you can create new list types by
derivation from existing atomic types. You cannot create list types from existing
list types, nor from complex types. For example, to create a list of myInteger's:
Several facets can be applied to list types: length, minLength, maxLength, and
enumeration. For example, to define a list of exactly six US states (SixUSStates),
we first define a new list type called USStateList from USState, and then we
derive SixUSStates by restricting USStateList to only six items:
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 defined 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 Amérique Latine
Even though "Amérique Latine" may exist as a single string outside of the list,
when it is included in the list, the whitespace between Amérique 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:
When we define 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>
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.
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 define 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 define 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:
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
We use the complexType element to start the definition 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 confined to the deepest
subelements.
To illustrate, consider the following snippet from a customer letter that uses some of
the same elements as the purchase order:
Notice the text appearing between elements and their child elements. Specifically,
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:
<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
defined 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 definition 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 specified 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"/>
<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>
This compact syntax works because a complex type defined 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
indeed a mixture of characters and elements. In fact, anyType is the default type
when none is specified, so the preceding could also be written as follows:
<xsd:element name="anything"/>
Annotations
XML Schema provides three elements for annotating schemas for the benefit 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 definition:
<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.
<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 simplified 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 redefine PurchaseOrderType as:
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>
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
To provide more information about each item in 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 definition:
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:
<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: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 defined and edited
in one place and referenced in multiple definitions 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 definitions.
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 defined 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 prefix (such as xsi:) associated with that namespace. (As
with the xsd: prefix, the xsi: prefix 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.
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)>
...
</complexType>
</element></schema>
DTD Limitations
DTDs, also known as XML Markup Declarations, are considered deficient in
handling certain applications which include the following:
■ Document authoring and publishing
■ Exchange of metadata
■ E-commerce
■ Inter-database operations
DTD limitations include:
■ No integration with Namespace technology, meaning that users cannot import
and reuse code.
■ No support of datatypes other than character data, a limitation for describing
metadata standards and database schemas.
■ Applications need to specify document structure constraints more flexibly than
the DTD allows for.
</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>
</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>
</xs:simpleType>
</xs:element>
</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>
See Also:
■ http://www.w3.org/TR/xpath
■ http://www.w3.org/TR/xpath20/
■ http://www.zvon.org/xxl/XPathTutorial/General/exa
mples.html
■ http://www.mulberrytech.com/quickref/XSLTquickref
.pdf
■ http://www.oreilly.com/catalog/xmlnut/chapter/ch0
9.html
■ http://www.w3.org/TR/2002/NOTE-unicode-xml-200202
18/ for information about using unicode in XML.
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.
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 filter sets of nodes. A
location path matches the production LocationPath.
Expressions are parsed by first 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.
Table C–1 XPath: Location Path Examples Using Unabbreviated Syntax (Cont.)
Unabbreviated Location Path Description
/descendant::figure[position()=42] Selects the forty-second figure element in the document
/child::doc/child::chapter[position()=5]/child::section Selects the second section of the fifth chapter of the doc
[position()=2] 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 fifth para child of the context node that has a type
attribute with value warning
child::para[position()=5][attribute::type= "warning"] Selects the fifth 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 C–2 XPath: Location Path Examples Using Abbreviated Syntax (Cont.)
Abbreviated Location Path Description
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 fifth para child of the context node that has a type
attribute with value warning
para[5][@type="warning"] Selects the fifth 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
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.
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.
Note: Location path //para[1] does not mean the same as the
location path /descendant::para[1]. The latter selects the first
descendant para element; the former selects all descendant para
elements that are the first para children of their parents.
and so will select all para descendant elements of the context node.
and so will select the title children of the parent of the context node.
Abbreviation Summary
AbbreviatedAbsoluteLocationPath ::= '//' RelativeLocationPath
AbbreviatedRelativeLocationPath ::= RelativeLocationPath '//' Step
AbbreviatedStep ::= '.' | '..'
AbbreviatedAxisSpecifier ::= '@'?
Nodes
The tree contains nodes. There are seven types of node:
■ Root Nodes
■ Element Nodes
■ Text Nodes
■ Attribute Nodes
■ Namespace Nodes
■ Processing Instruction Nodes
■ 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 specified 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 prefix and
there is no applicable default namespace.
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 identifier (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
characterdata. 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 <. 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 < and & respectively.
Note: When a text node that contains a < character is written out
as XML, the < character must be escaped by for example, using <,
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
specified in the XML Recommendation. A text node does not have
an expanded-name.
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.
Note: This is different from the DOM, which does not treat the
element bearing an attribute as the parent of the attribute.
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.
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.
Namespace Nodes
Each element has an associated set of namespace nodes, one for each distinct
namespace prefix that is in scope for the element (including the xml prefix, 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
will be the same node as the namespace nodes of another element node. This means
that an element will have a namespace node:
■ For every attribute on the element whose name starts with xmlns:;
■ For every attribute on an ancestor element whose name starts xmlns: unless the
element itself or a nearer ancestor redeclares the prefix;
■ 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 prefix
(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 prefix; if it is relative, it must be resolved just like a namespace URI
in an expanded-name.
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.
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:
■ A local part. This is a string.
■ A namespace URI. The namespace URI is either null or a string. If specified in
the XML document it can be a URI reference as defined in RFC2396; this means
it can have a fragment identifier 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, defined on all the nodes in the document
corresponding to the order in which the first 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 first 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 defined 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
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 specifications:
■ The XPath data model defines the information in an XML document that is
available to an XPath processor. The data model is defined in XQuery 1.0 and
XPath 2.0 Data Model.
■ The static and dynamic semantics of XPath are formally defined in XQuery 1.0
Formal Semantics. This is done by mapping the full XPath language into a
"core" subset for which the semantics is defined. This document is useful for
implementors and others who require a rigorous definition of XPath.
■ The library of functions and operators supported by XPath is defined in XQuery
1.0 and XPath 2.0 Functions and Operators.
What Is a Namespace?
An XML namespace is a collection of names, identified 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 qualified names, which contain a
single colon, separating the name into a namespace prefix and a local part.
The prefix, 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 identifiers that are universally unique. Mechanisms are
provided for prefix scoping and defaulting.
URI references can contain characters not allowed in names, so cannot be used
directly as namespace prefixes. Therefore, the namespace prefix 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 prefix with a URI reference;
software which supports this namespace proposal must recognize and act on these
declarations and prefixes.
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 prefix. These attributes, like any
other XML attributes, can be provided directly or by default.
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.
The following example namespace declaration associates the namespace prefix 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>
Qualified Names
In XML documents conforming to the W3C Namespace Recommendation, some
names (constructs corresponding to the nonterminal Name) may be given as
qualified names, defined 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 ]
Attributes are either namespace declarations or their names are given as qualified
names:
Attribute
[12] Attribute::= NSAttName Eq AttValue|QName Eq AttValue [NSC:Prefix Declared]
Element names and attribute types are also given as qualified names when they
appear in declarations in the DTD:
Namespace Scoping
The namespace declaration is considered to apply to the element where it is
specified 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>
Namespace Defaulting
A default namespace is considered to apply to the element where it is declared (if
that element has no namespace prefix), and to all elements with no prefix within the
content of that element. If the URI reference in a default namespace declaration is
empty, then unprefixed 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>
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>
Uniqueness of Attributes
In XML documents conforming to this specification, no tag may contain two
attributes which:
■ Have identical names, or
■ Have qualified names with the same local part and with prefixes 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>
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 specification does not define 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 specification does not define an information set for
documents which use relative URI references in namespace declarations. This is in
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 unexpanded
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 Recommnedation, 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 final URI used to retrieve the resource after all
redirection.
The value of these properties does not reflect any URI escaping that may be
required for retrieval of the resource, but it may include escaped characters if these
were specified 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
specification does not define 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.
Synthetic Infosets
This specification 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).
This appendix describes introductory information about the W3C XSL and XSLT
Recommendation. It contains the following sections:
■ Introducing XSL
■ XSL Transformation (XSLT)
■ XML Path Language (Xpath)
■ CSS Versus XSL
■ XSL Stylesheet Example, PurchaseOrder.xsl
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.
See Also:
■ Oracle9i XML Case Studies and Applications in particular, the
chapters that describe customizing content, Oracle9i Wireless
Edition, and customizing presentation with XML and XSL.
■ http://www.oasis-open.org/cover/xsl.html
■ http://www.mulberrytech.com/xsl/xsl-list/
■ http://www.builder.com/Authoring/XmlSpot/?tag=st.cn.sr1.ssr.
bl_xml
■ http://www.zvon.org/HTMLonly/XSLTutorial/Books/Book1/i
ndex.html
■ Chapter 6, "Transforming and Validating XMLType Data"
This specification defines the syntax and semantics of the XSLT language. A
transformation in the XSLT language is expressed as a well-formed XML document
Namespaces in XML
A namespace is a unique identifier or name. This is needed because XML
documents can be authored separately with different DTDs or XML Schemas.
In addition the XSLT 1.0 extension mechanism provides for an additional built-in
transformation functionality.
Benefits of the extensions come at the price of portability. Since XSLT 1.0 provides
no details or guidance on the implementation of extensions, today any user-written
or built-in extensions are inevitably tied to a single XSLT processor.
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.
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/>
</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>
</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>
</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"/>
<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/>
<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: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>
</td>
</tr>
</tbody>
</xsl:for-each>
</xsl:for-each>
</table>
</xsl:for-each>
</FONT>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
This appendix contains a quick reference for the following Oracle XML DB Java
APIs:
■ Java DOM API For XMLType
■ Java Bean API for XMLType
■ Oracle XML DB Resource API for Java/JNDI
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-1
Java DOM API For XMLType
See Also:
■ Oracle9i XML API Reference - XDK and Oracle XML DB
■ Chapter 9, "Java and Java Bean APIs for XMLType"
Table E–1 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.
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.
Table E–1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes (Cont.)
Java DOM API for XMLType Description
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
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.
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-3
Java DOM API For XMLType
Table E–1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes (Cont.)
Java DOM API for XMLType Description
XMLType Implements Java methods for the SQL type SYS.XMLTYPE.
(package oracle.xdb) 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,
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();
Table E–1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes (Cont.)
Java DOM API for XMLType Description
extract() Extracts and returns the given set of nodes from the XMLType. The set of
nodes is specified by the XPath expression. The original XMLType remains
unchanged. Works only in the thick case. If no nodes match the specified
expression, returns NULL. Throws java.sql.SQLException
public XMLType extract( String xpath, String nsmap);
Parameters:
xpath - xpath expression which specifies for which nodes to search
nsmap - map of namespaces which resolves the prefixes 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 specified by the xpath expression. Returns TRUE if specified nodes exist in
the XMLType; otherwise, returns FALSE. Throws
java.sql.SQLException
public boolean existsNode( String xpath, String nsmap);
Parameters:
xpath - xpath expression that specifies for which nodes to search
nsmap - map of namespaces that resolves prefixes in the xpath
expression;format is "xmlns=a.com xmlns:b=b.com",
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();
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-5
Java Bean API for XMLType
See Also: Chapter 9, "Java and Java Bean APIs for XMLType"
Table E–2 Mapping From XML Schema Entities to Java Bean Classes
XML Schema
Entity Java Bean Class Description
Attribute Get/setAttribute{attrname} Gets/sets the attribute for the document child
element and its specified attribute.
Complextype Get/set{complextype For complex children, separate bean classes get
classname}. generated. Extras (processing instructions or
comments). DOM classes for
processing instructions and comments are
returned.
Scalar data Get/set{scalar type name} Children with maxoccurs > 1
Get/set List of type of child.
Table E–3 lists the mapping used by the Java Bean API for XMLType between XML
Schema, SQL, and Java datatypes.
Table E–3 Mapping From XML Schema to SQL and Java Datatypes
XML Schema Datatype SQL Datatype Java Bean Datatype
Boolean boolean boolean
String URI reference ID
IDREF ENTITY NOTATION
Language NCName Name
java.lang.String String DECIMAL
INTEGER LONG SHORT
INT POSITIVEINTEGER NONPOSITIVEINTEGER
oracle.sql.Number int FLOAT
Table E–3 Mapping From XML Schema to SQL and Java Datatypes (Cont.)
XML Schema Datatype SQL Datatype Java Bean Datatype
DOUBLE oracle.sql.Number float
TIMEDURATION TIMEPERIOD RECURRINGDURATION
DATE TIME MONTH,YEAR
RECURRINGDATE java.sql.Timestamp Time
REF oracle.sql.Ref Ref
BINARY oracle.sql.RAW Byte[]
QNAME java.lang.String String
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-7
Oracle XML DB Resource API for Java/JNDI
Table E–4 Oracle XML DB Resource API for Java/JNDI (oracle.xdb.spi) (Cont.)
oracle.xdb.spi Class Description
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 modification 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 modification 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
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-9
Oracle XML DB Resource API for Java/JNDI
Table E–4 Oracle XML DB Resource API for Java/JNDI (oracle.xdb.spi) (Cont.)
oracle.xdb.spi Class Description
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 modification 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 E–4 Oracle XML DB Resource API for Java/JNDI (oracle.xdb.spi) (Cont.)
oracle.xdb.spi Class Description
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 modification date of the resource.
public void - setLastModDate( Date d);
Parameter: d - Last modification 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.
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-11
Oracle XML DB Resource API for Java/JNDI
This appendix provides a summary of the following Oracle XML DB SQL and
PL/SQL APIs:
■ XMLType API
■ PL/SQL DOM API for XMLType (DBMS_XMLDOM)
■ PL/SQL Parser for XMLType (DBMS_XMLPARSER)
■ PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
■ DBMS_XMLSCHEMA
■ Oracle XML DB XML Schema Catalog Views
■ Resource API for PL/SQL (DBMS_XDB)
■ RESOURCE_VIEW, PATH_VIEW
■ DBMS_XDB_VERSION
■ DBMS_XDBT
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-1
XMLType API
XMLType API
XMLType is a system-defined opaque type for handling XML data. XMLType has
predefined 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 F–1 lists the XMLType API functions.
See Also:
■ Oracle9i XML API Reference - XDK and Oracle XML DB
■ Chapter 4, "Using XMLType"
-- --
createXML() Static function for creating and returning an XMLType instance. The
string and clob parameters used to pass in the date must contain
STATIC FUNCTION createXML( xmlval IN well-formed and valid XML documents. The options are described
varchar2) RETURN XMLType deterministic in the following table.
STATIC FUNCTION createXML( xmlval IN clob) Parameters:
RETURN XMLType
xmlData - Actual data in the form of a CLOB, REF cursor,
STATIC FUNCTION createXML (xmlData IN clob, VARCHAR2 or object type.
schema IN varchar2, validated IN number := 0,
wellformed IN number := 0 ) RETURN XMLType schema - optional Schema URL to be used to make the input
deterministic conform to the given schema.
STATIC FUNCTION createXML ( xmlData IN validated - flag to indicate that the instance is valid according to the
varchar2, schema IN varchar2, validated IN given XMLSchema. (default 0)
number := 0, wellformed IN number := 0) wellformed - flag to indicate that the input is wellformed. If set,
RETURN XMLType deterministic then the database would not do well formed check on the input
STATIC FUNCTION createXML (xmlData IN instance. (default 0)
"<ADT_1>", schema IN varchar2 := NULL, element - optional element name in the case of the ADT_1 or REF
element IN varchar2 := NULL, validated IN CURSOR constructors. (default null)
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
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-3
XMLType API
getNumVal() Returns a numeric value, formatted from the text value pointed to
MEMBER FUNCTION getNumVal() RETURN by the XMLType instance. The XMLType must point to a valid text
number deterministic node that contains a numerical value.
transform() Transforms XML data using the XSL stylesheet argument and the
top-level parameters passed as a string of name=value pairs. If any
MEMBER FUNCTION transform(xsl IN argument other than the parammap is NULL, a NULL is returned.
XMLType, parammap in varchar2 := NULL)
RETURN XMLType deterministic Parameter
xsl - XSL stylesheet describing the transformation
parammap - top level parameters to the XSL - string of name=value
pairs
getRootElement() Gets the root element of the XMLType instance. Returns NULL if
the instance is a fragment.
MEMBER FUNCTION getRootElement return
varchar2 deterministic
getNamespace() 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.
MEMBER FUNCTION getNamespace return
varchar2 deterministic
schemaValidate() Validates the XML instance against its schema if it has not already
validated. For non-schema based documents an error is raised. If
MEMBER PROCEDURE schemaValidate validation fails an error is raised; else, the document’s status is
changed to validated.
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-5
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
setSchemaValidated() Sets the VALIDATION state of the input XML instance to avoid
schema validation.
MEMBER PROCEDURE setSchemaValidated(flag
IN BINARY_INTEGER := 1) Parameter: flag - 0 = NOT VALIDATED; 1 = VALIDATED; Default
value is 1.
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-7
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-9
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-11
PL/SQL DOM API for XMLType (DBMS_XMLDOM)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-13
PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)
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 F–5
summarizes the DBMS_XMLSCHEMA functions and procedures.
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-15
DBMS_XMLSCHEMA
DBMS_XMLSCHEMA contstants:
■ DELETE_RESTRICT, CONSTANT NUMBER := 1;
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-17
Oracle XML DB XML Schema Catalog Views
■ DELETE_INVALIDATE,CONSTANT NUMBER := 2;
■ DELETE_CASCADE, CONSTANT NUMBER := 3;
■ DELETE_CASCADE_FORCE, CONSTANT NUMBER := 4;
See Also: Chapter 16, "Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)"
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-19
Resource API for PL/SQL (DBMS_XDB)
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-21
DBMS_XMLGEN
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 F–8 summarizes the DBMS_XMLGEN functions and procedures.
See Also: Chapter 10, "Generating XML Data from the Database"
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, WebDAV, or JNDI
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 F–9 summarizes the Oracle XML DB Resource API for PL/SQL operators.
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-23
DBMS_XDB_VERSION
DBMS_XDB_VERSION
DBMS_XDB_VERSION along with DBMS_XDB implement the Oracle XML DB
versioning API.
Table F–10 summarizes the DBMS_XDB_VERSION functions and procedures.
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 onfiguration 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:
■ To customize the package to set up the appropriate configuration
■ To drop existing index preferences using dropPreferences()
■ To create new index preferences using createPreferences()
■ To create the ConText index using the createIndex()
■ To set up automatic synchronization of the ConText index using the
configureAutoSync()
Table F–11 summarizes the DBMS_XDBT functions and procedures.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-25
DBMS_XDBT
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:
■ Example Setup Scripts
■ Resource View and Path View Database and XML Schema
■ XDBResource.xsd: XML Schema for Representing Oracle XML DB Resources
■ acl.xsd: XML Schema for Representing Oracle XML DBACLs
■ xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-1
Example Setup Scripts
DBMS_LOB.fileclose(targetFile);
return charContent;
end;
/
show errors
declare
result boolean;
begin
result := dbms_xdb.createfolder(’/public/&4’);
end;
/
commit;
quit
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-3
Example Setup Scripts
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. Oracle XML DB- Supplied XML Schemas G-5
Example Setup Scripts
) = 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. Oracle XML DB- Supplied XML Schemas G-7
Example Setup Scripts
/
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
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>
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-9
Example Setup Scripts
<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>
Note:
■ The example XML schema, "XML Schema Example,
PurchaseOrder.xsd" is located in Appendix B, "XML Schema
Primer".
■ The example XSL file, "XSL Stylesheet Example,
PurchaseOrder.xsl" is located in Appendix D, "XSLT Primer".
if [ "$LOGNAME" = "oracle2" ]
then
ORAFTPPORT=2122
ORAHTTPPORT=8088
fi
echo "FTP Port = $ORAFTPPORT"
echo "HTTP Port = $ORAHTTPPORT"
ORASQLUSER=DOC92
ORASQLPASSWORD=DOC92
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-11
Resource View and Path View Database and XML Schema
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">
<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>
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-13
XDBResource.xsd: XML Schema for Representing Oracle XML DB Resources
</sequence>
</schema>
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 XDB ACL
documents.
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-15
acl.xsd: XML Schema for Representing Oracle XML DBACLs
<xdb:systemPrivileges>
<xdbacl:all>
<xdbacl:read-properties/>
<xdbacl:read-contents/>
<xdbacl:read-acl/>
<xdbacl:update/>
<xdbacl:bind/>
<xdbacl:unbind/>
<xdbacl:unlink/>
<xdbacl:write-acl-ref/>
<xdbacl:update-acl/>
<xdbacl:link/>
<xdbacl:resolve/>
</xdbacl:all>
</xdb:systemPrivileges>
</appinfo>
</annotation>
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "update" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "bind" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "unbind" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "unlink" 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" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "resolve" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "all" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-17
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
</schema>
xdbconfig.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">
<complexType><sequence>
<element name="sysconfig">
<complexType><sequence>
<!-- generic XDB properties -->
<element name="acl-max-age" type="positiveInteger"
default="1000"/>
<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="1"/>
type="xdbc:charset-mapping-type"/>
<element name="encoding-mappings"
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-19
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
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>
default="/sys/log/ftplog.xml"/>
<element name="log-level" type="unsignedInt"
default="1"/>
<element name="session-timeout"
type="unsignedInt"
default="6000"/>
</sequence></complexType>
</element>
type="unsignedShort" default="8080"/>
<element name="http-listener"
type="string"/>
<element name="http-protocol" type="string">
<!--simpleType>
<restriction base="string">
<enumeration value="tcp"/>
<enumeration value="tcps"/>
</restriction>
</simpleType-->
</element>
<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="1"/>
<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"
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-21
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
type="xdbc:servlet-config-type"/>
</sequence></complexType>
</element>
</sequence></complexType>
</element>
</sequence></complexType>
</element>
</sequence></complexType>
</element>
<!-- users can add any properties they want here -->
<element name="userconfig">
<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>
<simpleType>
<restriction base="positiveInteger">
<minInclusive value="100"/>
<maxInclusive value="999"/>
</restriction>
</simpleType>
</element>
<element name="OracleError">
<complexType><sequence>
<element name="facility" type="string"
default="ORA"/>
<element name="errnum"
type="unsignedInt"/>
</sequence></complexType>
</element>
</choice>
</sequence></complexType>
</element>
</sequence>
</complexType>
<complexType name="servlet-config-type">
<sequence>
<element name="servlet-mappings">
<complexType><sequence>
<element name="servlet-mapping" minOccurs="0"
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-23
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
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>
<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>
<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"/>
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-25
xdbconfig.xsd: XML Schema for Configuring Oracle XML DB
<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>
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 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-1
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 defined.
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 files 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.
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 first 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-2
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 Oracle 8 or later. Oracle Text is such a
cartridge, adding support for reading, writing, and searching text documents stored
within the database.
CDATA
See character data.
CDF
Channel Definition Format. Provides a way to exchange information about channels
on the internet.
CGI
See Common Gateway Interface.
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 file and creates a set of output classes that have
corresponding functionality. In the case of the XML Class Generator, the input file is
a DTD and the output is a series of classes that can be used to create XML
documents conforming with the DTD.
Glossary-3
CLASSPATH
The operating system environmental variable that the JVM uses to find 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.
CLOB
See Character Large Object.
command line
The interface method in which the user enters in commands at the command
interpreter’s prompt.
Content
The body of a resource in Oracle XML DB and what you get when you treat the
resource like a file and ask for its contents. Content is always an XMLType.
Glossary-4
CORBA
See Common Object Request Broker API.
CSS
See Cascading Style Sheets.
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 file
system. Internal DTDs are declared within the DOCTYPE declaration.
Glossary-5
DOM
See Document Object Model.
DOM fidelity
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 fidelity. DOM fidelity 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 fidelity by using a binary attribute,
SYS_XDBPD$.
DTD
See Document Type Definition.
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
identified 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.
entity
A string of characters that may represent either another string of characters or
special characters that are not part of the document’s character set. Entities and the
text that is substituted for them by the parser are declared in the DTD.
Glossary-6
existnode
The SQL operator that returns a TRUE or FALSE based upon the existence of an
XPath within an XMLType.
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-7
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 specified 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 specific 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 filesystems. 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-8
Hypertext Markup Language (HTML)
The markup language used to create the files 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.
iAS
See Oracle9iAS.
IDE
See Integrated Development Environment.
iFS
See Oracle9iFS.
INPATH
The SQL operator that is part of Oracle Text and is used for querying XMLType
datatypes for searching for specific text within a specific XPath.
instantiate
A term used in object-based languages such as Java and C++ to refer to the creation
of an object of a specific class.
interMedia
The collection of complex datatypes and their access in Oracle. These include text,
video, time-series, and spatial data.
Glossary-9
J2EE
See Java 2 Platform, Enterprise Edition.
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.
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 (EJB). See also Enterprise JavaBean.
Glossary-10
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.
JAXP
See Java API for XML Processing.
JDBC
See Java Database Connectivity.
JDeveloper
Oracle’s 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 Developer’s Kit.
JNDI
JServer
The Java Virtual Machine that runs within the memory space of the Oracle
database. In Oracle 8i Release 1 the JVM was Java 1.1 compatible while Release 2 is
Java 1.2 compatible.
Glossary-11
JVM
See Java virtual machine.
LAN
See local area network.
listener
A separate application process that monitors the input process.
LOB
See Large Object.
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 modification is
put on a queue, and the collection is locked and modified 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 defined by a W3C
Recommendation. For example, the <xsl:apply-templates/ > element is identified as
part of the XSL namespace. Namespaces are declared in the XML document or DTD
Glossary-12
before they are used be using the following attribute syntax:
xmlns:xsl="http://www.w3.org/TR/WD-xsl".
NCLOB
See National Character Large Object.
node
In XML, the term used to denote each addressable entity in the DOM tree.
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. Specific 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.
Glossary-13
object-relational
The term to describe a relational database system that can also store and manipulate
higher-order data types, such as text documents, audio, video files, and
user-defined objects.
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 file 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.
Glossary-14
ORACLE_HOME
The operating system environmental variable that identifies the location of the
Oracle database installation for use by applications.
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.
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.
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.
Glossary-15
path name
The name of a resource that reflects its location in the repository hierarchy. A path
name is composed of a root element (the first /), 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
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:
■ Database users.
■ 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 Definition Framework.
Glossary-16
renderer
A software processor that outputs a document in a specified format.
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 definition 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.
Glossary-17
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.
session
The active connection between two tiers.
SGML
See Structured Generalized Markup Language.
SOAP
See Simple Object Access Protocol.
SQL
See Structured Query Language.
SSI
See Server-Side Include.
SSL
See Secure Sockets Layer.
Glossary-18
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.
SYSTEM
Specifies 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).
Transviewer
The Oracle term used to describe the Oracle XML JavaBeans included in the XDK
for Java.
Glossary-19
TransXUtility
TransXUtility is a Java API that simplifies the loading of translated seed data and
messages into a database.
UDDI
See Universal Description, Discovery and Integration.
UIX
See User Interface XML.
URI
See Uniform Resource Identifier.
URL
See Uniform Resource Locator.
Glossary-20
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).
WAN
See wide area network.
WebDAV
See World Wide Web distributed authoring and versioning.
well-formed
The term used 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.
Glossary-21
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.
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 defined 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 Developer’s 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 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.
Glossary-22
XML Query
The W3C’s effort to create a standard for the language and syntax to query XML
documents.
XML Schema
The W3C’s 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 definition 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 definition
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 specifies 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
specifies the identification of individual entities or fragments within an XML
document using XPath navigation.
XSL
See eXtensible Stylesheet Language.
XSLFO
See eXtensible Stylesheet Language Formatting Object.
Glossary-23
XSLT
See eXtensible Stylesheet Language Transformation.
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.
Glossary-24
Index
A publish/subscribe support, 23-2
XML servlet, 23-11
access control entries (ACEs), 18-9 XMLType queue payloads, 23-6
elements in, 18-6 aggregating
access control lists (ACLs), 18-2 XSQL and XMLAgg, 10-51
bootstrap, 18-4 ALTER INDEX, using sections, 7-10
concurrency resolution, 18-5 any, 13-6
default, 18-4 attributes
defined, 13-5 collection, 5-38
features, 18-5 columnProps, 5-71
managing, 18-11 Container, 13-7
managing from Enterprise Manager, 21-22 defaultTable, 5-71
restrictions, 18-12 for root element, 3-21
security, row-level, 18-13 in elements, 5-26
setting the resource property, 18-11 maintainDOM, 5-22
summary, 1-12 maintainOrder, 5-38
term explained, 1-30 mapping any, 5-46
updating, 18-10 maxOccurs, 5-38
using, 18-9 namespaces, 5-5
accessing noNameSpaceSchemaLocation, 3-21
Java examples for, 9-4 of XMLFormat, 10-44
using XDBUriType, 3-44 passing to SYS_DBURIGEN, 12-30
with JDBC, 9-4 REF, 5-39, 5-48
XML documents using Java, 9-3 schemaLocation, 3-21, 5-9
adding setting to NULL, 4-35
XMLType columns, 4-8 SQLInLine, 5-38, 5-39
Advanced Queuing (AQ) SQLName, 5-25
definition, 23-2 SQLSchema, 5-25
enqueuing, 23-9 SQLType, 5-25, 5-29, 5-40
hub-and-spoke architecture support, 23-4 storeVarrayAsTable, 5-72
IDAP, 23-5 SYS_XDBPD$, 5-58
message management support, 23-4 tableProps, 5-71
messaging scenarios, 23-2 xdb.defaultTable, 3-40
point-to-point support, 23-2 xdb.SQLType, 3-30
Index-1
XMLAttributes in XMLElement, 10-7 API, A-9
XMLDATA, 4-13, 5-51 protocol server in Oracle XML DB, 19-4
XMLType, in AQ, 23-6 servlet, example, 20-12
xsi.NamespaceSchemaLocation, 5-5 servlets in Oracle XML DB, 20-4
xsi.noNamespaceSchemaLocation, 11-10 using Enterprise Manager, 21-7
authenticatedUser constraints
DBuri security, 12-37 on XMLType columns, 5-52
AUTO_SECTION_GROUP structured storage, 3-33
using, 7-10 using with XMLType tables, 3-22
CONTAINS, 4-38, 7-6
compared against existsNode, 7-38
B compared to existsNode(),extract(), 4-41
B*Tree, 1-12, 4-6, 5-52 contents, element, 13-6
indexing, 3-26 CREATE TABLE
bootstrap ACL, 18-4 XMLType storage, 5-51
createFolder(), 16-3
C createXML
inserting with CLOB, example, 4-15
CASCADE mode, 5-13 inserting with string, 4-16
cascading style sheets, see CSS, D-7 summarized, 3-17
catalog views, F-18 creating
cfg_get, 16-9, A-9 XML schema-based tables, columns, 5-23
cfg_refresh, A-10 XMLType columns, 4-8
CharacterData, 8-21 XMLType table, 4-7
Classes CSS and XSL, D-7
XDBContextFactory CTX_DDL.Add_Field_Section, 7-26
initial contexts for JNDI, 17-6 CTXAPP
CLOB storage of XMLType, 4-5 role, 7-6
collection attribute, 5-38 CTXSYS.PATH_SECTION_GROUP, 7-36
collection index, 5-61 CTXXPATH, 4-41
collections, 3-32, 18-6 indexes, 7-45
columnProps attribute, 5-71 storage preferences, 7-47
complexType cycling in complexTypes
collections, 3-32 self-referencing, 5-49
cycling, 5-49
cycling between, 5-47
elements, B-3 D
handling inheritance, 5-42 data integrity
in XML schema, explained, B-35 in structured, unstructured storage, 3-26
mapping any and any attributes, 5-46 Oracle XML DB, 3-33
mapping to SQL, 5-38 date
restrictions, 5-42 format conversion in updateXML(), 5-71
concatenating format conversions for XML, 5-63
elements using XMLConcat, 10-16 mapping to SQL, 5-36
configuring DBMS_METADATA, 12-5
Index-2
DBMS_XDB, F-19 defined, 12-2
AclCheckPrivileges, database objects, 18-13 examples, 12-25
cfg_get, A-9 notation for fragments, 12-12
cfg_refresh, A-10 stores references to data, 12-6
changePrivilege, 18-12 default table
checkPrivileges, 18-13 creating, 5-71
configuration management, 16-8 defining a, 3-40
getAclDocument, 18-12 defaultTable attribute, 5-71
Link, 16-2 deleteSchema, 9-21
LockResource, 16-2 deleting
overview, 16-2 resources, 3-39, 15-10
rebuilding hierarchical index, 16-11 rows using extract(), 4-37
security, 16-5 rows with XMLType columns, 4-37
DBMS_XDB_VERSION, 14-2, F-24 using extract(), 4-37
subprograms, 14-9 XML schema using DBMS_XMLSCHEMA, 5-13
DBMS_XDBT, F-25 DEPTH, 15-8
DBMS_XMLDOM, 8-5, 8-12, F-6 dequeuing
DBMS_XMLGEN, 10-20, F-22 with AQ XML servlet, 23-11
generating complex XML, 10-29 document
generating XML, 10-2 fidelity, explained, 1-4
DBMS_XMLPARSER, 8-24, F-13 no order, 5-65
DBMS_XMLSCHEMA, 5-7, F-15 no order with extract(), 5-69
deleteSchema, 5-7 order, 5-63
generateSchema() function, 5-18 order with extract(), 5-68
generateSchemas() function, 5-18 order, query rewrites with collection, 5-61
mapping of types, 5-32 ordering preserved in mapping, 5-69
registerSchema, 5-7 DOM
DBMS_XSLPROCESSOR, 8-28, F-14 differences, and SAX, 8-6
dbmsxsch.sql, F-15 explained, 1-28
DBUri, 12-10 fidelity, 5-21
and object references, 12-17 fidelity, default, 5-57
identifying a row, 12-15 fidelity, in structured storage, 4-5
identifying a target column, 12-16 fidelity, structured or unstructured
retrieving column text value, 12-16 storage, 3-27
retrieving the whole table, 12-14 fidelity, summarized, 1-4
security, 12-37 fidelity, SYS_XDBPD$, 5-22
servlet, 12-34 introduced, 8-5
servlet, installation, 12-36 Java API, 9-2
syntax guidelines, 12-13 Java API features, 9-16
URL specification, 12-12 Java API, XMLType classes, 9-18
XPath expressions in, 12-13 NodeList, 8-21
DBUri-refs, 12-9 non-supported, 8-5
HTTP access, 12-34 DOM API for PL/SQL, 8-5
where it can be used, 12-17 DOMDocument, 9-19
DBUriType dropping
Index-3
XMLType columns, 4-8 folder, defined, 13-4
DTD foldering
limitations, B-33 explained, 13-2
summary, 1-12
FORCE mode option, 5-13
E Frequently Asked Questions (FAQs)
elementFormDefault, 5-62 AQ and XML, 23-13
elements Oracle Text, 7-64
access control entries (ACEs), 18-6 versioning, 14-12
any, 13-6 FTP
complexType, B-3 configuration parameters, Oracle XMl DB, 19-5
Contents, Resource index, 13-6 creating default tables, 5-71
simpleType, B-3 protocol server, features, 19-7
XDBBinary, 13-11 protocol server, using, 3-44
XML, 8-4 function-based index
enqueuing creating in Enterprise Manager, 21-42
adding new recipients after, 23-14 creating on extract or existsNode, 4-38
using AQ XML servlet, 23-9 functions
EQUALS_PATH createXML, 4-15
summary, 15-5 DBUriType, 12-18
syntax, 15-8 isSchemaValid, 6-10
existsNode isSchemaValidated, 6-9
and CONTAINS, querying, 7-38 schemaValidate, 6-9
dequeing messages, 2-10 setSchemaValidated, 6-10
finding XML elements, nodes, 4-20 SYS_DBURIGEN, 12-29
indexing with CTXXPATH, 7-45 SYS_XMLAgg, 10-50
query rewrite, 5-52 SYS_XMLGEN, 10-41
XPath rewrites, 5-63 transform, 6-2
extract, 5-68 updateXML, 5-70
deleting, 4-37 XMLAgg, 10-17
dequeing messages, 2-10 XMLColAttVal, 10-19
mapping, 5-69 XMLConcat, 10-15
query rewrite, 5-52 XMLElement, 10-5
querying XMLType, 4-26 XMLForest, 10-9
rewrite in XPath expressions, 5-68 XMLSequence, 10-11, 10-13
extracting XMLTransform, 6-2
data from XML, 4-27 XMLType, 4-7
extractValue, 4-23
creating indexes, query rewrite, 5-67
query rewrite, 5-52 G
rewrites in XPath expressions, 5-66 genbean flag, 9-21
generating
DBUriType using SYS_DBURIGEN, 12-29
F generating XML
factory method, 12-25 DBMS_XMLGEN example, 10-29
Index-4
element forest accesses remote pages, 12-6
XMLColAttVal, 10-19 defined, 12-2
from SQL, DBMS_XMLGEN, 10-20 hub-and-spoke architecture, enabled by AQ, 23-4
one document from another, 10-12
SQL, SYS_XMLGEN, 10-41
SYS_XMLAgg, 10-50
I
using SQL functions, 10-2 IDAP
XML SQL Utility (XSU), 10-54 architecture, 23-6
XMLAgg, 10-17 transmitted over Internet, 23-5
XMLConcat, 10-15 XML schema, 23-12
XMLElement, 10-5 index
XMLForest, 10-9 collection, 5-61
XMLSequence, 10-11 Index Organized Table (IOT), 5-72
XSQL, 10-51 indexing
getClobVal B*Tree, 3-26
summarized, 3-17 function-based on existsNode(), 4-38
getNameSpace in structured, unstructured storage, 3-26
summarized, 3-17 Oracle Text, CTXXPATH, 7-45
getRootElement Oracle Text, XMLType, 7-34
summarized, 3-17 XMLType, 4-38
getXMLType, 9-18 Information Set
global XML schema, 5-11 W3C introducing XML, C-26
groups, 18-6 inheritance
in XML schema, restrictions in
complexTypes, 5-44
H INPATH, 4-39, 7-10
HASPATH, 4-39, 7-10 operator, 7-12
operator, 7-12 INPATH operator, 7-12
path existence searching, 7-20 inserting
path searching, 7-19 into XMLType, 4-9
HTTP new instances, 5-52
access for DBUri-refs, 12-34 XML data into XMLType columns, 4-15
accessing Java servlet or XMLType, 20-3 installing
accessing Repository resources, 13-11 from scratch, Oracle XML DB, A-2
configuration parameters, WebDAV, 19-5 manually without DBCA, A-3
creating default tables, 5-71 instance document
HttpUriType, DBUriType, 12-23 specifying root element namespace, 5-5
improved performance, 19-2 XML, described, B-36
Oracle XML DB servlets, 20-8 Internet Data Access Presentation (IDAP)
protocol server, features, 19-8 SOAP specification for AQ, 23-5
requests, 20-8 isFragment
servlets, 20-4 summarized, 3-17
UriFactory, 12-38 isSchemaValid, 6-10
using UriRefs to store pointers, 12-7 isSchemaValidated, 6-9
HttpUriType
Index-5
J mapping
collection predicates, 5-60
Java complexType any, 5-46
Oracle XML DB guidelines, 20-3 complexTypes to SQL, 5-38
using JDBC to access XMLType objects, 20-3 overriding using SQLType attribute, 5-33
writing Oracle XML DB applications, 20-2 predicates, 5-59
Java bean scalar nodes, 5-59
deleteSchema, 9-21 simpleContent to object types, 5-45
genbean flag, 9-21 simpleType XML string to VARCHAR2, 5-37
generated example, 9-24 simpleTypes, 5-34
generated names, 9-21 SQL to Java, 9-23
generated with XML schema registration, 5-17 type, setting element, 5-32
only for XML schema-based, 5-18 XML to Java bean, XML schema entities, 9-23
Java Bean API for XMLType, 9-20, E-6 maxOccurs, 5-38
using, 9-21 MIME
Java DOM API for XMLType, E-2 overriding with DBUri servlet, 12-35
Java Stored Procedure, 9-26 modes
JDBC CASCADE, 5-13
accessing documents, 9-4 FORCE, 5-13
manipulating data, 9-6 MULTISET operator
using SQL to determine object properties, 17-13 using with SYS_XMLGEN selects, 10-46
JNDI, 9-3, E-7
bind(), 9-17
context inputs, 17-8 N
context outputs, 17-10 NamedNodeMap object, 8-21
determining properties, 17-11 namespace
oracle.xdb.spi, 17-3 defining, 3-28
support, 17-2 handling in query rewrites, 5-62
using Resource API, 17-4 handling in XPath, 5-62
W3C introducing, C-18
L XDBResource, 13-17
XML schema URL, 5-5
Lazy Manifestation (LM), 3-25 xmlns, D-4
LDAP XMLSchema-Instance, 3-21
Oracle XML DB, in, 18-5 naming SQL objects
Least Recently Used (LRU), 3-25 SQLName, SQLType attributes, 5-25
Link, 16-2 navigational access, 13-9
LOBs nested
mapping XML fragments to, 5-40 generating nested XML using DBMS_
location path, C-5 XMLGEN, 10-31
LockResource, 16-2 object tables, 3-32
sections in Oracle Text, 7-54
M XML, generating with XMLElement, 10-7
XMLAgg functions and XSQL, 10-51
maintainDOM, 5-65
newDOMDocument, 8-20
maintainOrder attribute, 5-38
Index-6
NodeList object, 8-21 Oracle XML DB, and, 7-37
NULL querying, 7-6
mapping to in XPath, 5-61 querying within attribute sections, 7-30
searching data with, 7-3
searching XML in CLOBs, 1-24
O section_group, deciding which to use, 7-23
object references and DBUri, 12-17 users and roles, 7-5
operators XMLType, 7-4
CONTAINS, 4-38, 7-6 XMLType indexing, 7-34
CONTAINS compared, 4-41 Oracle XML DB, 3-5
DEPTH, 15-8 access models, 2-7
EQUALS_PATH, 15-8 advanced queueing, 1-24
HASPATH, 7-12 application language, 2-8
INPATH, 7-12 architecture, 1-8
MULTISET and SYS_XMLGEN, 10-46 benefits, 1-3
PATH, 15-8 configuring with Enterprise Manager, 21-7
UNDER_PATH, 15-6 designing, 2-3
WITHIN, 7-7, 7-11 features, 1-4
XMLIsValid, 6-9 foldering, 13-2
Oracle Enterprise Manager installation, A-2
configuring Oracle XML DB, 21-7 installing, 2-2
console, 21-7 installing manually, A-3
creating a view based on XML schema, 21-39 introducing, 1-2
creating function-based index, 21-42 Java applications, 20-2
creating resources, 21-12 processing models, 2-9
features, 21-3 Repository, 1-6, 3-34, 13-4
granting privileges, XML Tab, 21-23 storage models, 2-10
managing security, 21-22 storing XMLType, 4-4
managing XML schema, 21-27 upgrading, A-4
Oracle Net Services, 1-12 using XSL/XSLT with, 3-16
Oracle Text versioning, 14-2
advanced techniques, 7-45, 7-49 when to use, 2-2
ALTER INDEX, 7-10 Oracle XML DB Resource API for Java/JNDI
attribute sections, constraints, 7-52 calling sequence, 17-5
building query applications, 7-21 examples, 17-11
comparing CONTAINS and existsNode, 7-38 using, 17-4
conference Proceedings example, 7-56 oracle.xdb, E-2
CONTAINS and XMLType, 4-38 oracle.xdb.bean, 9-21, E-6
CONTAINS operator, 7-6 oracle.xdb.dom, E-2
creating index on XMLType columns, 4-11 oracle.xdb.spi, 17-9, E-7
creating on XMLType columns, 4-39 JNDI and WebDAV, 17-3
CTXSYS, 7-5 XDBResource.getContent(), E-10
CTXXPATH, 7-45 XDBResource.getContentType, E-10
DBMS_XDBT, F-25 XDBResource.getCreateDate, E-10
installing, 7-4 XDBResource.getDisplayName, E-10
Index-7
XDBResource.getLanguage(), E-10 PL/SQL XSLT Processor for XMLType, F-14
XDBResource.getLastModDate, E-10 point-to-point
XDBResource.getOwnerId, E-10 support in AQ, 23-2
XDBResource.setACL, E-10 Positional Descriptor (PD), 5-22
XDBResource.setAuthor, E-10 predicates, 5-59
XDBResource.setComment, E-10 collection, mapping of, 5-60
XDBResource.setContent, E-10 principals, 18-6
XDBResource.setContentType, E-11 privileges
XDBResource.setCreateDate, E-11 aggregate, 18-8
XDBResource.setDisplayName, E-11 atomic, 18-7
XDBResource.setInheritedACL, E-11 granting from Oracle Enterprise Manager, 21-23
XDBResource.setLanguage, E-11 processXSL, 8-31
XDBResource.setLastModDate, E-11 protocol server
XDBResource.setOwnerId, E-11 architecture, 19-3
oracle.xdb.XDBResource configuration parameters, 19-4
JNDI, 17-7 FTP, 19-7
oracle.xdb.XMLType, 9-18 FTP configuration parameters, 19-5
JNDI, 17-7 HTTP, 19-8
ora.contains HTTP/WebDAV configuration
creating a policy for, 7-42 parameters, 19-5
XPath full-text searches, 7-40 Oracle XML DB, 19-2
ordered collections in tables (OCTs), 5-72 using, 3-44
default storage of VARRAY, 5-38 WebDAV, 19-10
rewriting collection index, 5-61 protocols
access calling sequence, 13-11
access to Repository resources, 13-10
P retrieving resource data, 13-11
PATH, 15-8 storing resource data, 13-11
PATH_SECTION_GROUP publish/subscribe
using, 7-10 support in AQ, 23-2
PATH_VIEW, 3-38 purchase order
structure, 15-3 XML, 3-5
Path-based access purchaseorder.xsl, D-7
explained, 13-9
pathname
resolution, 13-7 Q
performance query access
improved using Java writeToStream, 13-12 using RESOURCE_VIEW and PATH_
improvement for structured storage, 3-25 VIEW, 15-2
piecewise update, 1-5 query results
PL/SQL DOM presenting, 7-21, 7-34
examples, 8-22 query rewrite, 5-52
methods, 8-12 query-based access
PL/SQL DOM API for XMLType, F-6 using SQL, 13-12
PL/SQL Parser for XMLType, F-13 querying
Index-8
resources, 3-38 (ACLs), 18-11
XML data, 4-17 storage options, 3-40
XMLType, 4-18 updating, 15-11
XMLType,transient data, 4-26 ResourceType
extending, 13-18
R
rebuilding hierarchical indexes, 16-11 S
REF attribute, 5-39, 5-48 scalar nodes, mapping, 5-59
registerHandler, 12-26 scalar value
Reinstalling converting to XML document using SYS_
Oracle XML DB XMLGEN, 10-45
reinstalling, A-4 schemaLocation, 5-9
Repository, 3-34, 13-4 schemaValidate, 3-24, 6-9
based on WebDAV, 3-35 method, 5-15
hierarchy explained, 3-35 searching CLOBs, 1-24
query-based access, 3-36 security
where is the data stored, 13-6 access control entries (ACEs), 18-6
resource id aggregate privileges, 18-8
new version, 14-5 DBUri, 12-37
RESOURCE_VIEW management using DBMS_XDB, 16-5
explained, 15-2 management with Enterprise Manager, 21-22
PATH_VIEW differences, 15-4 user and group access, 18-6
querying resource documents, 3-38 servlets
structure, 15-3 accessing Repository data, 13-13
resources and session pooling, 20-9
access using UNDER_PATH, 15-9 APIs, 20-10
accessing Repository, 13-8 AQ XML, 23-11
accessing with protocols, 19-6 configuring, 20-12
changing privileges, 18-12 configuring Oracle XML DB, 20-4
configuration management, 16-8 DBUri, URL into a query, 12-34
controlling access to, 18-7 example, 20-10
creating from Enterprise Manager, 21-12 explained, 1-30
defined, 13-4 installing, 20-11
deleting, 13-7 session pooling, 20-9
deleting non-empty containers, 15-11 session pooling and Oracle XML DB, 19-2
deleting using DELETE, 15-10 testing the, 20-12
extending metadata properties, 13-17 writing Oracle XML DB HTTP, 20-4
inserting data using RESOURCE_VIEW, 15-9 XML manipulation, with, 20-3
management using DBMS_XDB, 16-2 session pooling, 20-9
managing, 18-11 protocol server, 19-2
multiple simultaneous operations, 15-12 setSchemaValidated, 6-10
required privileges for operations, 18-8 Simple Object Access Protocol (SOAP) and
retrieving access control lists (ACLs), 18-12 IDAP, 23-5
setting property in access control lists simpleContent
Index-9
mapping to object types, 5-45 returning Uri-refs, 12-33
simpleType text function, 12-31
elements, B-3 SYS_REFCURSOR
mapping to SQL, 5-34 generating a document for each row, 10-13
mapping to VARCHAR2, 5-37 SYS_XDBPD$, 5-22, 5-65
SOAP in query rewrites, 5-58
access through Advanced Queueing, 1-12 suppressing, 5-22
and IDAP, 23-5 SYS_XMLAgg, 10-50
space SYS_XMLGEN, 10-41
requirements in structured, unstructured converting a UDT to XML, 10-46
storage, 3-26 converting XMLType instances, 10-47
SQL functions generating XML in SQL queries, 4-12
existsNode, 4-20 inserting, 4-16
extractValue, 4-23 object views, 10-48
SQL*Loader, 22-2 static member function create, 10-44
SQLInLine attribute, 5-38 using with object views, 10-48
SQLName, 5-25 XMLFormat attributes, 10-44
SQLType, 5-25, 5-29 XMLGenFormatType object, 10-43
attribute, 5-40
SQLX
generating XML, 10-5
T
generating XML, for, 10-2 tableProps attribute, 5-71
operators, explained, 1-5 tablespace
Oracle extensions, 10-2 do not drop, A-2
storage transform, 6-2
of complex types, 3-32 triggers
options for resources, 3-40 BEFORE INSERT trigger, 3-24
structured, 3-33 BEFORE INSERT, using with XMLType, 3-23
XMLDATA, 4-13 creating XMLType, 4-37
structured or unstructured, 3-24 using with XMLType, 4-37
structured, query rewrite, 5-52
VARRAYs and OCT, 5-72 U
XML-schema-based, 5-21
XMLType CREATE TABLE, 5-51 UDT
storeVarrayAsTable attribute, 5-72 generating an element from, 10-9
substitution generating an element using XMLForest, 10-10
creating columns by inserting UNDER_PATH, 3-38, 15-6
HttpUriType, 12-24 summary, 15-5
/sys, restrictions, 13-3 UPDATE_VAL
SYS_DBURIGEN, 12-29 binding XMLType objects to SQL, 17-2
examples, 12-31 updateXML, 5-70
inserting database references, 12-31 creating views, 4-35
passing columns or attributes, 12-30 mapping NULL values, 4-35
retrieving object URLs, 12-33 replacing contents of node tree, 3-13
returning partial results, 12-32 updating text node value, 3-12
Index-10
updating with XML schema, 5-7
resources, 3-38, 15-11 VARRAYS
same node more than once, 4-36 inline, 3-32
upgrading storage using OCT, 5-72
existing installation, A-4 VCR, 14-4, 14-6
URI access control and security, 14-8
base, C-28 version-controlled resource (VCR), 14-4, 14-6
UriFactory, 12-25 versioning, 1-11, 14-2
configuring to handle DBUri-ref, 12-38 FAQs, 14-12
factory method, 12-25 views
generating UriType instances, 12-25 RESOURCE and PATH, 15-2
registering ecom protocol, 12-27
registering new UriType subtypes, 12-26
registerURLHandler, 12-26
W
Uri-ref, see also Uri-reference, 12-4 W3C DOM Recommendation, 8-9
Uri-reference WebDAV
database and session, 12-17 oracle.xdb.spi, 17-3
datatypes, 12-6 protocol server, features, 19-10
DBUri, 12-10 standard introduced, 3-35
DBUri and object references, 12-17 WebFolder
DBUri syntax guidelines, 12-13 creating in Windows 2000, 19-11
DBUri-ref, 12-9 WITHIN
DBUri-ref uses, 12-17 in Oracle Text, 7-7
DBUriType examples, 12-25 limitations, 7-11
explained, 12-4 syntax, 7-11
HTTP access for DBUri-ref, 12-34 writeToStream, 13-12
UriFactory package, 12-25
UriType examples, 12-23 X
UriTypes, 12-22
UriTypes, 12-22 XDB$RESOURCE table, 13-18
benefits, 12-6 XDBBinary, 13-5, 13-11
creating Oracle Text index on column, 7-37 explained, 1-29
examples, 12-23 xdbconfig.xml, 19-2
subtypes, advantages, 12-28 XDBResource
URL JNDI Context output, 17-10
identifying XML schema, for, 5-5 namespace, 13-17
xsd, 13-17
XDBSchema.xsd, 5-20
V XDBUri, 12-5
validating XDBUriType
examples, 6-10 accessing non-schema content, 3-44
isSchemaValid, 6-10 accessing Repository content, 3-44
isSchemaValidated, 6-9 defined, 12-2
schemaValidate, 6-9 stores references to Repository, 12-6
SetSchemaValidated, 6-10 XDK for PL/SQL, backward compatibility, 8-2
Index-11
XML XML Schema, introducing W3C, B-2
binary datatypes, 5-35 XML SQL Utility
fragments, mapping to LOBs, 5-40 generating XML, 10-54
primitive datatypes, 5-37 XML SQL Utility (XSU)
primitive numeric types, 5-35 generating XML, 10-3
XML DB Resource API for Java/JNDI, 17-2 XML storage, 3-24
XML DB, Oracle, 3-5 XML_SECTION_GROUP
XML schema using, 7-8
and Oracle XML DB, 1-7, 5-5 XMLAgg, 10-17
benefits, 5-6 XMLAttributes, 10-7
compared to DTD, B-31 XMLColAttVal, 10-19
complexType declarations, 5-42 XMLConcat, 10-15
creating default tables during registration, 5-71 concatenating XML elements in
cyclical references, 5-75 argument, 10-16
cyclical references between, 5-72 returning XML elements by
DTD limitations, B-33 concatenating, 10-16
elementFormDefault, 5-62 XMLDATA
Enterprise Manager, managing them column, 5-59
from, 21-27 optimizing updates, 5-70
features, B-34 parameter, F-3
generating Java beans, 5-17 pseudo-attribute of XMLType, 5-51
global, 5-11 structured storage, 4-13
inheritance in, complexType restrictions, 5-44 XMLElement, 10-5
key feature explained, 1-5 attribute, 10-7
local, 5-10 generating elements from DTD, 10-9
local and global, 5-10 using namespaces to create XML
managing and storing, 5-20 document, 10-8
mapping to SQL object types, 8-10 XMLForest, 10-9
navigating in Enterprise Manager, 21-28 generating elements, 10-10
registering, 5-8 generating elements from DTD, 10-10
registering using DBMS_XMLSCHEMA, 5-8 XMLFormat
root, 5-20 XMLAgg, 10-17
SQL and Java datatypes, 9-23 XMLFormat object type
SQL mapping, 5-29 SYS_XMLGEN
storage and access, 5-12 XMLFormatType object, 10-43
storage of XMLType, 3-28 XMLGenFormatType object, 10-43
unsupported constructs in query rewrites, 5-55 XMLIsValid
updateXML(), 5-70 validating
URLs, 5-16 XMLIsValid, 6-9
validating an XML document, 3-22 XMLSequence, 10-11
W3C Recommendation, 3-17, 5-3 extracting description nodes, 3-11
xdb.SQLType, 3-30 generating an XML document for each
XMLType methods, 5-20 row, 10-13
XML schema, creating a view in Enterprise generating one document from another, 10-12
Manager, 21-39 unnesting collections in XML to SQL, 10-14
Index-12
XMLTransform, 4-36, 6-2 tables, storing, 5-24
XMLType, 4-2 tables, views, columns, 5-14
adding columns, 4-8 triggers, 4-37
API, F-2 updating column, example, 4-9
benefits, 4-3 using in SQL SELECT statement, 4-9
CLOB storage, 4-5 views,access with PL/SQL DOM APIs, 8-11
column, 3-3 when to use, 4-4
constraints, specifying, 4-14 Xpath support, 4-38
CONTAINS operator, 4-38 XMLType, loading with SQL*Loader, 22-2
CREATE TABLE, 5-51 XPath
creating columns, 4-8 basics, D-6
creating columns, example, 4-8 explained, 1-28
creating Oracle Text index, 4-11 expressions, mapping, 5-58
deleting a row containing, 4-10 mapping for extract(), 5-68
deleting rows, 4-37 mapping for extract() without document
deleting using extract(), 4-37 order, 5-69
dropping columns, 4-8 mapping for extractValue(), 5-66
extracting data, 4-27 mapping to NULL in, 5-61
functions, 4-7 mapping, simple, 5-58
guidelines for using, 4-11 rewrites for existNode(), 5-63
how to use, 4-7 rewriting expressions, 5-54
indexing, 7-34 support, 4-38
indexing columns, 4-38 text(), 5-59
inserting into, 4-9 unsupported constructs in query rewrites, 5-55
inserting with createXML() using string, 4-16 use for searching data, 1-5
inserting with SYS_XMLGEN(), 4-16 using with Oracle XML DB, 3-5
inserting XML data, 4-15 W3C introducing, C-2
instances, PL/SQL APIs, 8-2 XPath expressions
Java supported, 5-55
writeToStream, 13-12 xsi.noNamespaceSchemaLocation, 5-5
loading data, 22-2 XSL
manipulating data in columns, 4-14 and CSS, D-7
Oracle Text support, 7-4 basics, D-2
querying, 4-17, 4-18 defined, 1-28
querying transient data, 4-26 XSL stylesheet, example, D-7
querying with extract() and existsNode(), 4-26 XSLT, 8-12
querying XMLType columns, 4-26 1.1 specification, D-5
queue payloads, 23-6 explained, D-5
storage architecture, 1-12 xsql
storage characteristics, 4-12 include-xml
storing data in Oracle XML DB, 4-4 aggregating results into one XML, 10-51
summarized, 1-4 generating XML from database, 10-52
table, 3-3 XSQL Pages Publishing Framework
table storage, 1-10 generating XML, 10-3, 10-51
table, querying with JDBC, 9-4
Index-13
Index-14