Beruflich Dokumente
Kultur Dokumente
Release 2 (9.2)
March 2002
Part No. A96620-01
Oracle9i XML Database Developers Guide - Oracle XML DB, Release 2 (9.2)
Part No. A96620-01
Copyright 2002 Oracle Corporation. All rights reserved.
Primary Author:
Shelley Higgins
Contents
Send Us Your Comments .............................................................................................................. xxvii
Preface........................................................................................................................................................ xxix
Audience .............................................................................................................................................. xxx
Organization........................................................................................................................................ xxx
Related Documentation ................................................................................................................... xxxv
Conventions...................................................................................................................................... xxxvi
Documentation Accessibility ......................................................................................................... xxxix
Part I
1
xli
xliii
xlv
xlv
xlv
xlvi
1-2
1-2
1-3
1-4
iii
iv
1-7
1-8
1-10
1-11
1-12
1-15
1-16
1-17
1-18
1-21
1-22
1-22
1-24
1-24
1-25
1-26
1-26
1-27
1-27
1-30
2-2
2-2
2-2
2-3
2-3
2-3
2-3
2-4
2-4
2-4
2-5
2-7
2-8
2-9
2-10
2-11
2-12
3-3
3-4
3-5
3-6
3-8
3-10
3-11
3-12
3-14
3-16
3-17
3-17
3-19
3-21
3-22
3-24
3-27
3-27
3-28
3-32
3-33
3-34
3-36
3-37
3-37
3-37
3-38
3-38
3-39
Part II
4
Using XMLType
What Is XMLType?..............................................................................................................................
Benefits of the XMLType Data Type and API ..........................................................................
When to Use XMLType ......................................................................................................................
Storing XMLType Data in Oracle XML DB....................................................................................
Pros and Cons of XML Storage Options in Oracle XML DB ..................................................
When to Use CLOB Storage for XMLType ...............................................................................
XMLType Member Functions ...........................................................................................................
How to Use the XMLType API .........................................................................................................
Creating, Adding, and Dropping XMLType Columns ...........................................................
Inserting Values into an XMLType Column.............................................................................
Using XMLType in an SQL Statement.......................................................................................
Updating an XMLType Column.................................................................................................
Deleting a Row Containing an XMLType Column ...............................................................
Guidelines for Using XMLType Tables and Columns...............................................................
Specifying Storage Characteristics on XMLType Columns..................................................
Changing Storage Options on an XMLType Column Using XMLData .............................
Specifying Constraints on XMLType Columns......................................................................
Manipulating XML Data in XMLType Columns/Tables ...........................................................
Inserting XML Data into XMLType Columns/Tables ................................................................
Using INSERT Statements .........................................................................................................
Selecting and Querying XML Data ...............................................................................................
Selecting XML Data ....................................................................................................................
Querying XML Data ...................................................................................................................
Using XPath Expressions for Searching XML Documents ...................................................
vi
3-40
3-40
3-43
3-44
3-44
3-44
3-49
4-2
4-3
4-4
4-4
4-5
4-6
4-7
4-7
4-8
4-9
4-9
4-9
4-10
4-11
4-12
4-13
4-14
4-14
4-15
4-15
4-17
4-17
4-18
4-18
4-19
4-20
4-21
4-23
4-26
4-31
4-31
4-35
4-35
4-36
4-36
4-37
4-37
4-38
4-38
4-39
5-3
5-3
5-5
5-6
5-7
5-8
5-8
5-10
5-12
5-13
5-14
5-14
5-14
5-15
5-16
5-17
vii
viii
5-17
5-18
5-20
5-20
5-20
5-21
5-21
5-22
5-22
5-23
5-24
5-25
5-29
5-32
5-32
5-32
5-34
5-37
5-38
5-38
5-40
5-42
5-42
5-45
5-46
5-47
5-50
5-51
5-52
5-52
5-52
5-53
5-54
5-56
5-58
5-63
5-66
5-68
5-70
5-71
5-72
5-72
5-72
6-2
6-2
6-3
6-8
6-10
7-3
7-3
7-4
7-5
7-6
7-7
7-8
7-8
7-10
7-10
7-11
7-11
7-12
7-12
7-19
7-21
7-21
ix
7-21
7-23
7-23
7-23
7-24
7-24
7-25
7-25
7-26
7-28
7-28
7-30
7-30
7-34
7-34
7-35
7-36
7-36
7-37
7-37
7-38
7-40
7-40
7-40
7-41
7-42
7-45
7-45
7-46
7-46
7-47
7-47
7-49
7-49
7-50
7-50
7-50
7-52
7-53
7-54
7-54
7-55
7-56
7-56
7-56
7-60
7-64
7-64
7-64
7-64
7-65
7-65
7-65
7-66
7-66
7-66
7-67
7-67
7-68
7-68
7-68
7-69
7-69
7-69
7-70
7-70
7-71
7-72
7-72
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
Part III
8
xii
8-2
8-2
8-3
8-4
8-5
8-5
8-7
8-8
8-9
8-10
8-11
8-12
8-18
8-18
8-20
8-21
8-21
8-22
8-24
8-24
8-26
8-27
8-28
8-28
8-28
8-29
8-30
8-31
Part IV
10
9-2
9-2
9-3
9-6
9-16
9-18
9-19
9-20
9-21
10-2
10-2
10-2
10-2
10-2
10-3
10-3
10-5
10-5
10-9
10-11
10-15
10-17
10-19
10-19
10-20
10-20
10-21
10-41
xiii
SYS_XMLGEN() Function.............................................................................................................
Using XMLFormat Object Type..............................................................................................
SYS_XMLAGG() Function ............................................................................................................
Generating XML Using XSQL Pages Publishing Framework ...............................................
Generating XML Using XML SQL Utility (XSU)......................................................................
11
10-41
10-43
10-50
10-51
10-54
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
12
xiv
Part V
13
12-14
12-14
12-15
12-16
12-16
12-17
12-17
12-17
12-18
12-20
12-21
12-22
12-22
12-23
12-25
12-25
12-26
12-28
12-29
12-30
12-31
12-34
12-34
12-36
12-37
12-38
13-2
13-4
13-4
13-6
13-6
xv
14
15
xvi
15-2
15-3
15-3
15-4
15-5
15-6
15-6
EQUALS_PATH.................................................................................................................................
PATH ...................................................................................................................................................
DEPTH ................................................................................................................................................
Using the Resource View and Path View API.............................................................................
Accessing Paths and Repository Resources: Examples.........................................................
Inserting Data into a Repository Resource: Examples ........................................................
Deleting Repository Resources: Examples............................................................................
Updating Repository Resources: Examples..........................................................................
Working with Multiple Oracle XML DB Resources Simultaneously ..................................
16
17
15-8
15-8
15-8
15-9
15-9
15-10
15-10
15-11
15-12
16-2
16-2
16-2
16-3
16-5
16-6
16-8
16-9
16-11
16-11
17-2
17-2
17-2
17-3
17-4
17-5
17-5
17-6
17-7
17-8
17-9
17-11
xvii
18
19
xviii
19-2
19-2
19-3
19-4
19-6
19-7
19-7
19-7
20
Part VI
21
19-8
19-8
19-10
19-10
19-11
20-2
20-2
20-3
20-3
20-3
20-3
20-4
20-4
20-8
20-9
20-9
20-10
20-10
20-11
20-12
20-12
21-2
21-2
21-3
21-4
21-4
21-4
xix
22
Part VII
23
xx
23-2
23-2
23-5
23-5
23-6
23-6
23-9
23-11
23-12
23-13
23-13
23-13
23-14
23-14
23-15
23-15
23-16
23-16
23-16
xxi
xxii
C-2
C-3
C-3
C-4
C-5
C-5
C-5
C-7
XSLT Primer
Introducing XSL ..................................................................................................................................
The W3C XSL Transformation Recommendation Version 1.0...............................................
Namespaces in XML ....................................................................................................................
XSL Stylesheet Architecture........................................................................................................
XSL Transformation (XSLT) ..............................................................................................................
XSLT 1.1 Specification..................................................................................................................
XML Path Language (Xpath).............................................................................................................
CSS Versus XSL...................................................................................................................................
XSL Stylesheet Example, PurchaseOrder.xsl.................................................................................
D-2
D-2
D-4
D-5
D-5
D-5
D-6
D-7
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
G-2
G-2
G-3
G-8
G-9
G-10
G-11
G-12
G-12
G-12
G-12
G-12
G-15
G-15
G-15
G-18
G-18
Glossary
Index
xxv
xxvi
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.
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 comments to us in the following ways:
If you would like a reply, please give your name, address, telephone number, and (optionally) electronic 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
xxxi
xxxii
xxxiii
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 Developers Kits Guide - XDK
Oracle9i XML Case Studies and Applications (contains XDK examples, no
Oracle XML DB examples for this release)
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
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 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.
Convention
Meaning
Bold
Italics
xxxvi
Example
Convention
Meaning
Example
UPPERCASE
monospace
(fixed-width)
font
lowercase
monospace
(fixed-width)
font
lowercase
Lowercase italic monospace font
italic
represents placeholders or variables.
monospace
(fixed-width)
font
The following table describes typographic conventions used in code examples and
provides examples of their use.
xxxvii
Convention
Meaning
Example
[]
{}
...
.
.
.
Other notation
Italics
UPPERCASE
lowercase
xxxviii
acctbal NUMBER(11,2);
acct
CONSTANT NUMBER(4) := 3;
CONNECT SYSTEM/system_password
DB_NAME = database_name
sqlplus hr/hr
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
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
xlii
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:
xlvi
Part I
Introducing Oracle XML DB
Part I of this manual introduces Oracle XML DB. It contains the following chapters:
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:
The ability to store and manage both structured and unstructured data under
the same standard W3C XML data model (XML Schema).
Complete transparency and interchangeability between the XML and SQL data
views.
Valuable Repository functionality: foldering, access control, FTP, and WebDAV
protocol support with versioning. This enables applications to retain the file
abstraction when manipulating XML data brought into Oracle. As a result, you
can store XML in the database (rendering it queryable) and at the same time
access it through popular desktop tools.
Better management of unstructured XML data by supporting
Piecewise updates
XML indexing
Multiple views on the data, including relational views for SQL access
Users today face a performance barrier in storing and retrieving complex XML.
Oracle XML DB provides high performance and scalability for XML operations
with the help of a number of specific optimizations that relate to XML-specific
data-caching and memory management, query optimization on XML, special
hierarchical indexes on the XML Repository, and so on.
Enables data and documents from disparate systems to be accessed, for
example, through Oracle Gateway and External Tables, and combined into a
Description
XMLType
The native datatype XMLType helps store and manipulate XML. Multiple storage
options (Character Large Object (CLOB), structured XML) are available with
XMLType, and administrators can choose a storage that meets their requirements.
CLOB storage is an un-decomposed storage that is like an image of the original
XML.
The native structured XML storage is a shredded decomposition of XML into
underlying object-relational structures (automatically created and managed by
Oracle) for better SQL queriability.
With XMLType, you can perform SQL operations such as:
Queries, OLAP function invocations, and so on, on XML data, as well as XML
operations
XPath searches, XSL transformations, and so on, on SQL data
You can build regular SQL indexes or Oracle Text indexes on XMLType for high
performance for a very broad spectrum of applications. See Chapter 4, "Using
XMLType".
DOM fidelity
Document fidelity
For applications that need to store XML while maintaining complete fidelity to the
original, including whitespace characters, the CLOB storage option is available.
Description
XML Schema
Oracle XML DB gives you the ability to constrain XML documents to XML
schemas. You can create tables and types automatically given a W3C standard
XML Schema. You can also enforce that an XML document being stored is
schema-valid. This means you have a standard data model for all your data
(structured and unstructured) and can use the database to enforce this data model.
See Chapter 5, "Structured Mapping of XMLType".
XML Schema
validation
While storing XML documents in Oracle XML DB you can optionally ensure that
their structure complies (is valid against) with specific XML Schema. See
Chapter 6, "Transforming and Validating XMLType Data".
XML piecewise
update
You can use XPath to specify individual elements and attributes of your document
during updates, without rewriting the entire document. This is more efficient,
especially for large XML documents. See Chapter 5, "Structured Mapping of
XMLType".
XPath search
You can use XPath syntax (embedded in an SQL statement or as part of an HTTP
request) to query XML content in the database. See Chapter 4, "Using XMLType"
and Chapter 7, "Searching XML Data with Oracle Text".
XML indexes
Use XPath to specify parts of your document to create indexes for XPath searches.
Enables fast access to XML documents. See Chapter 4, "Using XMLType".
SQLX operators
New SQL member functions tracking the emerging ANSI SQLX standard, such as,
XMLElement (to create XML elements on the fly) and others, to make XML
queries and on-the-fly XML generation easy. These render SQL and XML
metaphors interoperable.See Chapter 10, "Generating XML Data from the
Database".
XSL transformations
for XMLType
Oracle XML DB provides a virtual DOM; it only loads rows of data as they are
requested, throwing away previously referenced sections of the document if
memory usage grows too large. You can use this to get high scalability when many
concurrent users are dealing with large XML documents. The virtual DOM is
available through Java interfaces running in a Java execution environment at the
client or with the server. See Chapter 8, "PL/SQL API for XMLType".
Description
XML views
You can create XML views to create permanent aggregations of various XML
document fragments or relational tables. You can also create views over
heterogeneous data sources using Oracle Gateways. See Chapter 11, "XMLType
Views".
A Java Bean Interface for fast access to structured XML data has extensions that
save only those parts that have been modified in memory. With this you get static
access to XML as well as dynamic (DOM) access. See Chapter 9, "Java and Java
Bean APIs for XMLType".
Use DOM and other APIs for accessing and manipulating XML data. You can get
static and dynamic access to XML. See Chapter 8, "PL/SQL API for XMLType".
Schema caching
XML generation
Oracle XML DB
Repository
A built-in XML Repository. This Repository can be used for foldering whereby you
can view XML content stored in Oracle XML DB as a hierarchy of directory-like
folders. See Chapter 13, "Oracle XML DB Foldering".
The repository supports access control lists (ACLs) for any XMLType object, and
lets you define your own privileges in addition to providing certain
system-defined ones. See Chapter 18, "Oracle XML DB Resource Security".
You can use the Repository to view XML content as navigable directories
through a number of popular clients and desktop tools. Items managed by the
repository are called resources.
Hierarchical indexing is enabled on the Repository. Oracle XML DB provides
a special hierarchical index to speed folder search. Additionally, you can
automatically map hierarchical data in relational tables into folders (where the
hierarchy is defined by existing relational information, such as with CONNECT
BY).
Description
SQL Repository
search
You can search the XML Repository using SQL. Operators like UNDER_PATH
and DEPTH allow applications to search folders, XML file metadata (such as
owner and creation date), and XML file content. See Chapter 15, "RESOURCE_
VIEW and PATH_VIEW".
You can access any foldered XMLType row using WebDAV and FTP. Users
manipulating XML data in the Oracle9i database can use the HTTP API. See
Chapter 19, "Using FTP, HTTP, and WebDAV Protocols".
Versioning
You can also choose to wrap existing relational and object-relational data into XML
format using XMLType views.
You can store an XMLType object as an XML schema-based object or a non-XML
schema-based object:
You can map from XML instances to structured or LOB storage. The mapping can
be specified in XML schema and the XML schema must be registered in Oracle XML
DB. This is a required step before storing XML schema-based instance documents.
Once registered, the XML schema can be referenced using its URL.
The XMLType tables and views storage, which includes storage of XMLType
tables and views
The Oracle XML DB Repository, also referred to in this manual as "XML
Repository" or "Repository"
Browser
or other
UI
Browser
JDBC
Application
Desktop
Tool
FTP
Tool
Direct
HTTP
Access
Oracle
Net
Services
Access
WebDAV
Access
FTP
Access
AQ and
Oracle9i
Streams
Access
Oracle9i Database
Gateways
to external
sources
Oracle XML DB
XMLType Tables
and Views
XML Services
XML Validation
XML Transformation
XML Schema
Registration
Create Tables
Store in LOB or O-R
Insert, Delete, Update
XMLType tables
Indexing
Retrieve / Generate
XML Using
XMLType APIs
SQL
Java / JavaBean
PL/SQL
Oracle XML DB
Repository
XML Services
Versioning
ACL Security
Foldering
Retrieve XML Using
Resource APIs
SQL
Java / JNDI
PL / SQL
PL/SQL and Java APIs for XMLType. Use these APIs to:
PL/SQL and Java APIs for XMLType. These enable you to manipulate
XMLType data, such as update, delete, and insert XML data.
Indexing. This speeds up data searches where XPath features are not critical. It
is most suited for XML data stored in LOBs.
Transforming XML data to other XML, HTML, and so on, using XMLTypes
XMLTransform() function, XDKs XSLT Processors, or XSQL Servlet Pages
Publishing Framework. See Chapter 6, "Transforming and Validating XMLType
Data" and Chapter 10, "Generating XML Data from the Database".
Validating XML data. Validates XML data against XML schema when the XML
data is stored in the database.
See Also: "XMLType Storage Architecture" on page 1-12.
1-10
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 Resource APIs. Use these APIs to access the foldered XMLType
and other data, that is, data accessed using the Oracle XML DB hierarchically
indexed Repository. The APIs are available in the following languages:
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.
WebDav and FTP, through the WebDav and FTP protocol server.
1-12
SQL, through Oracle Net Services including JDBC. Oracle XML DB also
supports XML data messaging using Advanced Queueing (AQ) and SOAP.
See Also:
JDBC
Direct
HTTP
Access
Oracle
Net
Access
WebDAV Access
and
FTP Access
AQ
Access
Oracle9i
Database
Oracle XML DB
HTTP
Protocol
Handler
SQL
Engine
DAV, FTP
Protocol
Handlers
XML Schemas
Indexes:
B*Tree
Text
Functional
Bitmap
CLOB
Storage
1-14
XMLType
Tables
XMLType
Views
Repository
Hierarchical
Index
Native
Structured
XML
Storage
Local
Tables
DBLinks
Remote
Tables
Accessed
via DBLinks
A lazily materialized virtual DOM from the stored XMLType, whose nodes are
fetched on demand
A cache for XML schemas
You can thus get dynamic access to XML without having to materialize an entire
XML DOM in memory. Static (Java Bean) access is also available. This is
accomplished by calculating offsets to the nodes in the DOM during compilation.
Figure 13 Cached XML Object Management Architecture
Dynamic
Java
Access
Cached XML
Object
Management
Static
Java (Bean)
Access
Compile-time
Calculated
Offsets
XML
Schemas Cache
Virtual
DOM
1-16
ACL
Property 1
Property N
Property N
abc
Oracle9i Database
XMLType
Rows
ACL
Property 1
Property N
Path
Extra
Content
Parent
LOB
FTP
WebDAV
B*Tree
Index
Text
Index
Hierarchical
Index
Tables or
Views
of XML
When Your Data Is Not XML You Can Use XMLType Views
Applications
Application Server
Applications
Oracle XML DB
Applications
Oracle iAS
Application Server
File
System
Multimedia and
Document Content
1-18
RDBMS
XML
Repository
RDBMS
Oracle
XML DB
Structured Data
and Metadata
Multimedia, Document
Content and XML,
Metadata
Structured Data
Multimedia and
Document Content,
Structured Data,
XML, Metadata
Organizations today typically manage their structured data and unstructured data
differently:
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:
This makes the database much more accessible to XML-shaped data content.
Indexing and Search: Applications use queries such as find all the product
definitions created between March and April 2002", a query that is typically
supported by a B*Tree index on a date column. Previously, content management
vendors have had to build proprietary query APIs to handle this problem.
Oracle XML DB can enable efficient structured searches on XML data. See
Chapter 4, "Using XMLType", Chapter 10, "Generating XML Data from the
Database", and Chapter 7, "Searching XML Data with Oracle Text".
Updates and Transaction Processing: Commercial relational databases use fast
updates of subparts of records, with minimal contention between users trying
to update. As traditionally document-centric data participate in collaborative
environments through XML, this requirement becomes more important. File- or
CLOB- storage cannot provide the granular concurrency control that Oracle
XML DB does. See Chapter 4, "Using XMLType".
Managing Relationships: Data with any structure typically has foreign key
constraints. Currently, XML data-stores lack this feature, so you must
1-20
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:
Oracle9i XML Developers Kits Guide - XDK, in the chapter, XSQL Pages
Publishing Framework. It includes XMLType examples.
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:
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.
See Also: Chapter 11, "XMLType Views".
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 16 summarizes the Oracle XML DB advantages.
1-22
Oracle
XML DB
Unifies Data
and Content
Enhanced native
database support for
XML
Stores and manages
structured, unstructured,
and semi-structured data
Higher performance
of XML operations
Higher scalability
of XML operations
Helps
Integrate
Applications
Also Handles
non-XML Data
with XMLType
Views
Facilitates migrating of
legacy and non-XML to
XML data
indexing, searching
updating, transaction processing
manages constraints
multiple data views
speeds up XML storage, retrieval
supports standards for storing,
modifying, retrieving data
Exploits XML features:
CONTAINS() function that can be used with existsNode() for XPath based
searches. This is for use as the ora:contains function in an XPath query, as
part of existsNode().
The ability to create indexes on UriType and XDBUriType columns.
A new index type, CTXXPATH, that allows higher performance XPath searching
in Oracle XML DB under existsNode().
See Also:
1-24
See Also:
Configuration
Create resources
1-26
W3C XML Schema 1.0 Recommendation. You can register XML schemas,
validate stored XML content against XML schemas, or constrain XML stored in
the server to XML schemas.
W3C XPath 1.0 Recommendation. You can search or traverse XML stored inside
the database using XPath, either from HTTP requests or from SQL.
ISO-ANSI Working Draft for XML-Related Specifications (SQL/XML) [ISO/IEC
9075 Part 14 and ANSI]. You can use the emerging ANSI SQLX functions to
query XML from SQL.
Java Database Connectivity (JDBC) API. JDBC access to XML is available for
Java programmers.
W3C XSL 1.0 Recommendation. You can transform XML documents at the
server using XSLT.
W3C DOM Recommendation Levels 1.0 and 2.0 Core. You can retrieve XML
stored in the server as an XML DOM, for dynamic access.
Java Beans. You can access XML stored in the server through a Java Bean
interface.
Protocol support. You can store or retrieve XML data from Oracle XML DB
using standard protocols such as HTTP, FTP, IETF WebDAV, as well as Oracle
Net. See Chapter 19, "Using FTP, HTTP, and WebDAV Protocols".
Java Naming and Directory Interface (JNDI). You can use JNDI for hierarchical
access to XML resources.
Java Servlet version 2.2, (except that the Servlet WAR file, web.xml is not
supported in its entirety, and only one ServletContext and one web-app are
currently supported, and stateful servlets are not supported). See Chapter 20,
"Writing Oracle XML DB Applications in Java".
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 Developers Guide - Advanced
Queuing.
In the left-hand navigation bar of the OTN site, select Support > Discussions.
2.
3.
4.
Description
XML Schema is a schema definition language (also in XML) that can be used to
describe the structure and various other semantics of conforming instance
documents. See Appendix B, "XML Schema Primer".
Oracle XML DB uses annotated XML schemas, that is, XML schemas that include
additional attributes defined by Oracle XML DB. The Oracle XML DB attributes
serve to specify metadata that in turn determines both the XML structuring and its
mapping to a database schema. You can register XML schemas and then use the
appropriate XML schema URLs while creating XMLType tables and columns and
also to define XMLType views. See:
XPath
A language for addressing parts of an XML document, for use by XSLT and
XPointer. XPath uses the directory traversal syntax to traverse an XML document.
It includes syntax for specifying predicate expressions on the nodes traversed. The
result of a XPath traversal is an XML fragment. See Appendix C, "XPath and
Namespace Primer".
XSL
DOM
Oracle XML DB
Repository
1-28
Description
Resource
Repository
Oracle XML DB Repository is the set of all Oracle XML DB resources. The
Repository is a hierarchically organized set of XMLType objects, each with a path
name to identify them. Think of the Oracle XML DB Repository as a file system of
objects rather than files. There is one root to this Repository (/), which contains a
set of resources, each with a path name. Resources that contain (contain with
respect to the hierarchical naming system) other resources are called folders (see
Folder in the following).
Oracle XML DB objects can have many path names (that is, a resource can be in
more than one folder). In some sense, the database itself is the Repository, since
any database object can be mapped to a path name. However, Oracle XML DB uses
Repository to refer to the set of database objects, in any schema, that are mapped
to path names. See Chapter 13, "Oracle XML DB Foldering".
Folder
A non-leaf node object in Oracle XML DB Repository, or one with the potential to
be such a node. Oracle XML DB has special storage semantics for collections for
optimization reasons. It maintains a special kind of hierarchical index used to
navigate the hierarchy of collections, and defines a property, called name that is
used to form path names in the hierarchy. There are many names for collections,
such as folders and directories. Any XML element type can be a folder by specifying
the isFolder attribute in the Oracle XML DB schema. See Chapter 13, "Oracle
XML DB Foldering".
Pathname
A hierarchical name is composed of a root element (the first /), element separators
(/), and various sub-elements (or path elements). A path element can be composed
of any character in the database character set except the following (\ /). In
Oracle XML DB, a forward slash is the default name separator in a path name.
Resource Name
A resource here means any database object stored in Oracle XML DB Repository.
Resource name is the name of a resource within its parent folder. Resource names
are the path elements, that is, filenames within folders. Resource names must be
unique (potentially subject to case-insensitivity) within a folder.
Content
The body of a resource is what you get when you treat the resource like a file and
ask for its contents.
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.
Description
ACL Terminology
Restricts access to an object. Oracle XML DB uses ACLs to restrict access to any
Oracle XML DB resource, that is, any XMLType object that is mapped into the
Oracle XML DB file system hierarchy.
See also Chapter 19, "Using FTP, HTTP, and WebDAV Protocols" and Chapter 3,
"Using Oracle XML DB"
FTP
HTTP
WebDAV
Servlets
Sun developed a widely accepted standard for invoking Java code as the result of
protocol requests and passing parameters to that request. Servlets are most
commonly implemented with HTTP. The majority of Java services are
implemented as servlets, through mechanisms (implemented in Java) such as JSPs
(Java Server Pages) or SOAP (Simple Object Access Protocol). Servlets thus form
the architectural basis for a large percentage of web application development.
Oracle XML DB provides a method for invoking Java stored procedures over
protocols other than Oracle Services (Net Services). Oracle XML DB implements
most servlet standards. Chapter 20, "Writing Oracle XML DB Applications in Java".
1-30
1-32
2
Getting Started with Oracle XML DB
This chapter provides some preliminary design criteria for consideration when
planning your Oracle XML DB solution. It contains the following sections:
Internet applications
Content-management applications
Messaging
Web Services
a. Data
Will your data be highly structured (mostly XML), semi- structured (pseudostructured), 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.
Note: Your choice of which models to choose in the preceding
Data
Structure?
Access?
Language?
Java
JDBC
PL/SQL
JNDI
Processing and
Data
Manipulation?
DOM
SQL inserts /
updates
XSLT
Queriability
Updatability
Repository
Path Access
SQL
Query Access
Storage Options ?
XMLType Tables or XMLType Views
You get the same Oracle XML DB functionality regardless
of which storage option you chose.
The storage option affects the application's performance
and data fidelity
Structured data. Is your data highly structured? In other words, is your data
mostly XML data?
Semi/pseudo-structured data. Is your data semi/pseudo-structured? In other
words does your data include some XML data?
Unstructured data. Is your data unstructured? In other words, is your data
mostly non-XML data?
For structured data, you can use either Character Large Object (CLOB) or
structured storage.
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.
Semi-structured
Psudo-structured
Data
Structured
Data
XML
Schema
Based?
Non-Schema
Based?
XML
Schema
Based?
Non-Schema
Based?
Use either:
CLOB or
Structured
Storage
Store as:
CLOB in
XMLType
Table
File in
Repository
Folder
Views
Access
through
Resource
APIs
Use either:
CLOB
Structured
Hybrid
Storage
(semistructured
storage)
Store as:
CLOB in
XMLType
Table
File in
Repository
Folder
Views
Access
through
Resource
APIs
Unstructured
Data
Store as:
CLOB in
XMLType
Table
File in
Repository
Folder
Views
Access
through
Resource
APIs
Java, JNDI access. See Chapter 17, "Oracle XML DB Resource API for
Java/JNDI".
Java (through JDBC) access. See Chapter 9, "Java and Java Bean APIs for
XMLType".
These options for accessing Repository data are also discussed in Chapter 13,
"Oracle XML DB Foldering".
You can also consider the following access model criteria:
What level of security do you need? See Chapter 18, "Oracle XML DB Resource
Security".
What kind of indexing will best suit your application? Will you need to use
Oracle Text indexing and querying? See Chapter 4, "Using XMLType" and
Chapter 7, "Searching XML Data with Oracle Text".
Do you need to version the data? If yes, see Chapter 14, "Oracle XML DB
Versioning".
Figure 23 Data Access Models: How Will Users or Applications Access the Data?
Oracle XML DB
Data Access Options
Query-based
Access
Path-based
Access
Use SQL
Use Repository
Available Language
and XMLType APIs
Available Languages
and APIs
PL/SQL
JNDI
FTP
HTTP / WebDav
PLSQL
See Also:
XSLT. Will you need to transform the XML to HTML, WML, or other
languages, and how will your application transform the XML? While storing
XML documents in Oracle XML DB you can optionally ensure that their
structure complies (is valid against) with specific XML Schema. See
Chapter 6, "Transforming and Validating XMLType Data".
DOM. See Chapter 8, "PL/SQL API for XMLType". Use object-relational
columns, VARRAYs, nested tables, as well as LOBs to store any element or
Element-subtree in your XML Schema, and still maintain DOM fidelity (DOM
stored == DOM retrieved). Note: If you choose the CLOB storage option,
available with XMLType since Oracle9i Release 1 (9.0.1), you can keep
whitespaces. If you are using XML schema, see the discussion on DOM fidelity
in Chapter 5, "Structured Mapping of XMLType".
XPath searching. You can use XPath syntax embedded in an SQL statement or
as part of an HTTP request to query XML content in the database. See
Chapter 4, "Using XMLType",Chapter 7, "Searching XML Data with Oracle
Text", Chapter 13, "Oracle XML DB Foldering", and Chapter 15, "RESOURCE_
VIEW and PATH_VIEW".
XML Generation and XMLType views. Will you need to generate or regenerate
XML? If yes, see Chapter 10, "Generating XML Data from the Database".
How often will XML documents be accessed, updated, and manipulated? See
Chapter 4, "Using XMLType" and Chapter 15, "RESOURCE_VIEW and PATH_
VIEW".
Will you need to update fragments or the whole document? You can use XPath to
specify individual elements and attributes of your document during updates,
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:
2-10
CLOBs, when the XML documents are retrieved there will be no data loss. Data
integrity is high, and the cost of regeneration is low.
Piece-wise updatability
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:
Structured storage
SQLX operators. Using these operators you can store the data in relational
tables and also generate/regenerate the XML . See Chapter 10, "Generating
XML Data from the Database".
Object Types:
Object tables
Object constructors. You can store the data in relational tables using object
constructors.
Object views
XMLType
Views
Structured
Storage
Hybrid or
Semi-structured
Storage
SQLX
Operators
Object
Types
Relational
Tables
Object
Tables
Object
Views
Object
Constructors
Relational
Tables
2-12
3
Using Oracle XML DB
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:
Defining Your Own Default Table Storage for XML Schema-Based Documents
Parsing the XML document apart, outside Oracle9i database, and storing the
data in the XML document as rows in one or more tables. In this scenario the
database has no idea that is managing XML content.
Storing the XML document in Oracle9i database using a CLOB or VARCHAR
column. Again in this scenario the database has no idea that it is managing
XML content, but you can programmatically use the XDK to perform XML
operations.
Storing the XML document in Oracle9i database using the XMLType datatype.
Two options are available in this scenario.
Both these options mean that the database is aware that it is managing XML
content. Selecting this approach provides you with a number of significant
advantages, as the database provides a set of features that make it possible to
process XML content efficiently.
Example 31 Creating a Table with an XMLType Column
CREATE TABLE Example1
(
KEYVALUE varchar2(10) primary key,
XMLCOLUMN xmltype
);
Type
In/Out Default?
-------------- ----- ------VARCHAR2
IN
-- 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:
INSERT INTO XMLTABLE
VALUES(XMLTYPE(getDocument(purchaseorder.xml)));
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: Appendix C, "XPath and Namespace Primer" for an
introduction to the W3C XPath Recommendation.
</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 31.
Figure 31 existsNode() Syntax
,
EXISTSNODE
XMLType_instance
XPath_string
namespace
)
Example 34 existsNode() Examples That Find a Node to Match the XPath Expression
Given this sample XML document, the following existsNode() operators return
true (1).
SELECT existsNode(value(X),/PurchaseOrder/Reference)
FROM XMLTABLE X;
SELECT existsNode(value(X),
/PurchaseOrder[Reference="ADAMS-20011127121040988PST"])
FROM XMLTABLE X;
SELECT existsNode(value(X),
/PurchaseOrder/LineItems/LineItem[2]/Part[@Id="037429135020"])
FROM XMLTABLE X;
SELECT existsNode(value(X),
/PurchaseOrder/LineItems/LineItem[Description="8 1/2"])
FROM XMLTABLE X;
Example 35 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.
Example 36 Using existsNode() in the WHERE Clause
SELECT count(*)
FROM XMLTABLE x
WHERE existsNode(value(x),'/PurchaseOrder[User="ADAMS"]') = 1;
Using extractValue()
The extractValue() syntax is shown in Figure 32.
Figure 32 extractValue() Syntax
,
EXTRACTVALUE
XMLType_instance
value_expr
XPath_string
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.
Example 38 Non-Valid Uses of extractValue()
SELECT extractValue(value(X),
/PurchaseOrder/LineItems/LineItem/Description)
FROM XMLTABLE X;
-- FROM XMLTABLE X;
-*
-- ERROR at line 3:
-- ORA-19025: EXTRACTVALUE returns value of only one node
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 33.
Figure 33 extract() Syntax
,
EXTRACT
XMLType_instance
namespace
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 datatypes extract() method.
Example 310 Using extract() to Return an XML Fragment
This returns:
EXTRACT(VALUE(X),/PURCHASEORDER/LINEITEMS/LINEITEM/DESCRIPTION)
-----------------------------------------------------------------<Description>The Ruling Class</Description>
<Description>Diabolique</Description>
<Description>8 1/2</Description>
Example 311 Using extract() to Return a Node Tree that Matches an XPath
Expression
In this example extract() returns the node tree that matches the specified XPath
expression:
3-10
SELECT extract(value(X),
'/PurchaseOrder/LineItems/LineItem[1]')
FROM XMLTABLE X;
This returns:
EXTRACT(VALUE(X),'/PURCHASEORDER/LINEITEMS/LINEITEM[1]')
------------------------------------------------------------------------<LineItem ItemNumber="1">
<Description>The Ruling Class</Description>
<Part Id="715515012423" UnitPrice="39.95" Quantity="2"/>
</LineItem>
Using XMLSequence()
The XMLSequence() syntax is shown in Figure 34.
Figure 34 XMLSequence() Syntax
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 312 Using XMLSequence() and TABLE() to Extract Description Nodes from
an XML Document
The following example shows how to use XMLSequence() and Table() to extract
the set of Description nodes from the purchaseorder document.
set long 10000
set feedback on
SELECT extractValue(value(t),'/Description')
FROM XMLTABLE X,
TABLE ( xmlsequence (
extract(value(X),
'/PurchaseOrder/LineItems/LineItem/Description')
)
) t;
This returns:
EXTRACTVALUE(VALUE(T),'/DESCRIPTION')
------------------------------------------------------------------------The Ruling Class
Diabolique
8 1/2
UPDATEXML
XMLType_instance
XPath_string
value_expr
namespace
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 313 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.
3-12
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>
In this example updateXML() replaces the contents of the node tree associated
with the element identified by the XPath expression
/PurchaseOrders/LineItems/LineItem[2].
Note: In this example, since the replacement value is a Node tree,
This returns:
1 row updated.
SELECT value(t)
FROM XMLTABLE t;
3-14
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.
XMLTransform() function
Since XSL stylesheets are valid XML documents both approaches apply when the
XSL stylesheets are provided as instances of the XMLType datatype. The results of
the XSL transformation are also returned as an XMLType.
Because the transformation takes place close to the data, Oracle XML DB can
optimize features such as memory usage, I/O operations, and network traffic
required to perform the transformation.
See Also: Chapter 6, "Transforming and Validating XMLType
Data"
Example 316 Using transform() to Transform an XSL
The following example shows how transform() can apply XSLT to an XSL
stylesheet, PurchaseOrder.xsl, to transform the PurchaseOrder.xml
document:
SELECT value(t).transform(xmltype(getDocument('purchaseOrder.xsl')))
from XMLTABLE t
where existsNode(value(t),
'/PurchaseOrder[Reference="MILLER-200203311200000000PST"]'
) = 1;
This returns:
VALUE(T).TRANSFORM(XMLTYPE(GETDOCUMENT('PURCHASEORDER.XSL')))
------------------------------------------------------------------------<html>
<head/>
<body bgcolor="#003333" text="#FFFFCC" link="#FFCC00" vlink="#66CC99" alink="#
669999">
<FONT FACE="Arial, Helvetica, sans-serif">
<center>
...
</FONT>
</body>
</html>
3-16
3-18
</xs:schema>
To use a W3C XML Schema with Oracle XML DB, the XML schema document has
to be registered with the database. Once an XML schema has been registered
XMLType tables and columns can be created which are bound to the schema.
To register an XML schema you must provide two items. The first is the
XMLSchema document, the second is the URL which will be used by XML
documents which claim to conform to this Schema. This URL will be provided in
the root element of the instance document using either the
noNamespaceSchemaLocation attribute or schemaLocation attribute as
defined in the W3C XML Schema recommendation
XML schemas are registered using methods provided by PL/SQL package DBMS_
XMLSCHEMA. Schemas can be registered as global or local schemas. See Chapter 5,
"Structured Mapping of XMLType" for a discussion of the differences between
Global and Local Schemas.
Oracle XML DB provides a number of options for automatically generating default
database objects and Java classes as part of the schema registration process. Some of
these options are discussed later in this section.
Example 318 Registering PurchaseOrder.xsd as a Local XML Schema Using
registerSchema()
/
--This returns:
-- PL/SQL procedure successfully completed.
Create a set of entries in Oracle Data Dictionary that describe the XML schema
Create a set of SQL object definitions, based on the complexTypes defined in the
XML schema
Once the XML schema has been registered with Oracle XML DB, it can be
referenced when defining tables that contain XMLType columns, or creating
XMLType tables.
Example 319 Creating an XMLType Table that Conforms to an XML Schema
This example shows how to create an XMLType table which can only contain XML
Documents that conform to the definition of the PurchaseOrder element in the
XML schema registered at
http://www.oracle.com/xsd/purchaseorder.xsd.
CREATE TABLE XML_PURCHASEORDER of XMLType
XMLSCHEMA "http://www.oracle.com/xsd/purchaseOrder.xsd"
ELEMENT "PurchaseOrder";
3-20
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.
noNameSpaceSchemaLocation Attribute. The XML schema associated with the
unqualified elements is defined using the attribute
noNamespaceSchemaLocation. In the case of the PurchaseOrder.xsd XML
schema, the correct definition would be as follows:
<PurchaseOrder
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:noNamespaceSchemaLocation="http://www.oracle.com/xsd/purchaseOrder.xsd">
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:
This example shows how to use a CHECK constraint to an XMLType table and the
result of attempting to insert an invalid document into the table:
ALTER TABLE XML_PURCHASEORDER
add constraint VALID_PURCHASEORDER
check (XMLIsValid(sys_nc_rowinfo$)=1);
-- This returns:
-- Table altered
INSERT INTO XML_PURCHASEORDER
3-22
values (xmltype(getDocument(InvalidPurchaseOrder.xml)));
INSERT INTO XML_PURCHASEORDER;
*
-- This returns:
-- ERROR at line 1:
-- ORA-02290: check constraint (DOC92.VALID_PURCHASEORDER) violated
Example 322 Using BEFORE INSERT Trigger to Validate Data Inserted Into XMLType
Tables
The next example shows how to use a BEFORE INSERT trigger to validate that the
data being inserted into the XMLType table conforms to the 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.
insert into XML_PURCHASEORDER
values (xmltype(getDocument(InvalidPurchaseOrder.xml)));
----------
values (xmltype(getDocument(InvalidPurchaseOrder.xml)))
*
ERROR at line 2:
ORA-31154: invalid XML document
ORA-19202: Error occurred in XML processing
LSX-00213: only 0 occurrences of particle "User", minimum is 1
ORA-06512: at "SYS.XMLTYPE", line 0
ORA-06512: at "DOC92.VALIDATE_PURCHASEORDER", line 5
ORA-04088: error during execution of trigger DOC92.VALIDATE_PURCHASEORDER
As can be seen both approaches ensure that only valid XML documents can be
stored in the XMLType table:
BEFORE INSERT Trigger. The BEFORE INSERT trigger requires a little more
coding. Its advantage is that it is based on the schemaValidate() method.
This means that when the instance document is not valid it can provide
information about what was wrong with the instance document. It also has the
advantage of allowing the trigger to take corrective action when appropriate.
Storage technique Contents of XMLType columns and tables are Contents of XMLType columns and tables are
stored using the CLOB data type.
stored as a collection of SQL objects. By
default, the underlying storage model for
XML schema-based XMLType columns and
tables is structured storage.
Can store
non-XML
schema-based
tables?
Performance:
Storage and
retrieval speed
3-24
Performance:
operation speed
Flexible. Can
easily process
varied content?
Memory usage:
Do the XML
documents need
parsing?
Update
processing
Indexing
Space needed
Can be large.
Data integrity
--
Tuning:
Fine-grained
object control
None
3-26
One of the common problems application developers face when using a traditional
relational model to manage the contents of XML documents is how to preserve this
information. Table 32 compares DOM fidelity in structured and unstructured
storage:
An XML schema defines the set of elements and attributes that can exist in a
particular class of XML document and defines the relationships between them.
During XML schema registration, Oracle XML DB generates an SQL Object Type for
each complexType defined in the XML schema. The definition of the SQL object
mirrors the definition of the complexType.
Each child element and attribute defined by the complexType maps to an attribute
of the SQL object type.
3-28
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 323 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>
Name
Null?
------------------------------ -------SYS_XDBPD$
Reference
Actions
Reject
Requestor
User
CostCenter
ShippingInstructions
SpecialInstructions
LineItems
Type
---------------------------XDB.XDB$RAW_LIST_T
VARCHAR2(26)
XML_ACTIONS_TYPE
XML_REJECTION_TYPE
VARCHAR2(128)
VARCHAR2(10)
VARCHAR2(4)
XML_SHIPPINGINSTRUCTIONS_TYPE
VARCHAR2(2048)
XML_LINEITEMS_TYPE
also used to assign names to the SQL types that correspond to the
complexTypes: ActionsType, ShippingInstructionsType
and LineItemsType.
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.
3-30
Type
---------------------------XDB.XDB$RAW_LIST_T
VARCHAR2(26)
Actions
Reject
Requestor
User
CostCenter
ShippingInstructions
SPECINST
LineItems
XML_ACTIONS_TYPE
XML_REJECTION_TYPE
VARCHAR2(128)
VARCHAR2(10)
VARCHAR2(4)
XML_SHIPPINGINSTRUCTIONS_TYPE
CLOB
XML_LINEITEMS_TYPE
3-32
Separate XMLType Table with Link Table. The members of the collection are
stored as a separate XMLType table. An link table is created which cross
references which member in the child table are linked to which members of the
parent. Table. All data is visible as XMLTypes. Possible to link from the child
back to the parent. Problems with creating multiple XMLType columns based on
the Schema.
The following example shows how you can introduce a Unique and Referential
Constraint on the PurchaseOrder table.
XMLDATA.SQLAttributeName
alter table XML_PURCHASEORDER
add constraint REFERENCE_IS_UNQIUE
-- unique(extractValue(/PurchaseOrder/Reference))
unique (xmldata."Reference");
alter table XML_PURCHASEORDER
add constraint USER_IS_VALID
-- foreign key extractValue(/PurchaseOrder/User) references
SCOTT.EMP(ENAME)
foreign key (xmldata."User") references SCOTT.EMP(ENAME);
As can be seen, when an attempt is made to insert an XML Document that contains
a duplicate value for the element /PurchaseOrder/Reference into the table, the
database detects that the insert would violate the unique constraint, and raises the
appropriate error.
insert into xml_purchaseorder values (
xmltype(getDocument(ADAMS-20011127121040988PST.xml))
);
This returns:
1 row created.
insert into xml_purchaseorder values (
xmltype(getDocument(ADAMS-20011127121040988PST.xml))
);
insert into xml_purchaseorder values (
*
This returns:
ERROR at line 1:
ORA-00001: unique constraint (DOC92.REFERENCE_IS_UNQIUE) violated
The following example shows how the database will enforce the referential
constraint USER_IS_VALID, which states that the value of the element
/PurchaseOrder/User, that translates to the SQLAttribute xmldata.user,
must match one of the values of ENAME in SCOTT.EMP.
insert into xml_purchaseorder values (
xmltype(getDocument(HACKER-20011127121040988PST.xml))
);
insert into xml_purchaseorder values (
*
This returns:
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.USER_IS_VALID)
violated - parent key notfound
3-34
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.
See Also: Chapter 13, "Oracle XML DB Foldering"
WebDAV uses the term Resource to define a file or folder. It defines a set of basic
operations that can be performed on a Resource. These operations require a
WebDAV server to maintain a set of basic metadata for each Resource. Oracle XML
DB exposes this metadata as a set of XML Documents in the following form:
Example 327 Oracle XML DB Exposes WebDAV Resource Metadata as XML
Documents
<Resource xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"
Hidden="false" Invalid="false" Container="false"
CustomRslv="false">
<CreationDate> 2002-02-14T16:01:01.066324000</CreationDate>
<ModificationDate> 2002-02-14T16:01:01.066324000</ModificationDate>
<DisplayName>testFile.xml</DisplayName>
<Language>us english</Language>
<CharacterSet>utf-8</CharacterSet>
<ContentType>text/xml</ContentType>
<RefCount>1</RefCount>
<ACL>
<acl description="/sys/acls/all_all_acl.xml"
xmlns="http://xmlns.oracle.com/xdb/acl.xsd"
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation="http://xmlns.oracle.com/xdb/acl.xsd
http://xmlns.oracle.com/xdb/acl.xsd">
<ace>
<grant>true</grant>
<privilege>
<all/>
</privilege>
<principal>PUBLIC</principal>
</ace>
</acl>
</ACL>
<Owner>DOC92</Owner>
<Creator>DOC92</Creator>
<LastModifier>DOC92</LastModifier>
<SchemaElement>
http://xmlns.oracle.com/xdb/XDBSchema.xsd#binary
</SchemaElement>
<Contents>
<binary>02C7003802C77B7000081000838B1C240000000002C71E7C</binary>
</Contents>
</Resource>
RESOURCE_VIEW
PATH_VIEW
It also provides a set of SQL functions and PL/SQL packages for performing
Repository operations.
3-36
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
Name
Null?
------------------------------- -------RES
ANY_PATH
Type
---------------------------SYS.XMLTYPE
VARCHAR2(4000)
Using PATH_VIEW
PATH_VIEW contains an entry for each Path in the Repository. Since a Resource can
be linked into more than one folder, PATH_VIEW shows all possible Paths in the
Repository and the resources they point to. The definition of the PATH_VIEW is as
follows:
SQL> describe PATH_VIEW
Name
Null?
------------------------------- -------PATH
RES
LINK
Type
---------------------------VARCHAR2(1024)
SYS.XMLTYPE
SYS.XMLTYPE
3 begin
4
result := dbms_xdb.createFolder('/public/testFolder');
5 end;
6 /
PL/SQL procedure successfully completed.
SQL>
2
3
4
5
6
7
8
9
declare
result boolean;
begin
result := dbms_xdb.createResource(
'/public/testFolder/testFile.xml',
getDocument('testFile.xml')
);
end;
/
Updating Resources
You can update Resources using updateXML().
Example 329 Updating Repository Resources
For instance, the following query updates the OWNER and NAME of the document
created in the previous example.
update RESOURCE_VIEW
set RES=updateXML(RES,
/Resource/DisplayName/text(),RenamedFile,
/Resource/Owner/text(),SCOTT
)
where any_path = /public/testFolder/testFile.xml;
-- 1 row updated.
3-38
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.
Example 330 Deleting Repository Resources
call dbms_xdb.deleteResource('/public/testFolder/testFile.xml')
/
Call completed.
call dbms_xdb.deleteResource('/public/testFolder')
/
Call completed.
3-40
Defining Your Own Default Table Storage for XML Schema-Based Documents
resource is created that contains a reference to the appropriate row in the default
table.
One of the special features of an XMLType table is that it can be hierarchically enabled.
Default Tables, created as part of XML schema registration are automatically
hierarchically enabled. When a table is hierarchically enabled DML operations on
the default table may cause corresponding operations on the Oracle XML DB
Repository. For example, when a row is deleted from the default table, any entries
in the Repository which reference that row are deleted.
Example 331 Adding the xdb:defaultTable Attribute to the XML Schemas Element
Definition
Defining Your Own Default Table Storage for XML Schema-Based Documents
Example 332 Inserting an XML Document into Oracle XML DB Repository Causes a
Insertion of a Row into the Table
The following example shows how, once the XML schema is registered, and the
default table created, when inserting an XML document into Oracle XML DB
Repository causes a row to be inserted into the designated default table:
select count(*) from XML_PURCHASEORDER;
Results in:
COUNT(*)
---------0
-- create testFolder
declare
result boolean;
begin
result := dbms_xdb.createFolder(/public/testFolder);
end;
/
declare
result boolean;
begin
result := dbms_xdb.createResource(
/public/testFolder/purchaseOrder1.xml,
getDocument(purchaseOrder1.xml)
);
end;
/
-- PL/SQL procedure successfully completed.
3-42
commit;
-- Commit complete.
select count(*) from XML_PURCHASEORDER;
Results in:
COUNT(*)
---------1
Example 333 Deleting a Row Causes Deletion of Corresponding Entry from the
Repository
This example shows when deleting a row from the hierarchy enabled default table,
the corresponding entry is deleted from the hierarchy.
select extractValue(res,'Resource/DisplayName') "Filename"
from RESOURCE_VIEW where under_path(res,'/public/testFolder') = 1;
/
Results in:
Filename
---------------------------------------------------------------------purchaseOrder1.xml
delete from XML_PURCHASEORDER;
1 row deleted.
SQL> commit;
Commit complete.
select extractValue(res,'Resource/DisplayName') "Filename"
from RESOURCE_VIEW where under_path(res,'/public/testFolder') = 1
/
Results in:
no rows selected
default table. This reference can be used to perform join operations between the
resource and its content. This can be seen in the following example.
3-44
Command line clients, such as the command line clients supplied with Unix
and Windows Command Prompt
Figure 36, Figure 37, Figure 38, and Figure 39 show examples of how you can
access the root level of the Repository using various of standard FTP clients.
Figure 36 Accessing the Repository Root Level from the Command Prompt Command Line
Figure 37 Accessing the Repository Root Level fro m IE Browser Web Folder Menu
3-46
Figure 38 Accessing the Repository Root Level fro m WS_FTP95LE FTP Interface Program
3-48
Figure 311 Accessing the Repository Using HTTP/WebDAV Protocol Server from Microsoft Web
Folders Client
3-50
Part II
Storing and Retrieving XML Data in Oracle
XML DB
Part II of this manual introduces you to ways you can store, retrieve, validate, and
transform XML data using Oracle XML DB. It contains the following chapters:
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?
What Is XMLType?
Note:
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:
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).
What Is XMLType?
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:
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:
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.
Database schema
flexibility
Data integrity
and accuracy
Maintains the original XML byte for byte - Trailing new lines, whites pace within tags, and
important in some applications.
data format for non-string datatypes is lost. But
maintains DOM fidelity.
Performance
Access to SQL
Space needed
You need to store XML as a whole document in the database and retrieve it as a
whole document.
You do not need to perform piece-wise updates on XML documents.
Note: XMLType and Varray:
See Also:
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.
See Also: Appendix C, "XPath and Namespace Primer"
schema
CREATE
TABLE
XMLTYPE
XMLType_storage
table
OF
XMLTYPE
XMLSchema_spec
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.
The XMLType column can be created like any other user-defined type column:
CREATE TABLE warehouses(
warehouse_id NUMBER(3),
warehouse_spec XMLTYPE,
warehouse_name VARCHAR2(35),
location_id NUMBER(4));
As explained, you can create XMLType columns by simply using the XMLType as
the datatype. The following statement creates a purchase order document column,
poDoc, of XMLType:
CREATE TABLE po_xml_tab(
poid number,
poDoc XMLTYPE);
CREATE TABLE po_xtab of XMLType; -- this creates a table of XMLType. The default
-- is CLOB based storage.
You can alter tables to add XMLType columns as well. This is similar to any other
datatype. The following statement adds a new customer document column to the
table:
You can alter tables to drop XMLType columns, similar to any other datatype. The
following statement drops column custDoc:
ALTER TABLE po_xml_tab drop (custDoc);
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
To update an XML document, you can execute a standard SQL UPDATE statement.
You need to bind an XMLType instance, as follows:
UPDATE warehouses SET warehouse_spec = XMLType
(<Warehouse whono="200">
<Building>Leased</Building>
</Warehouse>);
This example created an XMLType instance from a string literal and updates column
warehouse_spec with the new value.
Note: Any triggers would get fired on the UPDATE statement
You can see and modify the XML value inside the triggers.
You can use extract() and existsNode() functions to identify rows to delete
as well. For example to delete all warehouse rows for which the warehouse
building is leased, you can write a statement such as:
DELETE FROM warehouses e
WHERE e.warehouse_spec.extract(//Building/text()).getStringVal()
= Leased;
4-10
Using XMLType
4-11
See Also:
You can specify storage characteristics on this column when creating the table as
follows:
CREATE TABLE po_xml_tab(
poid NUMBER(10),
poDoc XMLTYPE
)
XMLType COLUMN poDoc
4-12
STORE AS CLOB (
TABLESPACE lob_seg_ts
STORAGE (INITIAL 4096 NEXT 4096)
CHUNK 4096 NOCACHE LOGGING
);
To add a new XMLType column to this table and specify the storage clause for that
column, you can use the following SQL statement:
ALTER TABLE po_xml_tab add(
custDoc XMLTYPE
)
XMLType COLUMN custDoc
STORE AS CLOB (
TABLESPACE lob_seg_ts
STORAGE (INITIAL 4096 NEXT 4096)
CHUNK 4096 NOCACHE LOGGING
);
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.
Using XMLType
4-13
You can use the XMLDATA attribute in constraints and indexes, in addition to
storage clauses.
See also: Oracle9i Application Developers Guide - Large Objects
(LOBs) f and Oracle9i SQL Reference for more information about LOB
storage options
Example 413 Using ALTER TABLE to Change NOT NULL of XMLType Columns
You can also use the ALTER TABLE statement to change NOT NULL information
of an XMLType column, in the same way you would for other column types:
ALTER TABLE po_xml_tab MODIFY (poDoc NULL);
ALTER TABLE po_xml_tab MODIFY (poDoc NOT NULL);
You can also define check constraints on XMLType columns. Other default values
are not supported on this datatype.
4-14
XMLType columns can only store well-formed XML documents. Fragments and
other non-well-formed XML cannot be stored in XMLType columns.
By using XMLType constructors. This can be done in SQL, PL/SQL, and Java.
By using SQL functions like XMLElement(), XMLConcat(), and XMLAGG().
This can be done in SQL, PL/SQL, and Java.
The following examples use INSERT...SELECT and the XMLType constructor to first
create an XML document and then insert the document into the XMLType columns.
Consider table po_clob_tab that contains a CLOB, poClob, for storing an XML
document:
CREATE TABLE po_clob_tab
(
poid number,
poClob CLOB
);
Using XMLType
4-15
You can insert a purchase order XML document into table, po_xml_tab, by simply
creating an XML instance from the CLOB data stored in the other po_clob_tab:
INSERT INTO po_xml_tab
SELECT poid, XMLType(poClob)
FROM po_clob_tab;
Note: You can also get the CLOB value from any expression,
This example inserts a purchase order into table po_tab using the XMLType
constructor:
INSERT INTO po_xml_tab
VALUES(100, XMLType(<?xml version="1.0"?>
<PO pono="1">
<PNAME>Po_1</PNAME>
<CUSTNAME>John</CUSTNAME>
<SHIPADDR>
<STREET>1033, Main Street</STREET>
<CITY>Sunnyvalue</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>'));
4-16
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.
Using XMLType
4-17
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>
4-18
Description
Denotes the root of the tree in an XPath expression. For example, /PO refers to the
child of the root node whose name is PO.
Also used as a path separator to identify the children node of any given node. For
example, /PO/PNAME identifies the purchase order name element, a child of the root
element.
//
Used to identify all descendants of the current node. For example, PO//ZIP matches
any zip code element under the PO element.
"*
Used as a wildcard to match any child node. For example, /PO/*/STREET matches
any street element that is a grandchild of the PO element.
[]
Used to denote predicate expressions. XPath supports a rich list of binary operators
such as OR, AND, and NOT. For example, /PO[PONO=20 and PNAME=PO_
2]/SHIPADDR select out the shipping address element of all purchase orders whose
purchase order number is 20 and whose purchase order name is PO_2. [ ] is also
used for denoting an index into a list. For example, /PO/PONO[2] identifies the
second purchase order number element under the PO root element.
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.
See Also: Appendix C, "XPath and Namespace Primer"
This example shows how to select an XMLType column using getClobVal() and
existsNode():
set long 2000
SELECT e.poDoc.getClobval() AS poXML
FROM po_xml_tab e
WHERE e.poDoc.existsNode(/PO[PNAME = "po_2"]) = 1;
Using XMLType
4-19
POXML
--------------------<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>Nance</CUSTNAME>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
existsNode Function
The syntax for the existsNode() function is described in Figure 42 and also as
follows:
existsNode(XMLType_instance IN XMLType,
XPath_string IN VARCHAR2, namespace_string IN varchar2 := null)
RETURN NUMBER
,
EXISTSNODE
XMLType_instance
XPath_string
namespace
)
4-20
<STATE>CA</STATE>
</SHIPADDR>
</PO>
The following example tests for the existence of the /Warehouse/Dock node in the
warehouse_spec column XML path of the sample table oe.warehouses:
SELECT warehouse_id, EXISTSNODE(warehouse_spec, /Warehouse/Docks)
"Loading Docks"
FROM warehouses
WHERE warehouse_spec IS NOT NULL;
WAREHOUSE_ID Loading Docks
------------ ------------1
1
2
1
3
0
4
1
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
Using XMLType
4-21
,
EXTRACT
XMLType_instance
namespace
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.
Note: The latter is still considered an XMLType. In other words,
4-22
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>
Using XMLType
4-23
extractValue() Function
The extractValue() function takes as arguments an XMLType instance and an
XPath expression. It returns a scalar value corresponding to the result of the XPath
evaluation on the XMLType instance. extractValue() syntax is also described in
Figure 44.
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.
Figure 44 extractValue() Syntax
,
EXTRACTVALUE
XMLType_instance
value_expr
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().
4-24
extractValue() Characteristics
extractValue() has the following characteristics:
Example 423 Extracting the Scalar Value of an XML Fragment Using extractValue()
The following example takes as input the same arguments as the example for
extract () Function on page 4-21. Instead of returning an XML fragment, as
extract() does, it returns the scalar value of the XML fragment:
SELECT warehouse_name,
extractValue(e.warehouse_spec, /Warehouse/Docks)
"Docks"
FROM warehouses e
WHERE warehouse_spec IS NOT NULL;
WAREHOUSE_NAME
-------------------Southlake, Texas
San Francisco
New Jersey
Seattle, Washington
Docks
-----------2
1
3
Using XMLType
4-25
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()
Assume the po_xml_tab table, which contains the purchase order identification
and the purchase order XML columns, and assume that the following values are
inserted into the table:
INSERT INTO po_xml_tab values (100,
xmltype(<?xml version="1.0"?>
<PO>
<PONO>221</PONO>
<PNAME>PO_2</PNAME>
</PO>));
INSERT INTO po_xml_tab values (200,
xmltype(<?xml version="1.0"?>
<PO>
<PONAME>PO_1</PONAME>
</PO>));
Now you can extract the numerical values for the purchase order numbers using
extract():
SELECT e.poDoc.extract(//PONO/text()).getNumberVal() as pono
FROM po_xml_tab e
WHERE e.podoc.existsnode(/PO/PONO) = 1 AND poid > 1;
Here extract() extracts the contents of tag, purchase order number, PONO.
existsNode() finds nodes where PONO exists as a child of PO.
Note: Here text() function is only used to return the text
4-26
The following example shows how you can select out the XML data and query it
inside PL/SQL: create a transient instance from the purchase order table and then
perform some extraction on it. Assume po_xml_tab contains the data shown in
Example 416, "Inserting XML Data Using XMLType() with String", modified:
set serverout on
declare
poxml XMLType;
cust XMLType;
val VARCHAR2(200);
begin
-- select the adt instance
select poDoc into poxml
from po_xml_tab p where p.poid = 100;
-- do some traversals and print the output
cust := poxml.extract('//SHIPADDR');
-- do something with the customer XML fragment
val := cust.getStringVal();
dbms_output.put_line(' The customer XML value is '|| val);
end;
/
Example 426 Extracting Data from an XML Document and Inserting It Into a Table
Using extract()
The following example shows how you can extract out data from an XML purchase
order and insert it into an SQL relational table. Consider the following relational
tables:
CREATE TABLE cust_tab
(
custid number primary key,
custname varchar2(20)
);
INSERT INTO cust_tab values (1001, 'John Nike');
Using XMLType
4-27
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>
4-28
PONO
PNAME CUSTID SHIPSTREET
SHIPCITY SHIPZIP
---------------------------------------------------------------2001
Po_1
1001
323 College Drive Edison
08820
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 427 Extracting Data from an XML Document and Inserting It Into a Table
Using extract() In a PL/SQL Block
You can do the same in an equivalent fashion inside a PL/SQL block, as follows:
DECLARE
poxml XMLType;
cname varchar2(200);
pono number;
pname varchar2(100);
shipstreet varchar2(100);
shipcity varchar2(30);
shipzip varchar2(20);
BEGIN
-- select the adt instance
SELECT poDoc INTO poxml FROM po_xml_tab p;
cname := poxml.extract('//CUSTOMER/@CUSTNAME').getstringval();
pono := poxml.extract('/PO/PONO/text()').getnumberval();
pname := poxml.extract('/PO/PNAME/text()').getstringval();
shipstreet := poxml.extract('/PO/SHIPADDR/STREET/text()').getstringval();
shipcity := poxml.extract('//CITY/text()').getstringval();
shipzip := poxml.extract('//ZIP/text()').getstringval();
INSERT INTO po_rel_tab
VALUES (pono, pname,
(SELECT custid FROM cust_tab c WHERE custname = cname),
shipstreet, shipcity, shipzip);
END;
/
Using XMLType
4-29
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.
Example 429 Searching XML Data with extractValue()
extract() member function extracts nodes identified by the XPath expression and
returns an XMLType containing the fragment. Here, the result of the traversal may
be a set of nodes, a singleton node, or a text value. You can check if the result is a
fragment by using the isFragment() function on the XMLType. For example:
SELECT e.poDoc.extract('/PO/SHIPADDR/STATE').isFragment()
FROM po_xml_tab e;
4-30
This example updates the XMLType using the UPDATE statement. It updates only
those documents whose purchase order number is 2001.
UPDATE po_xml_tab e
SET e.poDoc = XMLType(
'<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>Nance</CUSTNAME>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
Using XMLType
4-31
</SHIPADDR>
</PO>')
WHERE e.poDoc.EXTRACT('/PO/PONO/text()').getNumberVal() = 2001;
To update the XML document in the table instead of creating a new one, you can
use the updateXML() in the right hand side of an UPDATE statement to update
the document.
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
SELECT e.poDoc.getstringval() AS newpo
FROM po_xml_tab e;
NEWPO
-------------------------------------------------------------------<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>John</CUSTNAME>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
4-32
You can update multiple elements within a single updateXML() expression. For
instance, you can use the same UPDATE statement as shown in the preceding
example and update purchase order, po:
UPDATE emp_tab e
SET e.emp_col = UPDATEXML(e.emp_col,
'/EMPLOYEES/EMP[EMPNAME="Joe"]/SALARY/text()',100000,
'//EMP[EMPNAME="Jack"]/EMPNAME/text()','Jackson',
'//EMP[EMPNO=217]',XMLTYPE.CREATEXML(
'<EMP><EMPNO>217</EMPNO><EMPNAME>Jane</EMPNAME></EMP>'))
WHERE EXISTSNODE(e.emp_col, '//EMP') = 1;
This updates all rows that have an employee element with the new values.
Example 434 Updating Customer Name in Purchase Order XML Document Using
updateXML()
The following example updates the customer name in the purchase order XML
document, po:
Note: This example only selects the document and the update
Using XMLType
4-33
You can also use updateXML() to update multiple pieces of a transient instance.
For example, consider the following XML document stored in column emp_col of
table, emp_tab:
<EMPLOYEES>
<EMP>
<EMPNO>112</EMPNO>
<EMPNAME>Joe</EMPNAME>
<SALARY>50000</SALARY>
</EMP>
<EMP>
<EMPNO>217</EMPNO>
<EMPNAME>Jane</EMPNAME>
<SALARY>60000</SALARY>
</EMP>
<EMP>
<EMPNO>412</EMPNO>
<EMPNAME>Jack</EMPNAME>
<SALARY>40000</SALARY>
</EMP>
</EMPLOYEES>
To generate a new document with Joes salary updated to 100,000, update the Name
of Jack to Jackson, and modify the Employee element for 217, to remove the salary
element. You can write a query such as:
SELECT UPDATEXML(emp_col, '/EMPLOYEES/EMP[EMPNAME="Joe"]/SALARY/text()', 100000,
'//EMP[EMPNAME="Jack"]/EMPNAME/text()','Jackson',
'//EMP[EMPNO=217]',
XMLTYPE.CREATEXML('<EMP><EMPNO>217</EMPNO><EMPNAME>Jane</EMPNAME>'))
FROM emp_tab e;
4-34
<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.
'//empno/text()' to NULL.
Using XMLType
4-35
NULL Updates When Object Types Are Generated by XML Schema Registration
NULL updates remove the element except when DOM fidelity is not maintained.
Example 437 NULL Updates with updateXML()
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>
4-36
expressions in left-to-right order. Each successive XPath works on the result of the
previous XPath update.
XMLTransform() Function
The XMLTransform() function takes in an XMLType instance and an XSLT
stylesheet. It applies the stylesheet to the XML document and returns a transformed
XML instance. See Figure 45.
Figure 45 XMLTransform() Syntax
XMLTRANSFORM
XMLType_instance
XMLType_instance
For example, to delete all purchase order rows with a purchase order name of Po_
2, execute a statement such as:
DELETE FROM po_xml_tab e
WHERE e.poDoc.extract('/PO/PNAME/text()').getStringVal()='Po_2';
For example, you can write a trigger to change the purchase order if it does not
contain a shipping address:
CREATE OR REPLACE TRIGGER po_trigger
Using XMLType
4-37
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.
4-38
The SQL query uses this function-based index, to evaluate the predicate instead of
parsing the XML document row by row, and evaluating the XPath expression.
Example 441 Creating a Function-Based index on an existsNode() Function
You can also create bitmapped function-based indexes to speed up the evaluation of
the operators. existsNode() is suitable, since it returns a value of 1 or 0
depending on whether the XPath is satisfied in the XML document or not.
For example, to speed up a query that searches whether the XML document
contains an element called Shipping address (SHIPADDR) at any level:
SELECT * FROM po_xml_tab e
WHERE e.poDoc.existsNode(//SHIPADDR) = 1;
Using XMLType
4-39
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.
For example:
SELECT * FROM po_xml_tab w
WHERE CONTAINS(w.poDoc,
'haspath(/PO[./@CUSTNAME="John Nike"])') > 0;
QUERY_REWRITE privilege. You must have this privilege granted to create text
indexes on XMLType columns in your own schema.
GLOBAL_QUERY_REWRITE privilege. If you need to create Oracle Text indexes
on XMLType columns in other schemas or on tables residing in other schemas,
you must have this privilege granted.
Oracle Text index uses the PATH_SECTION_GROUP as the default section group
when indexing XMLType columns. This default can be overridden during Oracle
Text index creation.
With this release, you no longer need the additional QUERY_REWRITE privileges
when creating Oracle Text indexes.
See Also:
4-40
Since Oracle Text index ignores spaces, the XPath expression may not yield
accurate results when spaces are significant.
Using XMLType
4-41
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.
See Also: Chapter 7, "Searching XML Data with Oracle Text",
4-42
5
Structured Mapping of XMLType
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 DBMS_XMLSCHEMA
DOM Fidelity
</element>
<element name="Price" type="float"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<element name="PurchaseOrder" type="po:PurchaseOrderType"/>
</schema>
Note:
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:
Explicitly referencing a global XML schema when a local XML schema exists
with the same name.
Generating a structured database mapping from your XML schemas during
XML schema registration. This includes generating SQL object types, collection
types, and default tables, and capturing the mapping information using XML
schema attributes.
Specifying a particular SQL type mapping when there are multiple legal
mappings.
Creating XMLType tables, views and columns based on registered XML
schemas.
Performing manipulation (DML) and queries on XML schema-based XMLType
tables.
Automatically inserting data into default tables when schema-based XML
instances are inserted into Oracle XML DB Repository using FTP,
HTTP/WebDav protocols and other languages.
If your data is highly structured (mostly XML), each element in the XML
documents can be stored as a column in a table.
Introducing DBMS_XMLSCHEMA
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 DBs XML schema functionality is available through the PL/SQL
supplied package, DBMS_XMLSCHEMA, a server-side component that handles the
registration of XML schema definitions for use by Oracle XML DB applications.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
XML documents conforming to this XML schema, and referencing it using the
XML schemas URL within the XML document, can be processed by Oracle
XML DB.
Tables and columns can be created for root XML elements defined by this XML
schema to store the conforming XML documents.
<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
Local XML schema: An XML schema registered as a local schema is, by default,
visible only to the owner.
Global XML schema: An XML schema registered as a global schema is, by
default, visible and usable by all database users.
5-10
/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.
See Also: Chapter 18, "Oracle XML DB Resource Security"
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
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:
5-12
See Also:
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.
That the current user has the appropriate privileges (ACLs) to delete the
resource corresponding to the XML schema within Oracle XML DB Repository.
You can thus control which users can delete which XML schemas by setting the
appropriate ACLs on the XML schema resources.
For dependents. If there are any dependents, it raises an error and the deletion
operation fails. This is referred to as the RESTRICT mode of deleting XML
schemas.
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.
The following example deletes XML schema PO.xsd. First, the dependent table
po_tab is dropped. Then, the schema is deleted using the FORCE and CASCADE
modes with DBMS_XMLSCHEMA.DELETESCHEMA:
drop table po_tab;
EXEC dbms_xmlschema.deleteSchema(http://www.oracle.com/PO.xsd,
dbms_xmlschema.DELETE_CASCADE_FORCE);
Tables or views that have an XMLType column that conforms to some element
in the XML schema.
XML schemas that include or import this schema as part of their definition.
Cursors that reference the XML schema name, for example, within DBMS_
XMLGEN operators. Note that these are purely transient objects.
For example you can create an XML schema-based XMLType table as follows:
CREATE TABLE po_tab OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/PO.xsd" ELEMENT "PurchaseOrder";
5-14
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>));
Data"
Example 58 Validating XML Using schemaValidate()
The following PL/SQL example validates an XML instance against XML schema
PO.xsd:
declare
xmldoc xmltype;
begin
-- populate xmldoc (by fetching from table)
select value(p) into xmldoc from po_tab p;
-- validate against XML schema
xmldoc.schemavalidate();
if xmldoc.isschemavalidated() = 1 then
dbms_output.put_line(Data is valid);
else
dbms_output.put_line(Data is invalid);
end if;
end;
If there are no such XML schemas, then they are resolved as names of global
XML schemas.
If there are no global XML schemas, then Oracle XML DB raises an error.
Global XML schemas that have the same name as local XML schemas
Fully Qualified XML Schema URLs Permit Explicit Reference to XML Schema
URLs
To permit explicit reference to XML schemas in these cases, Oracle XML DB
supports a notion of fully 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>/<schemaURLminus-protocol>
For example, consider the global XML schema with the following URL:
http://www.example.com/po.xsd
Assume that database user SCOTT has a local XML schema with the same URL:
http://www.example.com/po.xsd
User JOE can reference the local XML schema owned by SCOTT as follows:
http://xmlns.oracle.com/xdb/schemas/SCOTT/www.example.com/po.xsd
Similarly, the fully qualified URL for the global XML schema is:
http://xmlns.oracle.com/xdb/schemas/PUBLIC/www.example.com/po.xsd
5-16
Since XML schema registration potentially involves creating object types and tables,
error recovery involves dropping any such created types and tables. Thus, the
entire XML schema registration is guaranteed to be atomic. That is, either it
succeeds or the database is restored to the state before the start of registration.
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.
Example 511 Generating XML Schema: Using generateSchema()
5-18
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>
Description
isSchemaBased()
getSchemaURL()
Returns the XML schema URL, name of root element, and the namespace for an
XML schema-based XMLType instance.
getRootElement()
getNamespace()
schemaValidate()
isSchemaValid()
is SchemaValidated()
setSchemaValidated()
See Also:
5-20
DOM Fidelity
SQL object types can be created optionally during the XML schema
registration process. See "Creating XMLType Tables and Columns Based on
XML Schema" on page 5-23.
In a single underlying LOB column. Here the storage choice is specified in the
STORE AS clause of the CREATE TABLE statement:
CREATE TABLE po_tab OF xmltype
STORE AS CLOB
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder";
Design criteria for storing XML data are discussed inChapter 2, "Getting Started
with Oracle XML DB" and Chapter 3, "Using Oracle XML DB".
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.
See Also: "Setting the SQLInLine Attribute to FALSE for
Out-of-Line Storage" on page 5-38
DOM Fidelity
Comments
Namespace declarations
Prefix information
To ensure the integrity and accuracy of this data, for example, when regenerating
XML documents stored in the database, Oracle XML DB uses a data integrity
mechanism called DOM fidelity.
DOM fidelity refers to how identical the returned XML documents are compared to
the original XML documents, particularly for purposes of DOM traversals.
5-22
TABLE
XMLTYPE
XMLType_storage
.
table
OF
XMLTYPE
XMLSchema_spec
A subset of the XPointer notation, shown in the following example, can also be used
to provide a single URL containing the XML schema location and element name.
Example 512 Creating XML Schema-Based XMLType Table
This example creates the XMLType table po_tab using the XML schema at the
given URL:
CREATE TABLE po_tab OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/PO.xsd" ELEMENT "PurchaseOrder";
or example, when PO.xsd is registered with Oracle XML DB, the following SQL
types are created.
Note: The names of the types are generated names, and will not
5-24
If you specify the SQLName and SQLType values, Oracle XML DB creates the
SQL object types using these names.
If you do not specify these attributes, Oracle XML DB uses system-generated
names.
Note: You do not have to specify values for any of these
Values
Default
Description
SQLName
Element name
SQLType
Name generated
Specifies the name of the SQL type
from element name corresponding to this XML
element declaration.
SQLCollType
Name generated
Specifies the name of the SQL collection
from element name type corresponding to this XML element
that has maxOccurs > 1.
SQLSchema
User registering
XML schema
SQLCollSchema
User registering
XML schema
maintainOrder
true | false
true
SQLInline
true | false
true
maintainDOM
true | false
true
5-26
Values
Default
Description
columnProps
NULL
tableProps
NULL
defaultTable
Based on element
name.
beanClassname
Generated from
element name.
JavaClassname
None
Values
Default
Description
SQLType
SQLSchema
beanClassname
Generated from
element name.
maintainDOM
true | false
true
Values
Default
Description
mapUnboundedStringToLob
true | false
false
storeVarrayAsTable
true | false
false
5-28
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 52 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.
5-30
Create
XMLType
Table
Structured
Storage
Store as CLOB
employee_2002 tables
employee_2002 tables
...
XMLType Column . . .
...
dept_id
...
...
...
...
...
...
...
...
...
...
scott
...1234
...
...
...
...
...
tiger
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.
Primitive type
Global simpleType, declared within this XML schema or in an external XML
schema
Reference to global attribute (ref=".."), declared within this XML schema or
in an external XML schema
Local simpleType
In all cases, the SQL type and associated information (length and precision) as well
as the memory mapping information, are derived from the simpleType on which
the attribute is based.
If the default type is a STRING, you can override it with any of the following:
CHAR, VARCHAR, or CLOB.
If the default type is RAW, you can override it with RAW or BLOB.
5-32
Any of the ways for specifying type for an attribute declaration. See "Setting
Attribute Mapping Type Information" on page 5-32.
Global complexType, specified within this XML schema document or in an
external XML schema.
Reference to a global element (ref="..."), which could itself be within this
XML schema document or in an external XML schema.
Local complexType.
VARCHAR2
RAW
CLOB
BLOB
These represent storage of the XML in a text or unexploded form in the database.
The following special cases are handled:
The name of the VARRAY type is either explicitly specified by the user
using SQLCollType attribute or obtained by mangling the element
name.
An XML primitive type is mapped to the closest SQL datatype. For example,
DECIMAL, POSITIVEINTEGER, and FLOAT are all mapped to SQL NUMBER.
An XML enumeration type is mapped to an object type with a single RAW(n)
attribute. The value of n is determined by the number of possible values in the
enumeration declaration.
An XML list or a union datatype is mapped to a string (VARCHAR2/CLOB)
datatype in SQL.
...
CLOB
...
Entire resume
value is stored
in the CLOB
5-34
Default Mapping
Compatible Datatype
string
CHAR,VARCHAR2,
CLOB
string
--
VARCHAR2(4000) if
mapUnboundedStringToLob="true",
CLOB
Default Mapping
Compatible Datatype
hexBinary,
base64Binary
RAW, BLOB
hexBinary,
base64Binary
RAW(2000) if
mapUnboundedStringToLob="true",
BLOB
RAW, BLOB
Default
Oracle
DataType
float
NUMBER
NUMBER(m,n)
double
NUMBER
NUMBER(m,n)
decimal
NUMBER
NUMBER(m,n)
integer
NUMBER
NUMBER(m,n)
nonNegativeInteger
NUMBER
NUMBER(m,n)
positiveInteger
NUMBER
NUMBER(m,n)
nonPositiveInteger
NUMBER
NUMBER(m,n)
Compatible Datatypes
Default
Oracle
DataType
negativeInteger
NUMBER
NUMBER(m,n)
long
NUMBER(20)
NUMBER(m,n)
unsignedLong
NUMBER(20)
NUMBER(m,n)
int
NUMBER(10)
NUMBER(m,n)
unsignedInt
NUMBER(10)
NUMBER(m,n)
short
NUMBER(5)
NUMBER(m,n)
unsignedShort
NUMBER(5)
NUMBER(m,n)
byte
NUMBER(3)
NUMBER(m,n)
unsignedByte
NUMBER(3)
NUMBER(m,n)
Compatible Datatypes
Default Mapping
Compatible Datatypes
datetime
TIMESTAMP
DATE
time
TIMESTAMP
DATE
date
DATE
DATE
gDay
DATE
DATE
gMonth
DATE
DATE
gYear
DATE
DATE
gYearMonth
DATE
DATE
gMonthDay
DATE
DATE
duration
VARCHAR2(4000)
none
5-36
Compatible Datatypes
boolean
RAW(1)
VARCHAR2
Language(string)
VARCHAR2(4000)
CLOB, CHAR
NMTOKEN(string)
VARCHAR2(4000)
CLOB, CHAR
NMTOKENS(string)
VARCHAR2(4000)
CLOB, CHAR
Name(string)
VARCHAR2(4000)
CLOB, CHAR
NCName(string)
VARCHAR2(4000)
CLOB, CHAR
ID
VARCHAR2(4000)
CLOB, CHAR
IDREF
VARCHAR2(4000)
CLOB, CHAR
IDREFS
VARCHAR2(4000)
CLOB, CHAR
ENTITY
VARCHAR2(4000)
CLOB, CHAR
ENTITIES
VARCHAR2(4000)
CLOB, CHAR
NOTATION
VARCHAR2(4000)
CLOB, CHAR
anyURI
VARCHAR2(4000)
CLOB, CHAR
anyType
VARCHAR2(4000)
CLOB, CHAR
anySimpleType
VARCHAR2(4000)
CLOB, CHAR
QName
XDB.XDB$QNAME
--
5-38
XMLType table
</element>
</sequence>
</complexType>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
On registering this XML schema, Oracle XML DB generates the following types and
XMLType tables:
CREATE TYPE OBJ_T1 AS OBJECT
(
SYS_XDBPD$ XDB.XDB$RAW_LIST_T,
Street VARCHAR2(4000),
City VARCHAR2(4000)
);
CREATE TYPE OBJ_T2 AS OBJECT
(
SYS_XDBPD$ XDB.XDB$RAW_LIST_T,
Name VARCHAR2(4000),
Age NUMBER,
Addr REF XMLType
);
In the following example, the XML schema specifies that the XML fragments
element Addr is using the attribute SQLType="CLOB":
declare
doc varchar2(3000) := <schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/emp.xsd"
xmlns:emp="http://www.oracle.com/emp.xsd"
5-40
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
);
Street and
city are stored
in the CLOB
Base type
complexType extension
complexType restriction.
5-42
because SQL does not support restriction of object types through the
inheritance mechanism. Any constraints are imposed by the restriction in XML
schema.
Example 517 Inheritance in XML Schema: complexContent as an Extension of
complexTypes
Consider an XML schema that defines a base complexType "Address" and two
extensions "USAddress" and "IntlAddress".
declare
doc varchar2(3000) := <xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<xs:complexType name="Address" xdb:SQLType="ADDR_T">
<xs:sequence>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="USAddress" xdb:SQLType="USADDR_T">
<xs:complexContent>
<xs:extension base="Address">
<xs:sequence>
<xs:element name="zip" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="IntlAddress" final="#all" xdb:SQLType="INTLADDR_T">
<xs:complexContent>
<xs:extension base="Address">
<xs:sequence>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
5-44
Since inheritance support in SQL does not support a notion of restriction,the SQL
type corresponding to the restricted complexType is a empty subtype of the parent
object type.For the preceding XML schema, the following SQL types are generated:
create type ADDR_T as object (
SYS_XDBPD$ XDB.XDB$RAW_LIST_T,
"street" varchar2(4000),
"city" varchar2(4000),
"zip" varchar2(4000),
"country" varchar2(4000)
) not final;
create type USADDR_T under ADDR_T;
</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)
);
The namespace attribute can be used to restrict the contents so that they
belong to a specified namespace.
The processContents attribute within the any element declaration, indicates
the level of validation required for the contents matching the any declaration.
This XML schema example declares an any element and maps it to the column
SYS_XDBANY$,in object type OBJ_T. This element also declares that the attribute,
processContents,skips validating contents that match the any declaration.
declare
doc varchar2(3000) := <schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/any.xsd"
xmlns:emp="http://www.oracle.com/any.xsd"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<complexType name = "Employee" xdb:SQLType="OBJ_T">
<sequence>
<element name = "Name" type = "string" />
<element name = "Age" type = "decimal"/>
<any namespace = "http://www/w3.org/2001/xhtml" processContents = "skip"/>
5-46
</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;
create type CT2 as object
(
SYS_XDBPD$ xdb.xdb$raw_list_t,
"e1" varchar2(4000),
"e2" CT1
) not final;
5-48
<xs:complexType name=
"CT2"...>
.
.
.
<xs:element name=
"e2" type="CT1"/>
.
.
.
page 5-72
5-50
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.
Note: XMLDATA is a pseudo-attribute of XMLType that enables
direct access to the underlying object column. See Chapter 4, "Using
XMLType", under Changing the Storage Options on an XMLType
Column Using XMLData.
Object notation
CREATE TABLE MyPOs OF XMLTYPE
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder"
(unique(xmldata.ponum));
XML notation
CREATE TABLE MyPOs P OF XMLTYPE
ELEMENT
"http://www.oracle.com/PO.xsd#PurchaseOrder"(unique(ExtractValue(p,'/ponum')
);
5-52
enables the XPath to be evaluated against the XML document without having to
ever construct the XML document in memory.
Example 523 Query Rewrite
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.
extract()
existsNode()
extractValue
updateXML
The rewrite happens when these SQL functions are present in any expression in a
query, DML, or DDL statement. For example, you can use extractValue() to
create indexes on the underlying relational columns.
Here are some examples of statements that get rewritten to use underlying
columns:
Example 525 DML Statement and Query Rewrites
This example deletes all purchaseorders where the Company is not Oracle:
DELETE FROM MYPOs x
WHERE EXTRACTVALUE(value(x),/PurchaseOrder/Company) = Oracle Corp;
This example creates an index on the Company column, since this is stored object
relationally and the query rewrite happens, a regular index on the underlying
relational column will be created:
CREATE INDEX company_index ON MyPos e
(extractvalue(value(e),/PurchaseOrder/Company));
In this case, if the rewrite of the SQL functions results in a simple relational column,
then the index is turned into a B*Tree or a domain index on the column, rather than
a function-based index.
5-54
Table 510 Supported XPath Expressions for Translation to Underlying SQL Queries
XPath Expression for Translation
Description
Involves traversals over object type attributes only, where the attributes
are simple scalar or object types themselves. The only axes supported
are the child and the attribute axes.
/PurchaseOrder/@PurchaseDate
/PurchaseOrder/Company
Collection traversal expressions:
/PurchaseOrder/Item/Part
Predicates:
[Company="Oracle"]
List indexe:
lineitem[1]
Unsupported XPath Constructs The following XPath constructs do not get rewritten:
XPath Functions
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:
Enumeration types.
Substitutable elements.
5-56
<maxLength value="1000"/>
</restriction>
</simpleType>
</element>
<element name="Price" type="float"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<element name="PurchaseOrder" type="po:PurchaseOrderType"/>
</schema>;
begin
dbms_xmlschema.registerSchema(http://www.oracle.com/PO.xsd, doc);
end;
-- A table is created conforming to this schema
CREATE TABLE MyPOs OF XMLTYPE
ELEMENT "http://www.oracle.com/PO.xsd#PurchaseOrder";
-- The inserted XML document is partially validated against the schema before
-- it is inserted.
insert into MyPos values (xmltype(<PurchaseOrder
xmlns="http://www.oracle.com/PO.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/PO.xsd
http://www.oracle.com/PO.xsd">
<PONum>1001</PONum>
<Company>Oracle Corp</Company>
<Item>
<Part>9i Doc Set</Part>
<Price>2550</Price>
</Item>
<Item>
<Part>8i Doc Set</Part>
<Price>350</Price>
</Item>
</PurchaseOrder>));
Since the XML schema did not specify anything about maintaining the ordering, the
default is to maintain the ordering and DOM 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 of Predicates"
"Collection Index"
"Namespace Handling"
Mapping for a Simple XPath A rewrite for a simple XPath involves accessing the
attribute corresponding to the XPath expression. Table 511 lists the XPath map:
5-58
Maps to
/PurchaseOrder
column XMLData
/PurchaseOrder/@PurchaseDate
column XMLData."PurchaseDate"
/PurchaseOrder/PONum
column XMLData."PONum"
/PurchaseOrder/Item
/PurchaseOrder/Item/Part
Mapping for Scalar Nodes An XPath expression can contain a text() operator which
maps to the scalar content in the XML document. When rewriting, this maps
directly to the underlying relational columns.
For example, the XPath expression "/PurchaseOrder/PONum/text()" maps to
the SQL column XMLData."PONum" directly.
A NULL value in the PONum column implies that the text value is not available,
either because the text node was not present in the input document or the element
itself was missing. This is more efficient than accessing the scalar element, since we
do not need to check for the existance of the element in the SYS_XBDPD$ attribute.
For example, the XPath "/PurchaseOrder/PONum" also maps to the SQL attribute
XMLData."PONum",
However,in this case, query reqrite also has to check for the existance of the element
itself, using the SYS_XDBPD$ in the XMLData column.
Mapping of Predicates Predicates are mapped to SQL predicate expressions.
Example 528 Mapping Predicates
from mypos p
where existsNode(value(p),/PurchaseOrder[PONum=1001 and Company = "Oracle
Corp"]) =1;
5-60
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.
Example 531 Document Ordering with Collection Traversals
For example:
SELECT extract(value(p),/PurchaseOrder/Item[Price>2100]/Part)
FROM mypos p;
Though in most cases, the result of the aggregation would be in the same order as
the collection elements, this is not guaranteed and hence the results may not be in
document order. This is a limitation that may be fixed in future releases.
Collection Index An XPath expression can also access a particular index of a
collection For example, "/PurchaseOrder/Item[1]/Part" is rewritten to
extract out the first Item of the collection and then access the Part attribute within
that.
If the collection has been stored as a VARRAY, then this operation retrieves the
nodes in the same order as present in the original document. If the mapping of the
collection is to a nested table, then the order is undetermined. If the VARRAY is
stored as an Ordered Collection Table (OCT) , (the default for the tables created by
the schema compiler, if storeVarrayAsTable="true" is set), then this collection
index access is optimized to use the IOT index present on the VARRAY.
Non-Satisfiable XPath Expressions An XPath expression can contain references to
nodes that cannot be present in the input document. Such parts of the expression
map to SQL NULLs during rewrite. For example the XPath expression:
"/PurchaseOrder/ShipAddress" cannot be satisified by any instance
document conforming to the PO.xsd XML schema, since the XML schema does not
allow for ShipAddress elements under PurchaseOrder. Hence this expression
would map to a SQL NULL literal.
Namespace Handling Namespaces are handled in the same way as the function-based
evaluation. For schema based documents, if the function (like existsNode() or
extract()) does not specify any namespace parameter, then the target namespace
of the schema is used as the default namespace for the XPath expression.
Example 532 Handling Namespaces
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;
5-62
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.
Example 533 Date Format Conversions
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.
Table 512 XPath Mapping for existsNode() with Document Ordering Preserved
XPath Expression
Maps to
/PurchaseOrder
/PurchaseOrder/@PurchaseDate
/PurchaseOrder/PONum
/PurchaseOrder[PONum = 2100]
/PurchaseOrder[PONum =
2100]/@PurchaseDate
/PurchaseOrder/PONum/text()
/PurchaseOrder/Item
/PurchaseOrder/Item/Part
/PurchaseOrder/Item/Part/text()
Using the preceding mapping, a query which checks whether the purchaseorder
with number 2100 contains a part with price greater than 2000:
SELECT count(*)
FROM mypos p
WHERE EXISTSNODE(value(p),/PurchaseOrder[PONum=1001 and Item/Price > 2000])=
1;
would become:
SELECT count(*)
5-64
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 513 shows the
mapping of existsNode() in the absence of the SYS_XDBPD$ attribute.
Maps to
/PurchaseOrder
/PurchaseOrder/@PurchaseDate
/PurchaseOrder/PONum
/PurchaseOrder[PONum = 2100]
/PurchaseOrder[PONum =
2100]/@PurchaseOrderDate
/PurchaseOrder/PONum/text()
Table 513 XPath Mapping for existsNode Without Document Ordering (Cont.)
XPath Expression
Maps to
/PurchaseOrder/Item
/PurchaseOrder/Item/Part
/PurchaseOrder/Item/Part/text()
5-66
XPath Expression
Maps to
/PurchaseOrder
/PurchaseOrder/@PurchaseDate
XMLData."PurchaseDate"
/PurchaseOrder/PONum
XMLData."PONum"
/PurchaseOrder[PONum = 2100]
Maps to
/PurchaseOrder[PONum =
2100]/@PurchaseDate
(SELECT x.XMLData."PurchaseDate")
FROM Dual
WHERE x."PONum" = 2100)
/PurchaseOrder/PONum/text()
XMLData."PONum"
/PurchaseOrder/Item
/PurchaseOrder/Item/Part
/PurchaseOrder/Item/Part/text()
would become:
SELECT p.XMLData."PONum"
FROM mypos p
WHERE p.XMLData."PONum" = 1001;
Since it gets rewritten to simple scalar columns, indexes if any, on the PONum
attribute may be used to satisfy the query.
Creating Indexes ExtractValue can be used in index expressions. If the expression
gets rewritten into scalar columns, then the index is turned into a B*Tree index
instead of a function-based index.
Example 536 Creating Indexes with extract
For example:
create index my_po_index on mypos x
(Extract(value(x),/PurchaseOrder/PONum/text()).getnumberval());
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;
with an empty alias string "" to indicate that you create a XML
instance with only text values. This is shown for illustration only.
Table 515 XPath Mapping for extract() with Document Ordering Preserved
XPath
Maps to
/PurchaseOrder
XMLForest(XMLData as "PurchaseOrder")
/PurchaseOrder/@PurchaseDate
/PurchaseOrder/PONum
/PurchaseOrder[PONum = 2100]
/PurchaseOrder[PONum = 2100]/@PurchaseDate
5-68
Table 515 XPath Mapping for extract() with Document Ordering Preserved (Cont.)
XPath
Maps to
/PurchaseOrder/PONum/text()
XMLElement("", XMLData.PONum)
/PurchaseOrder/Item
/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()
Example 537 XPath Mapping for extract() with Document Ordering Preserved
Using the mapping in Table 515, a query that extracts the PONum element where
the purchaseorder contains a part with price greater than 2000:
SELECT Extract(value(p),/PurchaseOrder[Item/Part > 2000]/PONum)
FROM po_tab p;
would become:
SELECT (SELECT CASE WHEN Check_Node_Exists(p.XMLData.SYS_XDBPD$, PONum) = 1
THEN XMLElement("PONum", p.XMLData."PONum")
ELSE NULL END)
FROM DUAL
WHERE EXISTS( SELECT NULL
FROM TABLE ( XMLData."Item") p
WHERE p."Part" > 2000)
)
FROM po_tab p;
Table 516 XPath Mapping for extract() Without Document Ordering Preserved
XPath
Equivalent to
/PurchaseOrder
XMLForest(XMLData AS "PurchaseOrder")
/PurchaseOrder/@PurchaseDate
XMLForest(XMLData."PurchaseDate" AS "")
/PurchaseOrder/PONum
XMLForest(XMLData."PONum" AS "PONum")
/PurchaseOrder[PONum = 2100]
/PurchaseOrder[PONum =
2100]/@PurchaseDate
/PurchaseOrder/PONum/text()
XMLForest(XMLData.PONum AS "")
/PurchaseOrder/Item
/PurchaseOrder/Item/Part/text()
5-70
The XMLType column must have been stored object relationally using Oracle
XML DBs XML schema mapping.
The XPath expressions must not involve any predicates or collection traversals.
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.
5-72
An XML schema that includes another xml schema cannot be created if the included
xml schema does not exist.
begin dbms_xmlschema.registerSchema(xm40.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:my="xm40"
targetNamespace="xm40">
<include schemaLocation="xm40a.xsd"/>
<!-- Define a global complextype here -->
<complexType name="Company">
<sequence>
<element name="Name" type="string"/>
<element name="Address" type="string"/>
</sequence>
</complexType>
<!-- Define a global element depending on included schema -->
<element name="Emp" type="my:Employee"/>
</schema>,
true, true, false, true); end;
/
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;
/
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.
The second operation automatically compiles s1.xsd and makes both XML
schemas valid.
See Figure 58. The preceding example is illustrated in the lower half of the figure.
5-74
XML schema 1, S1
XML schema 2, S2
References
S3
S1
References
XML schema 3, S3
References
S2
OR
XML schema 1, S1
References
XML schema 2, S2
References
S2
S1
5-76
6
Transforming and Validating XMLType Data
This chapter describes the SQL functions and XMLType APIs for transforming
XMLType data using XSLT stylesheets. It also explains the various functions and
APIs available for validating the XMLType instance against an XML schema. It
contains the following sections:
XMLTransform() Examples
XMLTransform() Examples
XMLTRANSFORM
XMLType_instance
XMLType_instance
XMLtransform()
transformed XMLType
(HTML, XML, ...)
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">
XMLTransform() Examples
<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>
XMLTransform() Examples
</schema>,
TRUE, TRUE, FALSE);
end;
/
-- create table to hold XML instance documents
DROP TABLE po_tab;
CREATE TABLE po_tab (id number, xmlcol xmltype)
XMLTYPE COLUMN xmlcol
XMLSCHEMA "http://www.example.com/schemas/ipo.xsd"
ELEMENT "purchaseOrder";
INSERT INTO po_tab VALUES(1, xmltype(
<?xml version="1.0"?>
<ipo:purchaseOrder
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ipo="http://www.example.com/IPO"
xsi:schemaLocation="http://www.example.com/IPO
http://www.example.com/schemas/ipo.xsd"
orderDate="1999-12-01">
<shipTo xsi:type="ipo:Address">
<name>Helen Zoe</name>
<street>121 Broadway</street>
<city>Cardiff</city>
<state>Wales</state>
<country>UK</country>
<zip>CF2 1QJ</zip>
</shipTo>
<billTo xsi:type="ipo:Address">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>CA</state>
<country>US</country>
<zip>95819</zip>
</billTo>
<items>
<item partNum="833-AA">
<productName>Lapis necklace</productName>
<quantity>1</quantity>
<USPrice>99.95</USPrice>
<ipo:comment>Want this for the holidays!</ipo:comment>
<shipDate>1999-12-05</shipDate>
</item>
</items>
XMLTransform() Examples
</ipo:purchaseOrder>));
XMLTransform() Examples
FROM po_tab x;
-------------------------
This example illustrates the use of a stored stylesheet to transform XMLType instances.
Unlike the previous example, this example uses a scalar subquery to retrieve the stored
stylesheet:
SELECT XMLTransform(x.xmlcol,
(select stylesheet from stylesheet_tab where id = 1)).getStringVal()
AS result
FROM po_tab x;
This example describes how you can transform XMLType instances using a transient
stylesheet:
SELECT x.xmlcol.transform(xmltype(
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*">
<td>
<xsl:choose>
<xsl:when test="count(child::*) > 1">
<xsl:call-template name="nested"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="name(.)"/>:<xsl:value-of select="text()"/>
</xsl:otherwise>
</xsl:choose>
</td>
</xsl:template>
<xsl:template match="*" name="nested" priority="-1" mode="nested2">
<b>
<!-- xsl:value-of select="count(child::*)"/ -->
<xsl:choose>
<xsl:when test="count(child::*) > 1">
<xsl:value-of select="name(.)"/>:<xsl:apply-templates mode="nested2"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="name(.)"/>:<xsl:value-of select="text()"/>
</xsl:otherwise>
</xsl:choose>
</b>
</xsl:template>
</xsl:stylesheet>
)).getStringVal()
FROM po_tab x;
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 instances 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:
schemaValidate
schemaValidate is a member procedure. It validates the XML instance against its
XML schema if it has not already been done. For non-schema-based documents an
error is raised. If validation fails an error is raised otherwise, the documents status
is changed to VALIDATED.
Syntax
MEMBER PROCEDURE schemaValidate
isSchemaValidated()
isSchemaValidated() is a member function. It returns the validation status of
the XMLType instance and tells if a schema-based instance has been actually
validated against its schema.It returns 1 if the instance has been validated against
the schema, 0 otherwise.
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 instances own
schema. If the validation fails, exceptions are thrown with the reason why the
validation has failed.
Syntax
member function isSchemaValid(schurl IN VARCHAR2 := NULL, elem IN VARCHAR2 :=
NULL) return NUMBER deterministic
Parameters:
schurl - The URL of the XML Schema against which to check conformance.
elem - Element of a 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.
6-10
The following PL/SQL example validates an XML instance against XML schema
PO.xsd:
declare
xmldoc xmltype;
begin
-- populate xmldoc (for example, by fetching from table)
-- validate against XML schema
xmldoc.isSchemaValid('http://www.oracle.com/PO.xsd');
if xmldoc.isSchemaValid = 1 then -else -end if;
end;
Verify that the XMLType instance conforms to the specified XML schema
Ensure that the incoming XML documents are valid by using CHECK
constraints
6-11
6-12
7
Searching XML Data with Oracle Text
This chapter explains the use of Oracle Text functionality in indexing and querying
XML data. It contains the following sections:
Introducing SECTION_GROUPS
XMLType Indexing
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.
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 :
http://otn.oracle.com/products/text
All XML data here is represented using US-ASCII, a 7 bit character set.
Issues about whether a character such as "*" is treated as white space or as part
of a word are not included.
Storage characteristics of the Oracle schema object that implement the Oracle
Text index are not considered.
They focus on the SECTION GROUP parameter in the CREATE INDEX or
ALTER INDEX statement. Other parameter types available for CREATE INDEX
User CTXSYS
User CTXSYS is created at install time. Administer Oracle Text users as this user.
User CTXSYS has the following privileges:
Call procedures in the CTX_ADM PL/SQL package to start servers and set
system-parameters
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:
CONTAINS Syntax
Here is the CONTAINS syntax:
...WHERE CONTAINS([schema.]column,text_query VARCHAR2,[label NUMBER])
where:
Table 71 CONTAINS Operator: Syntax Description
Syntax
Description
[schema.] column
text_query
label
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.
Example 71 Using a Simple SELECT Statement with CONTAINS
The following example illustrates how the CONTAINS operator is used in a SELECT
statement:
SELECT id FROM my_table
WHERE
CONTAINS (my_column, receipts) > 0
The receipts parameter of the CONTAINS operator is called the Text Query
Expression.
Note: The SQL statement with the CONTAINS operator requires an
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.
Introducing SECTION_GROUPS
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
Developers 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'
Introducing SECTION_GROUPS
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'
Regular queries on attribute text will not work unless qualified in a WITHIN
clause. Using the following XML document:
<book title="Tale of Two Cities">It was the best of times.</book>
Introducing SECTION_GROUPS
querying on Tale will not work unless qualified with WITHIN title@book.
Phrases ignore attribute text. For example, if the original document looked like:
....Now is the time for all good <word type="noun"> men </word> to come to
the aid......
The search would result in a regular querys, good men, and ignore the
intervening attribute text.
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]
7-10
Introducing SECTION_GROUPS
|
|
|
|
|
...
add
add
add
add
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:
You can combine and nest WITHIN clauses. For finer grained searches of XML
sections, you can use WITHIN clauses inside CONTAINS select statements.
You cannot embed the WITHIN clause in a phrase. For example, you cannot
write: term1 WITHIN section term2
You cannot combine WITHIN with expansion operators, such as $ ! and *.
Since WITHIN is a reserved word, you must escape the word with braces to
search on it.
See Also: Oracle Text Reference
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.
7-12
Syntax
Description
Case-sensitivity
Top-Level Tag
Searching
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState>VIRGINIA</AddressState>
</Address> ... </Legal>
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature
Syntax
Description
where contains(text,'Quijote
INPATH(//title)') > 0;
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState> VIRGINIA </AddressState>...
</Legal>
virginia INPATH
(//CourtInformation/Location)
for example:
select id from library_catalog where
contains(text,'virginia
INPATH(order/item)') > 0;
7-14
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature
Syntax
Description
Finds all documents where virginia appears in a B
element which is a grandchild of an A element. For
instance, <A><D><B>virginia</B></D></A>.
The intermediate element does not need to be an
indexed XML tag. For example:
<?xml version="1.0" standalone="yes"?>
<!-- <?xml-stylesheet type="text/xsl"
href="./xsl/vacourtfiling(html).xsl"?> -->
<Legal>
<CourtFiling>
<Filing ID="f001" FilingType="Civil">
<LeadDocument>
<CaseCaption>
<CourtInformation>
<Location>
<Address>
<AddressState>VIRGINIA</AddressState>...
</Legal>
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature
Syntax
Description
Multi-level Wildcard
Searching
'virginia INPATH
(Legal/*/Filing/*/*/CourtInformation)'
Attribute Searching
virginia INPATH(A/@B)
7-16
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature
Syntax
Description
Finds all documents where virginia appears in an
A element which has a B element as a direct child.
Table 72 Path Searching XML Documents Using the INPATH Operator (Cont.)
Path Search Feature
Syntax
Description
Attribute Value
Testing
Numeric Equality
Conjunctive Testing
7-18
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.
existsNode() in XMLType.
Only use the HASPATH operator when your index has been created with the PATH_
SECTION_GROUP. The syntax for the HASPATH operator is:
finds and returns a score of 100 only for the first document, and not the second.
7-20
Create a section preference group. Before you create a section group and
Oracle text index you must first determine the role you will need and grant the
appropriate privilege. See "Oracle Text Users and Roles" on page 7-5, and grant
the appropriate privilege.
After creating and preparing your data, you are ready to perform the next step.
See "Step 1. Create a Section Group Preference" on page 7-21.
2.
3.
Create an Oracle Text index based on the section group you created. Using the
section preference created, you then create an Oracle Text index. See Building a
Query Application with Oracle Text.
4.
Build your query application using the CONTAINS operator. Now you can
finish building your query application. See "Building a Query Application with
Oracle Text".
Description
XML_SECTION_GROUP
Use this group type for indexing XML documents and for defining sections in
XML documents.
AUTO_SECTION_GROUP
Use this group type to automatically create a zone section for each
start-tag/end-tag pair in an XML document. The section names derived from XML
tags are case-sensitive as in XML. Attribute sections are created automatically for
XML tags that have attributes. Attribute sections are named in the form
attribute@tag. Stop sections, empty tags, processing instructions, and comments
are not indexed. The following limitations apply to automatic section groups:
PATH_SECTION_GROUP
You cannot add zone, field or special sections to an automatic section group.
Automatic sectioning does not index XML document types (root elements.)
However, you can define stop-sections with document type.
The length of the indexed tags including prefix and namespace cannot exceed
64 characters. Tags longer than this are not indexed.
Use this group type to index XML documents. Behaves like the AUTO_SECTION_
GROUP. With this section group you can do path searching with the INPATH and
HASPATH operators. Queries are case-sensitive for tag and attribute names.
How is PATH_SECTION_GROUP Similar to AUTO_SECTION_GROUP?
Documents are assumed to be XML, Every tag and every attribute is indexed by
default, Stop sections can be added to prevent certain tags from being indexed,
Only stop sections can be added -- ZONE, FIELD, and SPECIAL sections cannot
be added, When indexing XML document collections, you do not need to
explicitly define sections as Oracle automatically does this for you.
How Does PATH_SECTION_GROUP Differ From AUTO_SECTION_GROUP?
Path Searching is allowed at query time (see "Case Study: Searching XML-Based
Conference Proceedings" and "You can use INPATH operator to perform path
searching in XML documents. Table 72 summarizes the ways you can use the
INPATH operator for path searching." on page 7-12) with the new INPATH and
HASPATH operators, Tag and attribute names are case-sensitive in queries.
7-22
XML_section_...
AUTO_section_...
PATH_section_...
--
Yes
--
--
--
Yes
--
Fastest
Fastest
Index size
Smallest
Other features
Mappings can be
defined so that tags in
one or different DTDs
can be mapped to one
section. Good for DTD
evolution and data
aggregation.
Simplest. No need to
define mapping, add_
stop_section can be
used to ignore some
sections.
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.
Add_Zone_Section
Add_Attr_Section
Add_Field_Section
Add_Special_Section
Add_Stop_Section
7-24
where my_tag implies opening with <my_tag> and closing with </my_tag>.
add_zone_section Guidelines
add_zone_section guidelines are listed here:
where my_tag implies opening with <my_tag> and closing with </my_tag>.
Add_Attr_Section Guidelines
Add_Attr_Section guidelines are listed here:
Is case-insensitive.
The tag specifies the name of the attribute in tag@attr format. This is case-sensitive.
Note: In the ADD_ATTR_SECTION procedure, you can have many
tags all represented by the same section name at query time.
Explained in another way, the names used as the arguments of the
keyword WITHIN can be different from the actual XML tag names.
That is many tags can be mapped to the same name at query time.
This feature enhances query usability.
Add_Field_Section Guidelines
Add_Field_Section guidelines are listed here:
7-26
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.
page 7-29.
7-28
See Also:
The more sections you add to your index, the longer your search will take.*/
Useful for defining attributes in XML documents as sections. This allows*/
you to search XML attribute text using the WITHIN operator.*/
The section name:
** Is used for WITHIN queries on the attribute text.
** Cannot contain the colon (:) or dot (.) characters.
** Must be unique within group_name.
** Is case-insensitive.
** Can be no more than 64 bytes.
** The tag specifies the name of the attribute in tag@attr format. This is
case-sensitive. */
/* Names used as arguments of the keyword WITHIN can be different from the
actual XML tag names. Many tags can be mapped to the same name at query
time.*/
/* Call CTX_DDL.Add_Zone_Section for each tag in your XML document that you need
to search on. */
EXEC ctx_ddl.add_zone_section('myxmlgroup', 'mybooksec', 'mydocname(book)');
CREATE INDEX my_index ON my_table ( my_column )
INDEXTYPE IS ctxsys.context
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.
Note: When you use the AUTO_SECTION_GROUP to index XML
documents, the system automatically creates attribute sections and
names them in the form attribute@tag.
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'
7-30
2.
3.
4.
preference_name =>
attribute_name =>
attribute_value =>
);
ctx_ddl.set_attribute
(
preference_name =>
attribute_name =>
attribute_value =>
end;
/
'my_basic_lexer',
'index_text',
'true'
'my_basic_lexer',
'index_themes',
'false');
7-32
Consider an XML file that defines the BOOK tag with a TITLE attribute as follows:
<BOOK TITLE="Tale of Two Cities">
It was the best of times. </BOOK>
<Author="Charles Dickens">
Born in England in the town, Stratford_Upon_Avon </Author>
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.
XMLType Indexing
The Oracle9i datatype for storing XML, XMLType, is a core database feature.
7-34
XMLType Indexing
(9.0.1).
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.
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.
XMLType Indexing
7-36
INDEXTYPE IS ctxsys.context;
ALTER SESSION SET query_rewrite_enabled = true;
ALTER SESSION SET query_rewrite_integrity = trusted;
SELECT a.doc.getclobval() FROM xtest a
WHERE CONTAINS (doc, 'simple INPATH(A)')>0;
For example:
CREATE TABLE table uri_tab ( url sys.httpuritype);
INSERT INTO uri_tab VALUES
(sys.httpuritype.createUri('http://www.oracle.com'));
CREATE INDEX urlx ON uri_tab(url) INDEXTYPE IS ctxsys.context;
SELECT url FROM uri_tab WHERE CONTAINS(url, Oracle)>0;
Table 75 lists system parameters used for default preference names for Oracle Text
indexing, when the column type is URIType:
Table 75 riType Column Default Preference Names for Oracle Text Indexing
URIType Column
DATASTORE
DEFAULT_DATASTORE
FILTER
DEFAULT_FILTER_TEXT
SECTION GROUP
DEFAULT_SECTION_HTML
LEXER
DEFAULT_LEXER
STOPLIST
DEFAULT_STOPLIST
WORDLIST
DEFAULT_WORDLIST
STORAGE
DEFAULT_STORAGE
CONTAINS()
existsNode()
XPath Conformance
--
--
Predicate Support
--
--
String equality
Numerical equality
Range Predicates
XPath functions
Spaces
Namespaces
Entity handling
Parent-ancestor and
sibling axes
7-38
CONTAINS()
existsNode()
Attribute searching
under wildcards. For
example, */@A or ../
Synchronous
--
--
DML
CTXXPath = N
Other indexes = Y
N
In INPATH() -> Y
ctxsys.context
ctxsys.ctxxpath
Query rewrites
Y, if XML schema-based
and stored
object-relationally
Functional indexes
--
--
Query
About
Highlighting
Limited XPath
searching.
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:
7-40
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>
Find books containing a chapter whose body contains the specified text query
string:
select * from xmltab x where
existsNode(value(x), '/book/chapter[ora:contains(body,"dog OR cat")>0]',
'xmlns:ora="http://xmlns.oracle.com/xdb"') = 1;
Example 713 Using ora:contains and extract() to Find a Text Query String
Extract chapters whose body contains the 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;
page 7-42.
7-42
Description
CREATE_POLICY
Defines a policy.
Arguments:
policy_name - the name for the new policy
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
Arguments:
policy_name - the name for the policy
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;
7-44
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:
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]
For example:
CREATE INDEX xml_idx ON xml_tab(col_xml) indextype is ctxsys.CTXXPATH;
7-46
or
CREATE INDEX xml_idx ON xml_tab(col_xml) indextype is ctxsys.CTXXPATH
PARAMETERS(storage my_storage memory 40M);
For example:
begin
ctx_ddl.create_preference(mystore, BASIC_STORAGE);
ctx_ddl.set_attribute(mystore, I_TABLE_CLAUSE,
tablespace foo storage (initial
ctx_ddl.set_attribute(mystore, K_TABLE_CLAUSE,
tablespace foo storage (initial
ctx_ddl.set_attribute(mystore, R_TABLE_CLAUSE,
tablespace foo storage (initial
ctx_ddl.set_attribute(mystore, N_TABLE_CLAUSE,
tablespace foo storage (initial
ctx_ddl.set_attribute(mystore, I_INDEX_CLAUSE,
tablespace foo storage (initial
end;
1K));
1K));
1K));
1K));
1K));
For example:
exec ctx_ddl.sync_index(xml_idx);
To optimize the CTXXPATH index, you can use the OPTIMIZE_INDEX() procedure
provided in the CTX_DDL package. For example:
exec ctx_ddl.optimize_index(xml_idx, FAST);
or
exec ctx_ddl.optmize_index(xml_idx, FULL);
See Also:
The Cost Based Optimizer decides it is too expensive to use CTXXPATH index as
primary filter.
The XPath expression cannot be handled by CTXXPATH index. Here are a list of
XPath constructs CTXXPATH index cannot handle:
XPATH functions.
Numerical equality.
Arithmetic operators.
Union operator |
Existence of attribute
7-48
predicate following . or *.
For the Optimizer to better estimate the costs and selectivities for the
existsNode() function, you must gather statistics on CTXXPATH index by using
ANALYZE command or DBMS_STATS package. You can analyze the index and
compute the statistics using the ANALYZE command as follows:
ANALYZE INDEX myPathIndex COMPUTE STATISTICS;
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.
7-50
<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.
7-52
Regular queries on attribute text do not hit the document unless qualified in a
within clause. Assume you have an XML document as follows:
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.
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>
7-54
AUTO_SECTION_GROUP
BASIC_SECTION_GROUP
HTML_SECTION_GROUP
NEWS_SECTION_GROUP
NULL_SECTION_GROUP
XML_SECTION_GROUP
<<==
<<==
...
Describe ctx_object_attributes
SELECT oat_attribute FROM ctx_object_attributes
WHERE oat_object = 'XML_SECTION_GROUP';
http://otn.oracle.com/products/text
7-56
For example, select the authors only from the XML document:
SELECT p.papers.extract('/paper/authors/text()').getStringVal()
FROM Proceedings p;
You can use the Oracle Text CONTAINS() operator to search for content in a text or
XML document. For example, to search for papers that contain Dynamic in the
title you can use:
SELECT tk FROM Proceedings
WHERE CONTAINS(papers,'Dynamic INPATH(paper/title)')>0
Using the CONTAINS() operator Oracle9i returns the columns selected. For an XML
document it returns the entire document. To extract fragments of XML, you can
combine the extract() function to manipulate the XML. For example, select the
authors of papers that contain Dynamic in the title:
SELECT p.papers.extract('/paper/authors/text()').getStringVal()
FROM Proceedings p
WHERE CONTAINS(papers,'Dynamic INPATH(paper/title)')>0
You can use all the functionality of an Oracle Text query for the content search. The
following example selects the authors of papers containing Dynamic or Edge or
Libraries in the title:
SELECT p.papers.extract('/paper/authors/text()').getStringVal()
FROM Proceedings p
WHERE CONTAINS(papers,'Dynamic or Edge or Libraries INPATH(paper/title)')>0
Traditional databases allow searching of XML content or structure, but not both at
the same time. Oracle provides unique features that enable querying of both XML
content and structure at the same time.
Figure 71 illustrates entering the search for Libraries in the structure of the
Conference Proceedings documents. You can search for Libraries within Authors,
abstract, title, company, or track. In this example, you are searching for the term
Libraries in the abstracts only. Since it is an XML document your are searching,
you can even select which fragment of the XML document you want to display.
This example only displays the title of the paper.
Figure 72 shows the search results.
For the .jsp code to build this look-up application, see "Searching Conference
Proceedings Example: jsp" on page 7-60.
7-58
See Also:
http://otn.oracle.com/products/text
Figure 71 Using Oracle Text to Search for Libraries in the Conference Proceedings Abstracts
7-60
<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")+")";
String tagValue = request.getParameter("tagvalue");
String sectionValue = request.getParameter("section");
// select p.papers.extract('/paper/authors').getStringVal()
// from oowpapers p
7-62
<%
<center>
<table border="0">
<tr bgcolor="#6699CC">
<th><%= sectionValue %></th>
</tr>
} %>
<tr bgcolor="#<%= color %>">
<td> <%= myDesc %></td>
</tr>
<%
if (color.compareTo("ffffff") == 0)
color = "eeeeee";
else
color = "ffffff";
}
} catch (SQLException e) {
%>
<b>Error: </b> <%= e %><p>
<%
} finally {
if (conn != null) conn.close();
if (stmt != null) stmt.close();
if (rset != null) rset.close();
}
%>
</table>
</center>
</body></html>
<%
}
%>
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
7-64
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)
7-66
<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.
custordnumber
product_dsc
ship_status
7-68
1.
2.
Concatenate your fields and store them in an extra CLOB field in one of your
tables. Then, create the index on the CLOB field. If you're using Oracle8i release
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:
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.
7-70
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.
7-72
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.
3.
4.
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
7-74
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');
...
We are looking for the subject PA with relevance = 100
Only Story_seq_num = 561107 should be returned
7-76
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/>
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>...
7-78
Part III
Using XMLType APIs to Manipulate XML
Data
Part III of this manual introduces you to ways you can use Oracle XML DB
XMLType Pl/SQL and Java APIs to access and manipulate XML data. Part III
contains the following chapters:
8
PL/SQL API for XMLType
This chapter describes the use of the APIs for XMLType in PL/SQL. It contains the
following sections:
The read-from and write-to files must be on the server file system.
Differences Between PL/SQL API for XMLType and XDK for PL/SQL
This section explains differences between PL/SQL APIs native to Oracle XML DB
and PL/SQL APIs available in XML Developers Kits (XDK).
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.
Note: Oracle XML DB APIs are natively integrated in Oracle9i
on page 8-5
See Also:
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/>.
What is a DOM Parser? An embedded DOM parser accepts an XML-formatted
document and constructs an in-memory DOM tree based on the documents
structure. It then checks whether or not the document is well-formed and optionally
whether it complies with a specific Document Type Definition (DTD). A DOM
parser also provides methods for traversing the DOM tree and return data from it.
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 1 (9.0.1), the XDK for PL/SQL implemented DOM Level 1.0
and parts of DOM Level 2.0.
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.
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.
Tree-based. The DOM is the primary generic tree-based API for XML.
Event-based. SAX (Simple API for XML) is the primary generic event-based
programming interface between an XML parser and an XML application.
The DOM works by creating objects. These objects have child objects and
properties, and the child objects have child objects and properties, and so on.
Objects are referenced either by moving down the object hierarchy or by explicitly
giving an HTML element an ID attribute. For example:
<img src="employee_jdoe.gif" ID="0123jdoe">
Reordering elements
Renaming elements
The types and methods described in this document are made available by the
PL/SQL package DBMS_XMLPARSER.
DTD validation follows the same rules that are exposed for the XML Parser
available through the XDK in Oracle9i Release 1(9.0.1) with the only difference
being that the validation occurs when the object document is manifested. For
example, if lazy manifestation is used, the document will be validated when it is
used.
Oracle XML DB extends the Oracle XML development platform beyond SQL
support for XML text and storage and retrieval of XML data. In this release, you can
operate on XMLType instances using the DOM in PL/SQL and Java. Thus, you can
directly manipulate individual XML elements and data using the language best
suited for your application or plug-in.
This release has updated the PL/SQL DOM API to exploit a C-based representation
of XML in the server and to operate on XML schema-based XML instances. Oracle
XML DB PL/SQL DOM API for XMLType and Java DOM API for XMLType
comply with the W3C DOM Recommendations to define and implement structured
storage of XML in relational or object-relational columns and as in-memory
instances of XMLType. See "Using PL/SQL DOM API for XMLType: Preparing XML
Data" on page 8-9, for a description of W3C DOM Recommendations.
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"
Simple API for XML (SAX) interface processing. SAX is an XML standard
interface provided by XML parsers and used by procedural and event-based
applications.
DOM interface processing for structural and recursive object-based processing.
Oracle XDKs contain the basic building blocks for creating applications that run on
the client, in a browser or plug-in, for example, for reading, manipulating,
transforming and viewing XML documents. To provide a broad variety of
deployment options, Oracle XDKs are also available for Java, Java beans, C, C++,
and PL/SQL. Unlike many shareware and trial XML components, Oracle XDKs are
fully supported and come with a commercial redistribution license.
Oracle XDK for Java consists of these components:
XML Parsers: Supports Java, C, C++ and PL/SQL, the components create and
parse XML using industry standard DOM and SAX interfaces.
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.
See Also: Oracle9i XML Developers Kits Guide - XDK
Create a standard XML schema if you do not already use one. Annotate the
XML schema with definitions for the SQL objects defined in your relational or
object-relational database.
2.
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.
8-10
Comments
Namespace declaration
Prefix information
Note: In this document, the SYS_XDBPD$ attribute has been
omitted in many examples for simplicity. However, the attribute is
always present in all SQL object types generated by the
schema-registration process.
8-11
8-12
Group/Method
Description
Node methods
--
isNull()
makeAttr()
makeCDataSection()
makeCharacterData()
makeComment()
makeDocumentFragment()
makeDocumentType()
makeElement()
makeEntity()
makeEntityReference()
makeNotation()
makeProcessingInstruction()
makeText()
makeDocument()
writeToFile()
writeToBuffer()
writeToClob()
getNodeName()
getNodeValue()
setNodeValue()
getNodeType()
getParentNode()
getChildNodes()
getFirstChild()
Description
getLastChild()
getPreviousSibling()
getNextSibling()
getAttributes()
getOwnerDocument()
insertBefore()
replaceChild()
removeChild()
appendChild()
hasChildNodes()
cloneNode()
--
isNull()
getNamedItem()
setNamedItem()
removeNamedItem()
item()
getLength()
--
isNull()
item()
getLength()
Attr methods
--
isNull()
makeNode()
getQualifiedName()
getNamespace()
8-13
8-14
Group/Method
Description
getLocalName()
getExpandedName()
getName()
getSpecifiied()
getValue()
setValue()
--
isNull()isNull()
makeNode()makeNode()
--
isNull()
makeNode()
getData()
setData()
getLength()
substringData()
appendData()
insertData()
deleteData()
replaceData()
Comment methods
--
isNull()
makeNode()
--
isNull()
hasFeature()
--
Description
isNull()
makeNode()
--
isNull()
makeNode()
findEntity()
findNotation()
getPublicId()
getSystemId()
writeExternalDTDToFile()
writeExternalDTDToBuffer()
writeExternalDTDToClob()
getName()
getEntities()
getNotations()
Element methods
--
isNull()
makeNode()
getQualifiedName()
getNamespace()
getLocalName()
getExpandedName()
getChildrenByTagName()
getElementsByTagName()
resolveNamespacePrefix()
getTagName()
8-15
8-16
Group/Method
Description
getAttribute()
setAttribute()
removeAttribute()
getAttributeNode()
setAttributeNode()
removeAttributeNode()
normalize()
Entity methods
--
isNull()
makeNode()
getPublicId()
getSystemId()
getNotationName()
--
isNull()
makeNode()
Notation methods
--
isNull()
makeNode()
getPublicId()
getSystemId()
--
isNull()
makeNode()
getData()
getTarget()
setData()
Description
Text methods
--
isNull()
makeNode()
splitText()
Document methods
--
isNull()
makeNode()
newDOMDocument()
freeDocument()
getVersion()
setVersion()
getCharset()
setCharset()
getStandalone()
setStandalone()
writeToFile()
writeToBuffer()
writeToClob()
writeExternalDTDToFile()
writeExternalDTDToBuffer()
writeExternalDTDToClob()
getDoctype()
getImplementation()
getDocumentElement()
createElement()
createDocumentFragment()
createTextNode()
8-17
Description
createComment()
createCDATASection()
createProcessingInstruction()
createAttribute()
Creates an attribute.
createEntityReference()
getElementsByTagName()
INDEX_SIZE_ERR
DOMSTRING_SIZE_ERR
HIERARCHY_REQUEST_ERR
WRONG_DOCUMENT_ERR
INVALID_CHARACTER_ERR
NO_DATA_ALLOWED_ERR
NO_MODIFICATION_ALLOWED_ERR
NOT_FOUND_ERR
NOT_SUPPORTED_ERR
INUSE_ATTRIBUTE_ERR
8-18
ELEMENT_NODE
ATTRIBUTE_NODE
TEXT_NODE
CDATA_SECTION_NODE
ENTITY_REFERENCE_NODE
ENTITY_NODE
PROCESSING_INSTRUCTION_NODE
COMMENT_NODE
DOCUMENT_NODE
DOCUMENT_TYPE_NODE
DOCUMENT_FRAGMENT_NODE
NOTATION_NODE
Table 82 shows the node types for XML and HTML and the allowed corresponding
children node types.
Table 82 XML and HTML DOM Node Types and Corresponding Children Node Types
Node Type
Document
DocumentFragment
DocumentType
No children
EntityReference
Element
Attr
Text, EntityReference
ProcessingInstruction
No children
Comment
No children
Text
No children
8-19
Table 82 XML and HTML DOM Node Types and Corresponding Children Node Types (Cont.)
Node Type
CDATASection
No children
Entity
Notation
No children
Oracle XML DB DOM API for XMLType also specifies these interfaces:
8-20
1.
2.
3.
Use the DOM API to access and manipulate the XML data
2.
You can use the DOM API methods such as, createElement, createText,
createAttribute, and createComment, and so on, to traverse and extend
the DOM tree. See Table 81 for a full list of available methods.
3.
The results of these methods (DOMElement, DOMText, and so on) can also be
passed to makeNode to obtain the DOMNode interface.
8-21
Createxml
Select Statement
XMLType
newDOMDocument
newDOMDocument
(Empty
document)
DOMDocument
CreateElement
CreateTextNode
DOMElement
Interface
CreateAttribute
DOMText
Interface
CreateComment
DOMAttibute
Interface
...
DOMComment
Interface
makeNode
DOMNode Interface
8-22
nodelist dbms_xmldom.DOMNodelist;
buf
varchar2(2000);
begin
var := xmltype(<PERSON> <NAME> ramesh </NAME> </PERSON>);
-- Create DOMDocument handle:
doc
:= dbms_xmldom.newDOMDocument(var);
ndoc
:= dbms_xmldom.makeNode(doc);
dbms_xmldom.writetobuffer(ndoc, buf);
dbms_output.put_line(Before:||buf);
docelem := dbms_xmldom.getDocumentElement( doc );
-- Access element:
nodelist := dbms_xmldom.getElementsByTagName(docelem, NAME);
node := dbms_xmldom.item(nodelist, 0);
childnode := dbms_xmldom.getFirstChild(node);
-- Manipulate:
dbms_xmldom.setNodeValue(childnode, raj);
dbms_xmldom.writetobuffer(ndoc, buf);
dbms_output.put_line(After:||buf);
end;
/
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;
/
8-23
Table 83 lists the PL/SQL Parser API for XMLType (DBMS_XMLPARSER) methods.
8-24
parse
newParser
parse
parseBuffer
parseClob
parseDTD
parseDTDBuffer
parseDTDClob
setBaseDir
showWarnings
setErrorLog
setPreserveWhitespace
setValidationMode
8-25
getValidationMode
Argument: (p Parser)
Result: Gets validation mode
setDoctype
getDoctype
Argument: (p Parser)
Result: Gets DTD
getDocument
Argument: (p Parser)
Result: Gets DOM document
freeParser
Argument: (p Parser)
Result: Frees a Parser object
8-26
1.
2.
XML documents can then be parsed using the Parser with methods such as,
parseBuffer, parseClob, parse(URI), and so on. See Table 83 for a full
list of Parser methods.
3.
4.
To use the PL/SQL DOM API for XMLType on the parsed XML document
instance, you need to call getDocument on the Parser to obtain a
DOMDocument interface.
newParser
Parser
parseBuffer
parse (URI)
...
getDocument
DOMDocument
This example parses a simple XML document and enables DOM APIs to be used.
declare
indoc
VARCHAR2(2000);
indomdoc
dbms_xmldom.domdocument;
innode
dbms_xmldom.domnode;
myParser
dbms_xmlparser.Parser;
begin
indoc := <emp><name> Scott </name></emp>;
myParser := dbms_xmlparser.newParser;
dbms_xmlparser.parseBuffer(myParser, indoc);
indomdoc := dbms_xmlparser.getDocument(myParser);
innode
:= dbms_xmldom.makeNode(indomdoc);
-- DOM APIs can be used here
end;
/
8-27
8-28
The types and methods of PL/SQL XSLT Processor are made available by the
PL/SQL package, DBMS_XSLPROCESSOR.
(Page 1 of 2)
Method
newProcessor
processXSL
processXSL
showWarnings
setErrorLog
NewStylesheet
transformNode
selectNodes
8-29
(Page 2 of 2)
Method
selectSingleNodes
valueOf
setParam
removeParam
ResetParams
freeStylesheet
freeProcessor
Argument: (p Processor)
Result: Frees a Processor object
8-30
1.
2.
3.
Optionally, you can set parameters to the Stylesheet using the call
setParams.
4.
The XSLT processing can then be executed with the call processXSL using the
processor and Stylesheet created in Steps 1 - 3.
5.
6.
newStylesheet
Processor
Stylesheet
xmldoc
(DOMDocument)
setParams
ProcessXSL
DOMDocumentFragment Interface
makeNode
DOMNode Interface
VARCHAR2(2000);
VARCHAR2(2000);
8-31
myParser
dbms_xmlparser.Parser;
indomdoc
dbms_xmldom.domdocument;
xsltdomdoc dbms_xmldom.domdocument;
xsl
dbms_xslprocessor.stylesheet;
outdomdocf dbms_xmldom.domdocumentfragment;
outnode
dbms_xmldom.domnode;
proc
dbms_xslprocessor.processor;
buf
varchar2(2000);
begin
indoc
:= <emp><empno> 1</empno> <fname> robert </fname> <lname>
smith</lname> <sal>1000</sal> <job> engineer </job> </emp>;
xsldoc
:=
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8"/>
<!-- alphabetizes an xml tree -->
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="*|text()">
<xsl:sort select="name(.)" data-type="text" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
</xsl:stylesheet>;
myParser := dbms_xmlparser.newParser;
dbms_xmlparser.parseBuffer(myParser, indoc);
indomdoc := dbms_xmlparser.getDocument(myParser);
dbms_xmlparser.parseBuffer(myParser, xsldoc);
xsltdomdoc := dbms_xmlparser.getDocument(myParser);
xsl
proc
:= dbms_xslprocessor.newstylesheet(xsltdomdoc, );
:= dbms_xslprocessor.newProcessor;
8-32
end;
/
8-33
8-34
9
Java and Java Bean APIs for XMLType
This chapter describes how to use XMLType in Java, including fetching XMLType
data through JDBC and manipulating them using the Java Bean API.
Java Document Object Model (DOM) API for XMLType. This is a generic API
for client and server, for both XML schema-based and non- schema-based
documents. It is implemented using the Java package oracle.xdb.dom.
To access XMLType data using JDBC use the class oracle.xdb.XMLType.
Java Bean API for XMLType. This is a high performance API for the server for
XML schema-based documents. It is implemented using Java package
oracle.xdb.bean. The Java Bean API for XMLType offers:
Java beans also have the advantage of being programmer-friendly, because the
API uses the XML schema names from which the bean was generated. Java
Bean API for XMLType supports any form of XML schema.
For XML documents that do not conform to any XML schema, you can use the
Java DOM API for XMLType as it can handle any valid XML document.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
XML DB Repository hierarchy can store both XML schema-based and nonschema-based documents.
See: Chapter 17, "Oracle XML DB Resource API for Java/JNDI"
And a bean has been generated for that XML schema, an instance of the bean
class is returned.
And if no bean has been generated for that XML schema or if the XML is
non-XML schema-based, then a DOM document interface is returned.
The Java application can also call the Java DOM API for XMLType for objects for
which beans have been generated. This is because the Java Beans interface is based
on an extension to the DOM. Once the application has the object returned by
lookup(), it can call either the Java DOM API for XMLType methods or Java Beans
methods on the class to access XML data. For Java DOM API for XMLType, an
XMLDocument class, which implements the DOM interface, is returned.
For example:
Document x = (org.w3c.dom.Document)ctx.lookup("/usr/local/bkhaladk/po.xml);
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.
Example 91
The following is an example that illustrates using JDBC to query an XMLType table:
import oracle.xdb.XMLType;
...
OraclePreparedStatement stmt = (OraclePreparedStatement)
conn.prepareStatement("select e.poDoc from po_xml_tab e");
ResultSet rset = stmt.executeQuery();
OracleResultSet orset = (OracleResultSet) rset;
while(orset.next())
{
// get the XMLType
XMLType poxml = XMLType.createXML(orset.getOPAQUE(1));
// get the XMLDocument as a string...
Document podoc = (Document)poxml.getDOM();
}
You can select the XMLType data in JDBC in one of two ways:
This example shows the use of getObject to directly get the XMLType from the
ResultSet. This is the easiest way to get the XMLType from the ResultSet.
import oracle.xdb.XMLType;
...
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"select e.poDoc from po_xml_tab e");
ResultSet rset = stmt.executeQuery();
OracleResultSet orset = (OracleResultSet) rset;
while(orset.next())
{
// get the XMLType
XMLType poxml = (XMLType)orset.getObject(1);
// get the XML as a string...
String poString = poxml.getStringVal();
}
When selecting out XMLType values, JDBC describes the column as an OPAQUE
type. You can select the column type name out and compare it with XMLTYPE to
check if you are dealing with an XMLType:
import oracle.sql.*;
import oracle.jdbc.*;
...
OraclePreparedStatement stmt =
(OraclePreparedStatement) conn.prepareStatement(
"select poDoc from po_xml_tab");
OracleResultSet rset = (OracleResultSet)stmt.exuecuteQuery();
// Now, we can get the resultset metadata
OracleResultSetMetaData mdata =
(OracleResultSetMetaData)rset.getMetaData();
// Describe the column = the column type comes out as OPAQUE
// and column type name comes out as XMLTYPE
if (mdata.getColumnType(1) == OracleTypes.OPAQUE &&
mdata.getColumnTypeName(1).compareTo("SYS.XMLTYPE") == 0)
{
// we know it is an XMLtype
}
conStr = "jdbc:oracle:oci8:@";
user = "scott";
pass = "tiger";
qryStr =
x.poDoc from po_xml_tab x "+
x.poDoc.extract('/PO/PONO/text()').getNumberVal()=200";
parser.setPreserveWhitespace (true);
parser.parse(new StringReader(xmlTypeStr));
System.out.println("xmlType.getStringVal(): xml String is well-formed");
XMLDocument doc = parser.getDocument();
NodeList nl = doc.getElementsByTagName("DISCOUNT");
for(int i=0;i<nl.getLength();i++){
XMLElement discount = (XMLElement)nl.item(i);
XMLNode textNode = (XMLNode)discount.getFirstChild();
textNode.setNodeValue("10");
}
StringWriter sw = new StringWriter();
doc.print(new PrintWriter(sw));
outXML = sw.toString();
//print modified xml
System.out.println("\n===============================");
System.out.println("Updated PurchaseOrder:");
System.out.println(outXML);
System.out.println("===============================");
}
catch ( Exception e )
{
e.printStackTrace(System.out);
}
return outXML;
}
public static void main(String args[]) throws Exception
{
try{
System.out.println("qryStr="+ qryStr);
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn =
DriverManager.getConnection("jdbc:oracle:oci8:@", user, pass);
Statement s = conn.createStatement();
OraclePreparedStatement stmt;
ResultSet rset = s.executeQuery(qryStr);
OracleResultSet orset = (OracleResultSet) rset;
while(orset.next()){
//retrieve PurchaseOrder xml document from database
XMLType xt = XMLType.createXML(orset.getOPAQUE(1));
//store this PurchaseOrder in po_xml_hist table
stmt = (OraclePreparedStatement)conn.prepareStatement(
"insert into po_xml_hist values(?)");
stmt.setObject(1,xt); // bind the XMLType instance
stmt.execute();
//update "DISCOUNT" element
String newXML = updateXML(xt.getStringVal());
// create a new instance of an XMLtype from the updated value
xt = XMLType.createXML(conn,newXML);
// update PurchaseOrder xml document in database
stmt = (OraclePreparedStatement)conn.prepareStatement(
"update po_xml_tab x set x.poDoc =? where "+
"x.poDoc.extract('/PO/PONO/text()').getNumberVal()=200");
stmt.setObject(1,xt); // bind the XMLType instance
stmt.execute();
conn.commit();
System.out.println("PurchaseOrder 200 Updated!");
}
//delete PurchaseOrder 1001
s.execute("delete from po_xml x"+
"where x.xpo.extract"+
"('/PurchaseOrder/PONO/text()').getNumberVal()=1001");
System.out.println("PurchaseOrder 1001 deleted!");
}
catch( Exception e )
{
e.printStackTrace(System.out);
9-10
}
}
}
----------------------- list PurchaseOrders
---------------------set long 20000
set pages 100
select x.xpo.getClobVal()
from po_xml x;
9-11
<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
import
import
import
java.sql.*;
java.io.*;
java.net.*;
java.util.*;
import
import
import
import
oracle.xml.parser.v2.*;
oracle.xml.parser.schema.*;
org.xml.sax.*;
org.w3c.dom.*;
import
import
import
import
oracle.xml.sql.dataset.*;
oracle.xml.sql.query.*;
oracle.xml.sql.docgen.*;
oracle.xml.sql.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;
9-12
import oracle.xdb.XMLType;
public class tkxmtpk1
{
static
static
static
static
static
String
String
String
String
String
conStr = "jdbc:oracle:oci8:@";
user = "tpjc";
pass = "tpjc";
qryStr = "select x.resume from
xslStr =
"<?xml version='1.0' ?> " +
"<xsl:stylesheet version='1.0'
999/XSL/Transform'> " +
"<xsl:template match='ROOT'> "
"<xsl:apply-templates/> " +
"</xsl:template> " +
"<xsl:template match='NAME'> "
"<html> " +
" <body> " +
"
This is Test " +
" </body> " +
"</html> " +
"</xsl:template> " +
"</xsl:stylesheet>";
t1 x where id<3";
xmlns:xsl='http://www.w3.org/1
+
9-13
System.out.println();
}
}
public static void main(String args[]) throws Exception
{
tkxmjnd1 util = new tkxmjnd1();
try{
if( args != null )
parseArg(args);
//
System.out.println("conStr=" + conStr);
System.out.println("user/pass=" + user + "/" +pass );
System.out.println("qryStr="+ qryStr);
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection(conStr, user, pass);
Statement s = conn.createStatement();
ResultSet rset = s.executeQuery(qryStr);
OracleResultSet orset = (OracleResultSet) rset;
OPAQUE xml;
while(orset.next()){
xml = orset.getOPAQUE(1);
oracle.xdb.XMLType xt = oracle.xdb.XMLType.createXML(xml);
System.out.println("Testing getDOM() ...");
Document doc = xt.getDOM();
util.printDocument(doc);
System.out.println("Testing getBytesValue() ...");
showValue(xt.getBytesValue());
System.out.println("Testing existsNode() ...");
try {
System.out.println("existsNode(/)" + xt.existsNode("/", null));
}
catch (SQLException e) {
System.out.println("Thin driver Expected exception: " + e);
}
9-14
9-15
}
catch (SQLException e) {
System.out.println("Got exception: " + e);
}
}
}
catch( Exception e )
{
e.printStackTrace(System.out);
}
}
}
XML schema-based
Non-XML schema-based
CLOB
BLOB
Object-relational.
The Java DOM API for XMLType supports deep or shallow searching in the
document to retrieve children and properties of XML objects such as name,
namespace, and so on. Conforming to the DOM 2.0 recommendation, Java DOM
API for XMLType is namespace aware.
9-16
In the format specified by the XML schema for XML schema-based documents
Example 98 Java DOM API for XMLType: Creating a DOM Object and Storing It in the
Format 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 = ? ");
// the second argument is a string
String poString = "<PO><PONO>200</PONO><PNAME>PO_2</PNAME></PO>";
XMLType poXML = XMLType.createXML(conn, poString);
Document poDOM = (Document)poXML.getDOM();
Element rootElem = poDOM.createElement("PO");
poDOM.insertBefore(poDOM, rootElem, null);
// now bind the string..
stmt.setObject(1,poXML);
stmt.execute();
9-17
JDBC/SQLJ
An XMLType instance is represented in Java by oracle.xdb.XMLType. When an
instance of XMLType is fetched using JDBC, it is automatically manifested as an
object of the provided XMLType class. Similarly, objects of this class can be bound
as values to Data Manipulation Language (DML) statements where an XMLType is
expected. The same behavior is supported in SQLJ clients.
9-18
oracle.xdb.dom.XMLDocument
org.w3c.dom.Document
oracle.xdb.dom.XMLCData
org.w3c.dom.CDataSection
oracle.xdb.dom.XMLComment
org.w3c.dom.Comment
oracle.xdb.dom.XMLPI
org.w3c.dom.ProcessingInstruction
oracle.xdb.dom.XMLText
org.w3c.dom.Text
oracle.xdb.dom.XMLEntity
org.w3c.dom.Entity
oracle.xdb.dom.DTD
org.w3c.dom.DocumentType
oracle.xdb.dom.XMLNotation
org.w3c.dom.Notation
oracle.xdb.dom.XMLNodeList
org.w3c.dom.NodeList
oracle.xdb.dom.XMLAttribute
org.w3c.dom.Attribute
oracle.xdb.dom.XMLDOMImplementation
org.w3c.dom.DOMImplementation
oracle.xdb.dom.XMLElement
org.w3c.dom.Element
oracle.xdb.dom.XMLNamedNodeMap
org.w3c.dom.NamedNodeMap
oracle.xdb.dom.XMLNode
org.w3c.dom.Node
Retrieve the XML data from the XMLType table or XMLType column in the
table. When you fetch XML data, Oracle XML DB creates a DOMDocument
instance of XMLType, parsing the document into a DOM tree. You can then
manipulate elements in the DOM tree using Java DOM API for XMLType.
2.
Use the Java DOM API for XMLType to perform operations and manipulations
on elements of the DOM tree.
3.
The Java DOM API for XMLType sends the changed XML data back to Oracle
XML DB.
Figure 91 illustrates the Java DOM API for XMLType calling sequence.
9-19
Oracle9i
Database
Oracle
XML DB
XMLType
Tables,
Columns,
Views
Oracle
XML DB
XMLType
Instance
JDBC
getDOM()
Method
Saved
back
in the
Database
XML DOM
Tree
Java DOM
API
JDBC
Use the Java Bean API for XMLType for applications that:
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.
9-20
If you have specified BeanName in the XML schema definition, then that name
is used as the class name for the XML schema.
If you have not specified BeanName in the XML schema definition, the name of
the element is used as the class name. Thus the Element name inside the
package name ensures the uniqueness of the name in the XML schema.
The bean name is always unique and is generated as the XML schema name,
appended with its number in the XML schema file. For example, if a file, emp.xsd,
contains three schemas: Emp, Def, and Manager, then:
The package name for the XML schema Emp will be Emp1.
Thus, class Emp() will be unique in package Emp1. This way Java bean names are
always unique.
First register the XML schema with Oracle XML DB. The XML Schema
registration API has a flag that enables the caller to generate a bean for the XML
schema. The flag is optional since not all XML schema users use Java Bean API
for XMLType.
9-21
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.
3.
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 93, "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.
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 92 illustrates the Java Bean API for XMLType calling sequence.
9-22
Oracle9i
Database
Oracle
XML DB
Repository
Generated
Java Bean
Java
Application
Saved
back
in the
Database
Manipulates
(bind / rebind
bean)
get / set
API Object
Processed Bean
Table 92 describes the mapping of XML schema entities to the Java bean
classes/methods.
Table 92 JavaBeans API for XMLType: Mapping of XML Schema Entities
XML Schema
Entity
JavaBeans
Classes/Methods
Attribute
get/setAttribute{attrname}
Complextype
get/set{complextype
classname}.
Scalar data
Description
Table 93 describes the mapping used by Java Bean API For XMLType between
XML schema, SQL, and Java datatypes.
Table 93 Mapping Between XML Schema, SQL, and Java DataTypes
XML Schema Data Type
SQL DataType
Boolean
boolean
boolean
9-23
Table 93 Mapping Between XML Schema, SQL, and Java DataTypes (Cont.)
XML Schema Data Type
SQL DataType
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
This example illustrates the use of Java Bean API for XMLType. Assume the
following XML schema:
<schema targetNamespace="http://www.oracle.com/tkxmsch1.xsd" version="1.0">
<element name = "Employee">
<complexType>
<sequence>
<element name = "EmployeeId" type = "positiveInteger"/>
<element name = "FirstName" type = "string"/>
<element name = "LastName" type = "string"/>
<element name = "Salary" type = "positiveInteger"/>
</sequence>
</complexType>
</element>
</schema>
The generated Java bean for this XML schema looks like this:
9-24
9-25
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
9-26
Part IV
Viewing Existing Data as XML
Part IV of this manual introduces you to ways you can view your existing data as
XML. It contains the following chapters:
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
XMLElement() Function
XMLForest() Function
XMLColAttVal() Function
XMLSEQUENCE() Function
XMLConcat() Function
XMLAgg() Function
SYS_XMLGEN() Function
SYS_XMLAGG() Function
Oracle XML DB Options for Generating XML Data From Oracle9i Database
Figure 101 illustrates the Oracle XML DB options you can use to generate XML
from Oracle9i database.
10-2
Oracle XML DB Options for Generating XML Data From Oracle9i Database
page 10-54
Oracle XML DB Options for Generating XML Data From Oracle9i Database
Figure 101 Oracle XML DB Options for Generating XML from Oracle9i Database
Oracle9i Database
Oracle XML DB
SQLX Functions
XMLElement
XMLForest
XMLColAttVal
XMLConcat
XMLAgg
SQL Functions
SYS_XMLGEN
SYS_XMLAGG
XMLSequence
PL/SQL Package
DBMS_XMLGEN
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:
10-4
XML SQL
Utility
(XSU)
XMLElement() Function
XMLElement() Function
XMLElement() function is based on the emerging SQL XML standard. It takes an
element name, an optional collection of attributes for the element, and zero or more
arguments that make up the elements content and returns an instance of type
XMLType. See Figure 102. The XML_attributes_clause is described in the following
section.
Figure 102 XMLElement() Syntax
,
NAME
XMLELEMENT
,
identifier
XML_attributes_clause
value_expr
)
XMLElement() Function
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 103.
Figure 103 XML_attributes_clause Syntax
,
AS
XMLATTRIBUTES
c_alias
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.
Example 101 XMLElement(): Generating an Element for Each Employee
The following example produces an Emp XML element for each employee, with the
employees name as its content:
SELECT e.employee_id, XMLELEMENT ( "Emp", e.fname ||' ' || e.lname ) AS "result"
FROM employees e
WHERE employee_id > 200;
------
10-6
XMLElement() Function
XMLElement() can also be nested to produce XML data with a nested structure.
Example 102 XMLElement(): Generating Nested XML
To produce an Emp element for each employee, with elements that provide the
employees name and start date:
SELECT XMLELEMENT("Emp", XMLELEMENT("name", e.fname ||' '|| e.lname),
XMLELEMENT ( "hiredate", e.hire)) AS "result"
FROM employees e
WHERE employee_id > 200 ;
This 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;
XMLElement() Function
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 ... ;
The following example illustrates the use of namespaces to create a schema based
document. Assuming that an XML schema
"http://www.oracle.com/Employee.xsd" exists and has no target namespace,
then the following query creates an XMLType instance conforming to that schema.
SELECT XMLELEMENT ( "Employee",
XMLATTRIBUTES ( http://www.w3.org/2001/XMLSchema AS "xmlns:xsi",
http://www.oracle.com/Employee.xsd AS
"xsi:nonamespaceSchemaLocation" ),
XMLForest(empno, ename, sal)) AS "result"
FROM scott.emp
WHERE deptno = 100;
10-8
XMLForest() Function
<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 104 describes the XMLForest() syntax.
XMLForest() Function
c_alias
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 106 XMLForest(): Generating Elements for Each Employee with Name
Attribute, Start Date, and Dept as Content
This example generates an Emp element for each employee, with a name attribute
and elements with the employees start date and department as the content.
SELECT XMLELEMENT("Emp", XMLATTRIBUTES ( e.fname ||' '|| e.lname AS "name" ),
XMLForest ( e.hire, e.dept AS "department")) AS "result"
FROM employees e;
You can also use XMLForest() to generate XML from user-defined types (UDTs) .
Using the same example as given in the following DBMS_XMLGEN section
(Example 1018, "DBMS_XMLGEN: Generating Complex XML" on page 10-29), you
can generate a hierarchical XML for the employee, department example as follows:
SELECT XMLForest(
XMLSEQUENCE() Function
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.
Note: Unlike in the XMLElement() case, the DEPT_T element is
missing.
<Department DEPTNO="100">
<DNAME>Sports</DNAME>
<EMPLIST>
<EMP_T EMPNO="200">
<ENAME>John</ENAME>
</EMP_T>
<EMP_T>
<ENAME>Jack</ENAME>
</EMP_T>
</EMPLIST>
</Department>
XMLSEQUENCE() Function
XMLSequence() function returns a sequence of XMLType. The function returns an
XMLSequenceType which is a VARRAY of XMLType instances. Since this function
returns a collection, it can be used in the FROM clause of SQL queries. See
Figure 105.
Figure 105 XMLSequence() Syntax
XMLType_instance
XMLSEQUENCE
fmt
sys_refcursor_instance
10-11
XMLSEQUENCE() Function
The first form inputs an XMLType instance and returns a VARRAY of top-level
nodes. This form can be used to shred XML fragments into multiple rows.
The second form takes as input a REFCURSOR argument, with an optional
instance of the XMLFormat object and returns the varray of XMLTypes
corresponding to each row of the cursor. This form can be used to construct
XMLType instances from arbitrary SQL queries. Note that in this release, this
use of XMLFormat does not support XML schemas.
Suppose you had the following XML document containing employee information:
<EMPLOYEES>
<EMP>
<EMPNO>112</EMPNO>
<EMPNAME>Joe</EMPNAME>
<SALARY>50000</SALARY>
</EMP>
<EMP>
<EMPNO>217</EMPNO>
<EMPNAME>Jane</EMPNAME>
<SALARY>60000</SALARY>
</EMP>
<EMP>
<EMPNO>412</EMPNO>7
<EMPNAME>Jack</EMPNAME>
<SALARY>40000</SALARY>
</EMP>
</EMPLOYEES>
To create a 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;
XMLSEQUENCE() Function
<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.
2.
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.
Here XMLSequence() creates an XML document for each row of the cursor
expression and returns the value as an XMLSequenceType. The XMLFormat object
can be used to influence the structure of the resulting XML documents. For
example, a call such as:
SELECT value(e).getClobVal()
FROM TABLE(XMLSequence(Cursor(SELECT * FROM emp))) e;
10-13
XMLSEQUENCE() Function
<EMPNO>968</EMPNO>
<ENAME>Jack</ENAME>
</ROW>
...
The row tag used for each row can be changed using the XMLFormat object.
Example 1010 XMLSequence(): Unnesting Collections inside XML Documents into
SQL Rows
XMLConcat() Function
<Employee empno="300"><Ename>Jack</Ename><Salary>333444</Salary></Employee>
</EmployeeList></Department>));
INSERT INTO dept_xml_tab VALUES (
xmltype(<Department deptno="200">
<DeptName>Sports</DeptName><EmployeeList>
<Employee empno="400"><Ename>Marlin</Ename><Salary>20000</Salary></Employee>
</EmployeeList></Department>));
SELECT extractvalue(value(d),/Department/@deptno) as deptno,
extractvalue(value(e),/Employee/@empno) as empno,
extractvalue(value(e),/Employee/Ename) as ename
FROM dept_xml_tab d,
TABLE(XMLSequence(extract(value(d),/Department/EmployeeList/Employee))) e;
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 106 shows the XMLConcat() syntax. XMLConcat() has two
forms:
10-15
XMLConcat() Function
elements of the varray. This form is useful to collapse lists of XMLTypes into a
single instance.
,
XMLCONCAT
XMLType_instance
The following example creates an XML element for the first and the last names and
then concatenates the result:
SELECT XMLConcat ( XMLElement ("first", e.fname), XMLElement ("last", e.lname))
AS "result"
FROM employees e ;
XMLAgg() Function
<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 107 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.
Figure 107 XMLAgg() Syntax
ORDER
XMLAGG
BY
XMLType_instance
sort_list
)
10-17
XMLAgg() Function
XMLAgg() can be used to reflect the hierarchical nature of some relationships that
exist in tables. The following example generates a department element for each
department. Within this it creates elements for all employees of the department.
Within each employee, it lists their dependents:
SELECT XMLELEMENT( "Department", XMLATTRIBUTES ( d.dname AS "name" ),
(SELECT XMLAGG(XMLELEMENT ("emp", XMLATTRIBUTES (e.ename AS name),
( SELECT XMLAGG(XMLELEMENT( "dependent",
XMLATTRIBUTES(de.name AS "name")))
FROM dependents de
WHERE de.empno = e.empno ) ))
FROM emp e
WHERE e.deptno = d.deptno) ) AS "dept_list"
FROM dept d ;
The query might produce a row containing the XMLType instance for each
department.
<Department name="Accounting">
<emp name="Smith">
<dependent name="Sara Smith"/d>
<dependent name="Joyce Smith"/>
</emp>
<emp name="Yates"/>
</Department>
<Department name="Shipping">
<emp name="Martin">
<dependent name="Alan Martin"/>
</emp>
<emp name="Oppenheimer">
<dependent name="Ellen Oppenheimer"/>
</emp>
</Department>
XMLColAttVal() Function
XMLColAttVal() Function
XMLColAttVal() function generates a forest of XML column elements containing
the value of the arguments passed in. Figure 108 shows the XMLColAttVal()
syntax.
Figure 108 XMLColAttVal() Syntax
,
AS
XMLCOLATTVAL
c_alias
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.
Example 1015 XMLColAttVal(): Generating an Emp Element Per Employee with
Name Attribute and Elements with Start Date and Dept as Content
This example generates an Emp element for each employee, with a name attribute
and elements with the employees start date and department as the content.
SELECT XMLELEMENT("Emp",XMLATTRIBUTES(e.fname ||' '||e.lname AS "name" ),
XMLCOLATTVAL ( e.hire, e.dept AS "department")) AS "result"
FROM employees e;
10-19
<column name="HIRE">1992-11-15</column>
<column name="department">Standards</column>
</Emp>
To create an XML document instance from any SQL query and get the
document as a CLOB or XMLType.
To use a fetch interface with maximum rows and rows to skip. For example,
the first fetch could retrieve a maximum of 10 rows, skipping the first four. This
is useful for pagination in Web-based applications.
Options for changing tag names for ROW, ROWSET, and so on.
See Also: "Generating XML with XSUs OracleXMLQuery", in
Chapter 7, "XML SQL Utility (XSU)", and compare the functionality
of OracleXMLQuery with DBMS_XMLGEN.
<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.
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.
10-21
set
the options
bind
values
User / Browser /
Client /
Application
fetch
XML
Generated
XML
as DOM
User / Browser
Client /
Application
close
Generated
XML
as String
Get the context from the package by supplying a SQL query and calling the
newContext() call.
2.
Pass the context to all the procedures/functions in the package to set the
various options. For example to set the ROW elements name, use
setRowTag(ctx), where ctx is the context got from the previous
newContext() call.
3.
Get the XML result, using the getXML() or getXMLType(). By setting the
maximum rows to be retrieved for each fetch using the setMaxRows() call,
you can call this function repeatedly, getting the maximum number of row set
for each call. The function returns null if there are no rows left in the query.
getXML() and getXMLType() always return an XML document, even if there
were no rows to retrieve. If you want to know if there were any rows retrieved,
use the function getNumRowsProcessed().
4.
You can reset the query to start again and repeat step 3.
5.
Description
FUNCTION PROTOTYPES
newContext()
FUNCTION
newContext(queryString IN VARCHAR2)
FUNCTION
newContext(queryString IN SYS_REFCURSOR)
RETURN ctxHandle;
setRowTag()
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:
Sets the name of the element separating all the rows. The default name is
ROW.
PROCEDURE
PARAMETERS:
setRowTag(ctx IN ctxHandle,rowTag IN
VARCHAR2);
ctx (IN) - the context handle obtained from the newContext call,
setRowSetTag()
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.
Sets the name of the documents root element. The default name is
ROWSET
10-23
getXML()
Description
PARAMETERS:
ctx (IN) - the context handle obtained from the newContext call,
rowsetTag (IN) - the name of the document element. NULL indicates
that you do not want the ROW element to be present. Call this to set the
name of the document root element, if you do not want the default
ROWSET name in the output. You can also set this to NULL to
suppress the printing of this element. However, this is an error if both
the row and the rowset are null and there is more than one column or
row in the output.
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,
getXML()
FUNCTION
getXML(ctx IN ctxHandle, dtdOrSchema IN
number:= NONE) RETURN clob
FUNCTION
getXMLType(ctx IN ctxHandle, dtdOrSchema IN
number:= NONE) RETURN XMLTYPE
FUNCTION
getNumRowsProcessed(ctx IN ctxHandle)
RETURN number
setMaxRows()
Description
Converts the query results from the passed in SQL query string to XML
format, and returns the XML as a CLOB.
Converts the query results from the passed in SQL query string to XML
format, and returns the XML as a CLOB.
Gets the number of SQL rows processed when generating the XML
using the getXML call. This count does not include the number of rows
skipped before generating the XML.
PARAMETERS: queryString (IN)- the query string, the result of which
needs to be converted to XML RETURNS:
This gets the number of SQL rows that were processed in the last call to
getXML. You can call this to 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.
Sets the maximum number of rows to fetch from the SQL query result
for every invocation of the getXML call.
PROCEDURE
setMaxRows(ctx IN ctxHandle, maxRows IN
NUMBER);
setSkipRows()
Skips a given number of rows before generating the XML output for
every call to the getXML routine.
PROCEDURE
setSkipRows(ctx IN ctxHandle,
skipRows IN NUMBER);
10-25
Description
setConvertSpecialChars()
PROCEDURE
setConvertSpecialChars(ctx IN ctxHandle,
conv IN boolean);
useItemTagsForColl()
PROCEDURE useItemTagsForColl(ctx IN
ctxHandle);
restartQuery()
PROCEDURE
restartQuery(ctx IN ctxHandle);
closeContext()
PROCEDURE
closeContext(ctx IN ctxHandle);
You can use this function to speed up the XML processing whenever you
are sure that the input data cannot contain any special characters such as
<, >, ", , and so on, which need to be escaped. Note that it is expensive
to actually scan the character data to replace the special characters,
particularly if it involves a lot of data. So in cases when the data is
XML-safe, then this function can be called to improve performance.
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.
PARAMETERS: ctx (IN) - the context handle.
If you have a collection of NUMBER, say, the default tag name for the
collection elements is NUMBER. You can override this behavior and
generate the collection column name with the _ITEM tag appended to it,
by calling this procedure.
Restarts the query and generate the XML from the first row again.
PARAMETERS: ctx (IN) - the context handle corresponding to the
current query. You can call this to start executing the query again,
without having to create a new context.
Closes a given context and releases all resources associated with that
context, including the SQL cursor and bind and define buffers, and so
on.
Conversion Functions
FUNCTION
convert(xmlData IN varchar2, flag IN NUMBER :=
ENTITY_ENCODE) return varchar2;
FUNCTION
convert(xmlData IN CLOB, flag IN NUMBER :=
ENTITY_ENCODE)
return CLOB;
This example creates an XML document by selecting out the employee data from an
object-relational table and putting the resulting CLOB into a table.
CREATE TABLE temp_clob_tab(result CLOB);
DECLARE
qryCtx DBMS_XMLGEN.ctxHandle;
result CLOB;
BEGIN
qryCtx := dbms_xmlgen.newContext('SELECT * from scott.emp');
-- set the row header to be EMPLOYEE
DBMS_XMLGEN.setRowTag(qryCtx, 'EMPLOYEE');
-- now get the result
result := DBMS_XMLGEN.getXML(qryCtx);
INSERT INTO temp_clob_tab VALUES(result);
--close context
DBMS_XMLGEN.closeContext(qryCtx);
END;
/
10-27
<JOB>SALESMAN</JOB>
<MGR>7698</MGR>
<HIREDATE>20-FEB-81</HIREDATE>
<SAL>1600</SAL>
<COMM>300</COMM>
<DEPTNO>30</DEPTNO>
</EMPLOYEE>
...
</ROWSET>
Instead of generating all the XML for all rows, you can use the fetch interface that
DBMS_XMLGEN provides to retrieve a fixed number of rows each time. This speeds
up response time and also can help in scaling applications that need a DOM API on
the resulting XML, particularly if the number of rows is large.
The following example illustrates how to use DBMS_XMLGEN to retrieve results from
table scott.emp:
-- create a table to hold the results..!
CREATE TABLE temp_clob_tab ( result clob);
declare
qryCtx dbms_xmlgen.ctxHandle;
result CLOB;
begin
-- get the query context;
qryCtx := dbms_xmlgen.newContext('select * from scott.emp');
-- set the maximum number of rows to be 5,
dbms_xmlgen.setMaxRows(qryCtx, 5);
loop
-- now get the result
result := dbms_xmlgen.getXML(qryCtx);
-- if there were no rows processed, then quit..!
exit when dbms_xmlgen.getNumRowsProcessed(qryCtx) = 0;
------
Complex XML can be generated using object types to represent nested structures:
CREATE TABLE new_departments (
department_id NUMBER PRIMARY KEY,
department_name VARCHAR2(20)
);
CREATE TABLE new_employees (
employee_id
NUMBER PRIMARY KEY,
last_name
VARCHAR2(20),
department_id NUMBER REFERENCES new_departments
);
CREATE TYPE emp_t AS OBJECT(
"@employee_id" NUMBER,
last_name VARCHAR2(20)
);
/
CREATE TYPE emplist_t AS TABLE OF emp_t;
/
CREATE TYPE dept_t AS OBJECT(
"@department_id" NUMBER,
department_name VARCHAR2(20),
emplist emplist_t
);
/
qryCtx := dbms_xmlgen.newContext
('SELECT dept_t(department_id, department_name,
CAST(MULTISET
(SELECT e.employee_id, e.last_name
10-29
FROM new_employees e
WHERE e.department_id = d.department_id)
AS emplist_t)) AS deptxml
FROM new_departments d');
DBMS_XMLGEN.setRowTag(qryCtx, NULL);
-- Here is the resulting XML:
-- <ROWSET>
-<DEPTXML DEPARTMENT_ID="10">
-<DEPARTMENT_NAME>SALES</DEPARTMENT_NAME>
-<EMPLIST>
-<EMP_T EMPLOYEE_ID="30">
-<LAST_NAME>Scott</LAST_NAME>
-</EMP_T>
-<EMP_T EMPLOYEE_ID="31">
-<LAST_NAME>Mary</LAST_NAME>
-</EMP_T>
-</EMPLIST>
-</DEPTXML>
-<DEPTXML DEPARTMENT_ID="20">
-...
-- </ROWSET>
Now, you can select the LOB data from the temp_clob_Tab table and verify the
results. The result looks like the sample result shown in the previous section,
"Sample DBMS_XMLGEN Query Result" on page 10-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:
When you input a user-defined type (UDT) value to DBMS_XMLGEN functions, the
user-defined type is mapped to an XML document using canonical mapping. In the
canonical mapping, user-defined types attributes are mapped to XML elements.
Attributes with names starting with @ are mapped to attributes of the preceding
element.
User-defined types can be used for nesting in the resulting XML document. For
example, consider tables, EMP and DEPT:
CREATE TABLE DEPT
(
deptno number primary key,
dname varchar2(20)
);
CREATE TABLE EMP
(
empno number primary key,
ename varchar2(20),
deptno number references dept
);
To generate a hierarchical view of the data, that is, departments with employees in
them, you can 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.
10-31
The MULTISET operator treats the result of the subset of employees working in the
department as a list and the CAST around it, cast's it to the appropriate collection
type. You then create a department instance around it and call the DBMS_XMLGEN
routines to create the XML for the object instance. The result is:
------------------
<?xml version="1.0"?>
<ROWSET>
<DEPTXML deptno="10">
<DNAME>Sports</DNAME>
<EMPLIST>
<EMP_T empno="200">
<ENAME>John</ENAME>
</EMP_T>
<EMP_T empno="300">
<ENAME>Jack</ENAME>
</EMP_T>
</EMPLIST>
</DEPTXML>
<DEPTXML deptno="20">
<!-- .. other columns -->
</DEPTXML>
</ROWSET>
The default name ROW is not present because you set that to NULL. The deptno
and empno have become attributes of the enclosing element.
Example 1020 DBMS_XMLGEN: Generating a Purchase Order from the Database in
XML Format
10-33
Street
City
State
Zip
)
VARCHAR2(200),
VARCHAR2(200),
CHAR(2),
VARCHAR2(20)
/
-- Customer object type
CREATE TYPE Customer_typ AS OBJECT (
CustNo
NUMBER,
CustName
VARCHAR2(200),
Address
Address_typ,
PhoneList
PhoneList_vartyp
)
/
-- StockItem object type
CREATE TYPE StockItem_typ AS OBJECT (
"@StockNo"
NUMBER,
Price
NUMBER,
TaxRate
NUMBER
)
/
-- LineItems object type
CREATE TYPE LineItem_typ AS OBJECT (
"@LineItemNo" NUMBER,
Item
StockItem_typ,
Quantity
NUMBER,
Discount
NUMBER
)
/
-- LineItems Nested table
CREATE TYPE LineItems_ntabtyp AS TABLE OF LineItem_typ
/
-- Purchase Order object type
CREATE TYPE PO_typ AUTHID CURRENT_USER AS OBJECT (
PONO
NUMBER,
Cust_ref
REF Customer_typ,
OrderDate
DATE,
ShipDate
TIMESTAMP,
LineItems_ntab
LineItems_ntabtyp,
ShipToAddr
Address_typ
)
/
-- Create Purchase Order Relational Model tables
--Customer table
CREATE TABLE Customer_tab(
CustNo
NUMBER NOT NULL,
CustName
VARCHAR2(200) ,
Street
VARCHAR2(200) ,
City
VARCHAR2(200) ,
State
CHAR(2) ,
Zip
VARCHAR2(20) ,
Phone1
VARCHAR2(20),
Phone2
VARCHAR2(20),
Phone3
VARCHAR2(20),
constraint cust_pk PRIMARY KEY (CustNo)
)
ORGANIZATION INDEX OVERFLOW;
-- Purchase Order table
CREATE TABLE po_tab (
PONo
NUMBER, /* purchase order no */
Custno
NUMBER constraint po_cust_fk references Customer_tab,
/* Foreign KEY referencing customer */
OrderDate DATE, /* date of order */
ShipDate
TIMESTAMP, /* date to be shipped */
ToStreet
VARCHAR2(200), /* shipto address */
ToCity
VARCHAR2(200),
ToState
CHAR(2),
ToZip
VARCHAR2(20),
constraint po_pk PRIMARY KEY(PONo)
);
--Stock Table
CREATE TABLE Stock_tab (
StockNo
NUMBER constraint stock_uk UNIQUE,
Price
NUMBER,
TaxRate
NUMBER
);
--Line Items Table
CREATE TABLE LineItems_tab(
LineItemNo
NUMBER,
PONo
NUMBER constraint LI_PO_FK REFERENCES po_tab,
StockNo
NUMBER ,
10-35
Quantity
NUMBER,
Discount
NUMBER,
constraint LI_PK PRIMARY KEY (PONo, LineItemNo)
);
-- create Object Views
--Customer Object View
CREATE OR REPLACE VIEW Customer OF Customer_typ
WITH OBJECT IDENTIFIER(CustNo)
AS SELECT c.Custno, C.custname,
Address_typ(C.Street, C.City, C.State, C.Zip),
PhoneList_vartyp(Phone1, Phone2, Phone3)
FROM Customer_tab c;
--Purchase order view
CREATE OR REPLACE VIEW PO OF PO_typ
WITH OBJECT IDENTIFIER (PONO)
AS SELECT P.PONo,
MAKE_REF(Customer, P.Custno),
P.OrderDate,
P.ShipDate,
CAST( MULTISET(
SELECT LineItem_typ( L.LineItemNo,
StockItem_typ(L.StockNo,S.Price,S.TaxRate),
L.Quantity, L.Discount)
FROM LineItems_tab L, Stock_tab S
WHERE L.PONo = P.PONo and S.StockNo=L.StockNo )
AS LineItems_ntabtyp),
Address_typ(P.ToStreet,P.ToCity, P.ToState, P.ToZip)
FROM PO_tab P;
-- create table with XMLType column to store po in XML format
create table po_xml_tab(
poid number,
poDoc XMLTYPE /* purchase order in XML format */
)
/
--------------------- Populate data
-------------------- Establish Inventory
INSERT INTO Stock_tab VALUES(1004, 6750.00, 2) ;
INTO
INTO
INTO
INTO
LineItems_tab
LineItems_tab
LineItems_tab
LineItems_tab
VALUES(01,
VALUES(02,
VALUES(01,
VALUES(02,
1001,
1001,
2001,
2001,
1534,
1535,
1004,
1011,
12,
10,
1,
2,
0)
10)
0)
1)
;
;
;
;
10-37
<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>
10-39
<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>
SYS_XMLGEN() Function
page NUMBER := 0;
xmlpage boolean := true;
refcur SYS_REFCURSOR;
BEGIN
OPEN refcur FOR 'select * from emp where rownum < :1' USING ctx1;
ctx2 := DBMS_XMLGEN.newContext( refcur);
ctx1 := 4;
OPEN refcur FOR 'select * from emp where rownum < :1' USING ctx1;
ctx1 := 5;
OPEN refcur FOR 'select * from emp where rownum < :1' USING ctx1;
dbms_lob.createtemporary(xmldoc, TRUE);
-- xmldoc will have 4 rows
xmldoc := DBMS_XMLGEN.getXML(ctx2,DBMS_XMLGEN.NONE);
DBMS_XMLGEN.closeContext(ctx2);
return xmldoc;
END;
/
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.
Example 1022 Using SQL_XMLGEN to Create XML
10-41
SYS_XMLGEN() Function
SYS_XMLGEN Syntax
SYS_XMLGEN() takes in a scalar value, object type, or XMLType instance to be
converted to an XML document. It also takes an optional XMLFormat (the old name
was XMLGenFormatType) object that you can use to specify formatting options for
the resulting XML document. See Figure 1010.
Figure 1010 SYS_XMLGEN Syntax
fmt
SYS_XMLGEN
expr
If expr is a scalar value, the function returns an XML element containing the
scalar value.
If expr is a type, the function maps the user-defined type attributes to XML
elements.
If expr is a XMLType instance, then the function encloses the document in an
XML element whose default tag name is ROW.
By default the elements of the XML document match the elements of expr. For
example, if expr resolves to a column name, the enclosing XML element will have
the same name as the column. If you want to format the XML document differently,
specify fmt, which is an instance of the XMLFormat object.
In this release, the formatting argument for SYS_XMLGEN() accepts the schema and
element name, and generates the XML document conforming to that registered
schema.
SELECT sys_xmlgen(
dept_t(d.deptno, d.dname, d.loc,
cast(multiset(
SELECT emp_t(e.empno, e.ename, e.job, e.mgr, e.hiredate,e.sal, e.comm)
FROM emp e
WHERE e.deptno = d.deptno) AS emplist_t),
xmlformat.createformat('Department', 'http://www.oracle.com/dept.xsd'))
FROM dept d;
SYS_XMLGEN() Function
The following example retrieves the employee email ID from the sample table
oe.employees where the employee_id value is 205, and generates an instance of
a XMLType containing an XML document with an EMAIL element.
SELECT SYS_XMLGEN(email).getStringVal()
FROM employees
WHERE employee_id = 205;
SYS_XMLGEN(EMAIL).GETSTRINGVAL()
-----------------------------------------------------------------<EMAIL>SHIGGENS</EMAIL>
You can create and query XML instances within SQL queries.
Using the object-relational infrastructure, you can create complex and nested
XML instances from simple relational tables.
XML
10-43
SYS_XMLGEN() Function
Table 102 lists the XMLFormat attributes. of the XMLFormat object. The function
that implements this type follows the table.
Table 102 Attributes of the XMLFormat Object
Attribute
Datatype
Purpose
enclTag
VARCHAR2(100)
The name of the enclosing tag for the result of the SYS_XMLGEN
function. If the input to the function is a column name, the default
is the column name. Otherwise the default is ROW. When
schemaType is set to USE_GIVEN_SCHEMA, this attribute also
gives the name of the XMLSchema element.
schemaType
VARCHAR2(100)
schemaName
VARCHAR2(4000)
The name of the target schema Oracle uses if the value of the
schemaType is USE_GIVEN_SCHEMA. If you specify
schemaName, then Oracle uses the enclosing tag as the element
name.
targetNameSpace
VARCHAR2(4000)
dburl
VARCHAR2(2000)
processingIns
VARCHAR2(4000)
You can use the static member function createformat to implement the
XMLFormat object. This function has most of the values defaulted. For example:
STATIC FUNCTION createFormat(
enclTag IN varchar2 := ROWSET,
schemaType IN varchar2 := NO_SCHEMA,
schemaName IN varchar2 := null,
targetNameSpace IN varchar2 := null,
dburlPrefix IN varchar2 := null,
processingIns IN varchar2 := null) RETURN XMLGenFormatType,
MEMBER PROCEDURE genSchema (spec IN varchar2),
MEMBER PROCEDURE setSchemaName(schemaName IN varchar2),
MEMBER PROCEDURE setTargetNameSpace(targetNameSpace IN varchar2),
MEMBER PROCEDURE setEnclosingElementName(enclTag IN varchar2),
MEMBER PROCEDURE setDbUrlPrefix(prefix IN varchar2),
SYS_XMLGEN() Function
When you input a scalar value to SYS_XMLGEN(), it converts the scalar value to an
element containing the scalar value. For example:
select sys_xmlgen(empno) from scott.emp where rownum < 2;
returns an XML document that contains the empno value as an element, as follows:
<?xml version="1.0"?>
<EMPNO>30</EMPNO>
The enclosing element name, in this case EMPNO, is derived from the column name
passed to the operator. Also, note that the result of the SELECT statement is a row
containing a XMLType.
Example 1026 Generating Default Column Name, ROW
In the last example, you used the column name EMPNO for the document. If the
column name cannot be derived directly, then the default name ROW is used. For
example, in the following case:
SELECT sys_xmlgen(empno).getclobval()
FROM scott.emp
WHERE rownum < 2;
10-45
SYS_XMLGEN() Function
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.
Example 1027 Overriding the Default Column Name: Supplying an XMLFormat
Object to the Operators First Argument
For example, in the last case, if you wanted the result to have EMPNO as the tag
name, you can supply a formatting argument to the function, as follows:
SELECT sys_xmlgen(empno *2,
xmlformat.createformat(EMPNO)).getClobVal()
FROM emp;
The MULTISET operator treats the result of the subset of employees working in the
department as a list and the CAST around it, casts it to the appropriate collection
SYS_XMLGEN() Function
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.
Note: The difference between SYS_XMLGEN() function and
DBMS_XMLGEN package is apparent from the preceding example:
10-47
SYS_XMLGEN() Function
<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.
Example 1030 SYS_XMLGEN(): Using SYS_XMLGEN() with Object Views
-- create Purchase Order object type
CREATE OR REPLACE TYPE PO_typ AUTHID CURRENT_USER AS OBJECT (
SYS_XMLGEN() Function
PONO
Customer
OrderDate
ShipDate
LineItems_ntab
ShipToAddr
)
/
NUMBER,
Customer_typ,
DATE,
TIMESTAMP,
LineItems_ntabtyp,
Address_typ
10-49
SYS_XMLAGG() Function
<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
expr
The following example uses nested xmlagg() functions to aggregate the results of
a dynamically-constructed XML document containing departments and nested
employees into a single XML "result" document, wrapped in a <DepartmentList>
element:
<xsql:include-xml connection="orcl92" xmlns:xsql="urn:oracle-xsql">
select XmlElement("DepartmentList",
XmlAgg(
XmlElement("Department",
XmlAttributes(deptno as "Id"),
XmlForest(dname as "Name"),
(select XmlElement("Employees",
XmlAgg(
XmlElement("Employee",
XmlAttributes(empno as "Id"),
XmlForest(ename as "Name",
sal as "Salary",
job as "Job")
)
)
)
from emp e
10-51
Since it is more efficient for the database to aggregate XML fragments into a single
result document, the <xsql:include-xml> element encourages this approach by
only retrieving the first row from the query you provide.
For example, if you have a number of <Movie> XML documents stored in a table of
XmlType called MOVIES, each document might look something like this:
<Movie Title="The Talented Mr.Ripley" RunningTime="139" Rating="R">
<Director>
<First>Anthony</First>
<Last>Minghella</Last>
</Director>
<Cast>
<Actor Role="Tom Ripley">
<First>Matt</First>
<Last>Damon</Last>
</Actor>
<Actress Role="Marge Sherwood">
<First>Gwenyth</First>
<Last>Paltrow</Last>
</Actress>
<Actor Role="Dickie Greenleaf">
<First>Jude</First>
<Last>Law</Last>
<Award From="BAFTA" Category="Best Supporting Actor"/>
</Actor>
</Cast>
</Movie>
You can use the built-in Oracle9i XPath query features to extract an aggregate list of
all cast members who have received Oscar awards from any movie in the database
using a query like this:
SELECT xmlelement("AwardedActors",
xmlagg(extract(value(m),
'/Movie/Cast/*[Award[@From="Oscar"]]')))
FROM movies m;
-- To include this query result of XMLType into your XSQL page,
-- simply paste the query inside an <xsql:include-xml> element, and add
-- a getClobVal() method call to the query expression so that the result will
-- be returned as a CLOB instead of as an XMLType to the client:
<xsql:include-xml connection="orcl92" xmlns:xsql="urn:oracle-xsql">
select xmlelement("AwardedActors",
xmlagg(extract(value(m),
'/Movie/Cast/*[Award[@From="Oscar"]]'))).getClobVal()
from movies m
</xsql:include-xml>
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 Developers Kits Guide - XDK, the chapter
in "XDK for Java" on XSQL Page Publishing Framework.
10-53
You can generate XML on this table using Java with the call:
java OracleXML getXML -user "scott/tiger" -rowTag "Part" "select * from parts"
11
XMLType Views
This chapter describes how to create and use XMLType views. It contains the
following sections:
You can exploit the new Oracle XML DB XML features that use XMLSchema
functionality without having to migrate your base legacy data.
With XMLType views, you can experiment with various other forms of storage,
besides the object-relational or CLOB storage alternatives available to XMLType
tables.
XMLType views are similar to object views. Each row of an XMLType view
corresponds to an XMLType instance. The object identifier for uniquely identifying
each row in the view can be created using an expression such as extract() on the
XMLType value.
Similar to XMLType tables, XMLType views can conform to an XML schema. This
provides stronger typing and enables optimization of queries over these views.
To use XMLType views with XML schemas, you must first register your XML
schema with annotations that represent the bi-directional mapping from XML to
SQL object types. An XMLType view conforming to this registered XML schema can
then be created by providing an underlying query that constructs instances of the
appropriate SQL object type.
See Also:
This chapter describes the two main ways you can create XMLType views:
11-2
Example 111 XMLType View: Creating XMLType View Using XMLElement() Function
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.
11-4
1.
2.
Create or generate and then register an XML schema document that contains
the XML structures, along with its mapping to the SQL object types and
attributes. See Chapter 5, "Structured Mapping of XMLType".
3.
Create the XMLType view and specify the XML schema URL and the root
element name. The underlying view query first constructs the object instances
and then converts them to XML. This step can also be done in two steps:
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:
For the first example view, to wrap the relational employee data with nested
department information as XML, follow these steps:
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.
11-6
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;
11-8
The XMLElement() function creates the Employee XML element and the inner
XMLForest() creates the kids of the employee element. The XMLAttributes
clause inside the XMLElement() constructs the required XML namespace and
schema location attributes so that the XML generated conforms to the views XML
schema.The innermost XMLForest() function creates the department XML
element that is nested inside the Employee element.
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.
-<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;
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",
specified at the view level because the SELECT list could arbitrarily
construct XML of a different XML schema from the underlying
table.
For example, consider the creation of XMLType table po_tab. Refer to Example 61,
"Transforming an XMLType Instance Using XMLTransform() and DBUriType to Get
the XSL Stylesheet" on page 6-6 for an xmltransform() example:
DROP TABLE po_tab;
CREATE TABLE po_tab OF xmltype xmlschema "ipo.xsd" element
"PurchaseOrder";
-- You can then create a view of the table as follows:
XMLType view reference REF() is based on one of the following object IDs:
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.
For example, if the XMLType view query is based on an object view or an object
constructor that is itself inherently updatable:
DROP TYPE dept_t force;
CREATE OR REPLACE TYPE dept_t AS OBJECT
(
DEPTNO
NUMBER(2),
DNAME
VARCHAR2(14),
LOC
VARCHAR2(13)
);
/
BEGIN
dbms_xmlschema.deleteSchema(http://www.oracle.com/dept.xsd, 4);
END;
/
BEGIN
dbms_xmlschema.registerSchema(http://www.oracle.com/dept.xsd,
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/dept.xsd" version="1.0"
xmlns:xdb="http://xmlns.oracle.com/xdb"
elementFormDefault="qualified">
<element name = "Department" xdb:SQLType="DEPT_T" xdb:SQLSchema="SCOTT">
<complexType>
<sequence>
<element name = "DeptNo" type = "positiveInteger" xdb:SQLName="DEPTNO"
xdb:SQLType="NUMBER"/>
<element name = "DeptName" type = "string" xdb:SQLName="DNAME"
xdb:SQLType="VARCHAR2"/>
<element name = "Location" type = "string" xdb:SQLName="LOC"
xdb:SQLType="VARCHAR2"/>
</sequence>
</complexType>
</element>
</schema>, TRUE, FALSE, FALSE);
END;
/
CREATE OR REPLACE VIEW dept_xml of xmltype
xmlschema "http://www.oracle.com/dept.xsd" element "Department"
with object id (sys_nc_rowinfo$.extract(/Department/DeptNo).getnumberval()) as
select dept_t(d.deptno, d.dname, d.loc) from dept d;
INSERT INTO dept_xml VALUES (XMLType.createXML(
<Department xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.oracle.com/dept.xsd">
<DeptNo>50</DeptNo>
<DeptName>EDP</DeptName>
<Location>NEW YORK</Location>
</Department>));
UPDATE dept_xml d
SET d.sys_nc_rowinfo$ = updateXML(d.sys_nc_rowinfo$,
/Department/DeptNo/text(), 60)
WHERE existsNode(d.sys_nc_rowinfo$, /Department[DeptNo=50]) = 1;
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.
Note: Query rewrite only happens with SYS_XMLGEN. Queries
is rewritten to :
SELECT SYS_XMLGEN(empno)
FROM emp e
WHERE e.ename = SMITH;
createXML()
SYS_XMLGEN()
SYS_XMLAGG()
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)
12
Creating and Accessing Data Through
URLs
This chapter describes how to generate and store URLs inside the database and to
retrieve the data pointed to by the URLs. It also introduces the concept of DBUris
which are URLs to relational data stored inside the database. It explains how to
create and store references to data stored in Oracle XML DB Repository hierarchy.
This chapter contains these sections:
URI Concepts
HttpUriType Functions
XDBUriType
the more general term, but the details apply to URLs as well. Some
of the type names use Uri instead of URI. Because most of this
information is based on SQL and PL/SQL, the names are usually
not case-sensitive; only when referring to a real filename on a Web
site or a Java API name does case matter.
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.
12-2
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 Also: "Registering New UriType Subtypes with the
UriFactory Package" on page 12-26
URI Concepts
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.
12-4
URI Concepts
The portion after the # identifies a fragment within the document. This
portion is defined by the W3C XPointer recommendation.
Using a servlet
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.
These datatypes are object types with member functions that can be used to access
objects or pages pointed to by the objects. By using UriType, you can:
Create table columns that point to data inside or outside the database.
These are related by an inheritance hierarchy. UriType is an abstract type and the
DBUriType, HttpUriType, and XDBUriType are subtypes of UriType. You can
reference data stored in CLOBs or other columns and expose them as URLs to the
external world. Oracle9i provides a standard servlet than can be installed and run
under the Oracle Servlet engine that interprets these URLs.
12-6
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.
See Also: "Using UriType Objects" on page 12-22.
UriType Functions
The UriType abstract type supports a variety of functions that can be used over
any subtype. Table 121 lists the UriType member functions.
Table 121 UriType Member Functions
UriType Member
Functions
Description
getClob()
getUrl()
getExternalUrl()
getContentType()
Returns the MIME information for the URL. For UriType, this
is an abstract function.
getXML()
HttpUriType Functions
Description
getBlob()
createUri(uri IN VARCHAR2)
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 122 lists the HttpUriType member functions.
Table 122 HttpUriType Member Functions
12-8
HttpUriType Method
Description
getClob
getUrl
getExternalUrl
getBlob
getXML
getContentType()
createUri()
httpUriType()
getContentType() Function
getContentType() function returns the MIME information for the URL. The
HttpUriType de-references the URL and gets the MIME header information. You
can use this information to decide whether to retrieve the URL as BLOB or CLOB
based on the MIME type. You would treat a Web page with a MIME type of
x/jpeg as a BLOB, and one with a MIME type of text/plain or text/html as
a CLOB.
Example 121 Using getContentType() and HttpUriType to Return HTTP Headers
Getting the content type does not fetch all the data. The only data transferred is the
HTTP headers (for HTTPURiType) or the metadata of the column (for DBUriType).
For example:
declare
httpuri HttpUriType;
x clob;
y blob;
begin
httpuri := HttpUriType('http://www.oracle.com/object1');
if httpuri.getContentType() = 'application-x/bin' then
y := httpuri.getblob();
else
x := httpuri.getclob();
end if;
end;
getXML() Function
getXML() function returns XMLType information for the result. If the document is
not valid XML (or XHTML) an error is thrown.
The visual model is a hierarchical view of what a current connected user would
see in terms of SQL schemas, tables, rows, and columns.
The XML view contains a root element that maps to the database. The root XML
element contains child elements, which are the schemas on which the user has
some privileges on any object. The schema elements contain tables and views
that the user can see.
For example, the user scott can see the following virtual XML document.
<?xml version=1.0?>
<oradb SID="ORCL">
<PUBLIC>
<ALL_TABLES>
..
</ALL_TABLES>
<EMP>
<!-- EMp table -->
</EMP>
</PUBLIC>
<SCOTT>
<ALL_TABLES>
....
</ALL_TABLES>
<EMP>
<ROW>
<EMPNO>1001</EMPNO>
<ENAME>John</ENAME>
<EMP_SALARY>20000</EMP_SALARY>
</ROW>
<ROW>
<EMPNO>2001</EMPNO>
</ROW>
</EMP>
<DEPT>
<ROW>
<DEPTNO>200</DEPTNO>
<DNAME>Sports</DNAME>
</ROW>
</DEPT>
</SCOTT>
<JONES>
<CUSTOMER_OBJ_TAB>
<ROW>
<NAME>xxx</NAME>
<ADDRESS>
<STATE>CA</STATE>
<ZIP>94065</ZIP>
</ADDRESS>
</ROW>
</CUSTOMER_OBJ_TAB>
</JONES>
</oradb>
Figure 121 DBUri: Visual or SQL View, XML View, and Associated XPath
Database
Table Emp
Empno
Ename
Job
.
21
33
x
.
John
Mary
x
.
x
x
x
<oracle>
<scott>
<emp>
<row>
XML
<EmpNo> 21
Visualization
<Ename> John
</row>
</emp>
</scott>
</oracle>
XML document
XMLview
URL becomes . . .
/oracle/scott/emp/row/[empno=21]/ename..
URI-Reference
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
Scalar
Object
Collection
These are the smallest addressable units. For example, you can use:
/oradb/SCOTT/EMP
or
/oradb/SCOTT/EMP/ROW[empno=7263]
Include the user database schema name or specify PUBLIC to resolve the table
name without a specific schema.
Include predicates at any level in the path other than the schema and table
elements.
Indicate predicates not on the selection path in the ROW element.
For example, if you wanted to specify the predicate pono = 100, but the
selection path is:
/oradb/scott/purchase_obj_tab/ROW/line_item_list
you must include the pono predicate along with the ROW node as:
/oradb/scott/purchase_obj_tab/ROW[pono=100]/line_item_list
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 124 Searching for Attribute Values on Object Columns Using DBUri
For example, the following DBUri refers to an ADDRESS column containing state,
city, street, and zip code attributes:
/oradb/SCOTT/EMP/ROW[ADDRESS/STATE=CA OR
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.
See Also: http://www.w3.org/TR/xpath for an explanation
of the XML XPath notation
For example:
/oradb/SCOTT/EMP
For example:
/oradb/SCOTT/EMP/ROW[EMPNO=7369]
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 129 Using DBUri to Retrieve Only the Text Value of the Node
For example:
/oradb/SCOTT/EMP/ROW[EMPNO=7369]/ENAME/text()
retrieves the text value of the employee name, without the XML tags, for an
employee with empno = 7369. This returns a text document, not an XML
document, with value SMITH.
Note: The XPath alone does not constitute a valid URI. Oracle
calls it a DBUri since it behaves like a URI within the database, but
it can be translated into a globally valid Uri-ref.
DBUriType Functions
To access the XSL stylesheets stored in the database for use during parsing.
To make references, such as import or include, to related XSL stylesheets. You
can encode these references within the XSL stylesheet itself.
Note:
DBUriType Functions
Table 123 lists the DBUriType methods and functions.
Table 123 DBUriType Methods and Functions
Method/Function
Description
getClob()
Returns the value pointed to by the URL as a character LOB value. The character
encoding is the same as the database character set.
getUrl()
getExternalUrl()
Similar to getUrl, except that it calls the escaping mechanism to escape the
characters in the URL as to conform to the URL specification. For example, spaces
are converted to the escaped value %20.
DBUriType 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()
getContentType()
createUri()
dbUriType()
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.
XDBUriType
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:
Table 124 lists the XDBUriType methods. These methods do not take any
arguments.
Description
getClob()
Returns the value pointed to by the URL as a Character Large Object (CLOB)
value. The character encoding is the same as the database character set.
get Blob()
Returns the value pointed to by the URL as a Binary Large Object (BLOB) value.
getUrl()
getExternalUrl()
Similar to getUrl, except that it calls the escaping mechanism to escape the
characters in the URL as to conform to the URL specification. For example, spaces
are converted to the escaped value %20.
XDBUriType
Description
getXML()
Returns the XMLType object corresponding to the contents of the resource that this
URI points to. This is provided so that an application that needs to perform
operations other than getClob/getBlob can use the XMLType methods to do those
operations..
getContentType()
Returns the MIME information for the resource stored in the ORACLE XML DB
Repository.
XDBUriType()
For example, the following statement returns an XDBUriType instance that refers
to /home/scott/doc1.xml:
SELECT sys.UriFactory.getUri(/home/scott/doc1.xml) FROM dual;
Example 1211 Creating XDBUriType, Inserting Values Into a Purchase Order Table
and Selecting All the PurchaseOrders
Example 1212 Retrieving Purchase Orders at a URL Using UriType, getXML() and
extractValue()
You can create a list of all purchase orders with URL references to them as follows:
CREATE TABLE uri_tab
(
poUrl SYS.UriType, -- Note that we have created abstract type columns
-- if you know what kind of uri's you are going to store, you can
-- create the appropriate types.
poName VARCHAR2(200)
);
-- insert an absolute url into SYS.UriType..!
-- the Urifactory creates the correct instance (in this case a HttpUriType
INSERT INTO uri_tab VALUES
(sys.UriFactory.getUri('http://www.oracle.com/cust/po'),'AbsPo');
-- insert a URL by directly calling the SYS.HttpUriType constructor.
-- Note this is strongly discouraged. Note the absence of the
-- http:// prefix when creating SYS.HttpUriType instance through the default
-- constructor.
INSERT INTO uri_tab VALUES (sys.HttpUriType('proxy.us.oracle.com'),'RelPo');
-- Now extract all the purchase orders
SELECT e.poUrl.getClob(), poName FROM uri_tab e;
-- In PL/SQL
declare
a SYS.UriType;
begin
-- absolute URL
SELECT poUrl into a from uri_Tab WHERE poName like 'AbsPo%';
SELECT poUrl into a from uri_Tab WHERE poName like 'RelPo%';
-- here u need to supply a prefix before u can get at the data..!
printDataOut(a.getClob());
end;
/
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;
release.
Example 1214 DBUriType: Creating DBUri References
The following example creates a table with a column of type DBUriType and
assigns a value to it.
CREATE TABLE DBURiTab(DBUri DBUriType, dbDocName VARCHAR2(2000));
-- insert values into it..!
INSERT INTO DBUriTab VALUES
(sys.DBUriType.createUri(/ORADB/SCOTT/EMP/ROW[EMPNO=7369]),emp1);
INSERT INTO DBUriTab VALUES
(sys.DBUriType(/SCOTT/EMP/ROW[EMPNO=7369]/,null);
-- access the references
SELECT e.DBUri.getCLOB() from DBUriTab e;
If the prefix starts with http://, getUri creates and returns an instance of a
SYS.HttpUriType object.
If the string starts with either /oradb/ or /dburi/, getUri creates and
returns an instance of a SYS.DBUriType object.
If the string does not start with one of the prefixes noted in the preceding
bullets, getUri creates and returns an instance of a SYS.XDBUriType object.
For example, you can invent a new protocol ecom:// and define a subtype of
UriType to handle that protocol. Perhaps the subtype implements some special
logic for getCLOB, or does some changes to the XML tags or data within getXML.
When you register the ecom:// prefix with UriFactory, any calls to
UriFactory.getUri generate the new subtype instance for URIs that begin with
the ecom:// prefix.
Description
escapeUri()
MEMBER FUNCTION escapeUri() RETURN
varchar2
unescapeUri()
PROCEDURE registerUrlHandler(prefix IN
The type also implements the following static member function:
varchar2, schemaName in varchar2,
STATIC FUNCTION createUri(url IN varchar2) RETURN
typename in varchar2, ignoreCase in boolean <typename>;
:= true, stripprefix in boolean := true)
This function is called by getUrl() to generate an instance of the type.
The stripprefix indicates that the prefix must be stripped off before
calling the appropriate constructor for the type.
unRegisterUrlHandler()
PROCEDURE unregisterUrlHandler(prefix in
varchar2)
);
/
-- Register a new handler for the ecom:// prefix.
begin
-- register a new handler for ecom:// prefixes. The handler
-- type name is ECOMUriTYPE, schema is SCOTT
-- Ignore the prefix case, so that UriFactory creates the same subtype
-- for URIs beginning with ECOM://, ecom://, eCom://, and so on.
-- Strip the prefix before calling the createUri function
-- so that the string ecom:// is not stored inside the
-- ECOMUriTYPE object. (It is added back automatically when
-- you call ECOMUriTYPE.getURL.)
urifactory.registerURLHandler
(
prefix => ecom://,
schemaname => SCOTT,
typename => ECOMURITYPE,
ignoreprefixcase => true,
stripprefix => true
);
end;
/
-- Now the example inserts this new type of URI into the table.
insert into url_tab values (ECOM://company1/company2=22/comp);
-- Use the factory to generate an instance of the appropriate
-- subtype for each URI in the table.
select urifactory.getUri(urlcol) from url_tab;
-- would now generate
HttpUriType(www.oracle.com); -- a Http uri type instance
DBUriType(/oradb/SCOTT/EMPLOYEE/ROW[ENAME="Jack"],null); -- a DBUriType
EComUriType(company1/company2=22/comp); -- an EComUriType instance
Additionally, you can have different constraints on the columns based on the
type involved. For instance, for the HTTP case, you could potentially define
proxy and firewall constraints on the column so that any access through the
HTTP would use the proxy server.
rowid
text
)
attribute
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.
See Also: Oracle9i SQL Reference for SYS_DBURIGEN syntax
If you do not specify an XML schema, Oracle interprets the table or view name as a
public synonym.
For example:
select SYS_DBURIGEN(empno) from emp
WHERE empno=7369;
uses the empno both as the key column and the referenced column, generating
a URL of the form:
/SCOTT/EMP/ROW[EMPNO=7369]/EMPNO,
SYS_DBURIGEN Examples
Example 1218 Inserting Database References Using SYS_DBURIGEN()
CREATE TABLE doc_list_tab(docno number primary key, doc_ref SYS.DBUriType);
-- inserts /SCOTT/EMP/ROW[rowid=xxx]/EMPNO
INSERT INTO doc_list_tab values(1001,
(select SYS_DBURIGEN(rowid,empno) from emp where empno = 100));
-- insert a Uri-ref to point to the ename column of emp!
INSERT INTO doc_list_tab values(1002,
(select SYS_DBURIGEN(empno, ename) from emp where empno = 7369));
-- result of the DBURIGEN looks like, /SCOTT/EMP/ROW[EMPNO=7369]/ENAME
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;
SHORT_STORY
STORY_LINK
----------------------------------------------------------------------------Egypt
This is my story of h
SYS.DBUriType(/PUBLIC/TRAVEL_STORY/ROW[STORY_NAME=Egypt]/STORY/text())
RETURNING Uri-Refs
You can use SYS_DBURIGEN() in the RETURNING clause of DML statements to
retrieve the URL of an object as it is inserted.
Example 1220 Using SYS_DBURIGEN in the RETURNING Clause to Retrieve the
URL of an Object
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;
/
that you want the URL to return just the CLOB value and not an
XML document enclosing the CLOB text.
Example 1221 URL for Overriding the MIME Type by Generating the contenttype
Argument, to Retrieve the empno Column of Table Employee
For example, to retrieve the empno column of the employee table, you can write a
URL such as one of the following:
-- Generates a contenttype of text/plain
http://machine.oracle.com:8080/oradb/SCOTT/EMP/ROW[EMPNO=7369]/ENAME/text()
-- Generates a contenttype of text/xml
http://machine.oracle.com:8080/oradb/SCOTT/EMP/ROW[EMPNO=7369/ENAME
Description
rowsettag
Changes the default root tag name for the XML document. For
example:
http://machine.oracle.com:8080/oradb/SCOTT/EMP
?rowsettag=Employee
contenttype
transform
Note: When using XPath notation in the URL for this servlet, you
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.
Example 1222 Installing DBUri Servlet Under /dburi/*
For example, to have the servlet installed under /dburi/*, you can run the
following PL/SQL:
declare
doc XMLType;
doc2 XMLType;
begin
doc := dbms_xdb.cfg_get();
select updateXML(doc,
/xdbconfig/sysconfig/protocolconfig/httpconfig/webappconfig/servletconfig/servl
et-mappings/servlet-mapping[servlet-name="DBUriServlet"]/servlet-pattern/text()
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
Part V
Oracle XML DB Repository: Foldering,
Security, and Protocols
Part V of this manual describes Oracle XML DB Repository. It includes how to
version your data, implement and manage security, and how to use the associated
Oracle XML DB APIs to access and manipulate Repository data.
Part V contains the following chapters:
13
Oracle XML DB Foldering
This chapter describes how to access data in Oracle XML DB Repository using
standard protocols such as FTP, HTTP/WebDAV and other Oracle XML DB
Resource APIs. It also introduces you to using RESOURCE_VIEW and PATH_VIEW as
the SQL mechanism for accessing and manipulating Repository data. It includes a
table for comparing Repository operations through the various Resource APIs.
This chapter contains the following sections:
Query-Based Access
13-2
Figure 131 A Typical Folder Tree Showing Hierarchical Structures in Oracle XML
Repository
/
Root Node
/home
/sys
Oracle XML DB System Folders
Do not store your data in /sys
/general
/log
/schemas
/PUBLIC
/schemas
/acls
/po
/acls
/XDB
/SCOTT
/graphics
/schemas
/acls
Oracle
XML DB
folders
(containers)
/xmlns.oracle.com
Directories
(containers)
/xdb
Files or Documents
(non-containers)
architecture.jpg
logo.gif
banner.png
readme.txt
whatsnew.fm
into.doc
maincode.jav
chapter1.xml
po_101.xml
po_Jan02.xml
po_Jan03.xml
Binary
files stored
as BLOBs
11_28_01.txt
Graphics
or
binary.files
stored in
BLOBs
all_owner_acl.xml
all_all_acl.xml
XDBSchema.xsd
XML files
typically stored
object-relationally
can also store
in LOBS
ACL files
are stored
in xdb.xdb$ACL
table
XML files
stored in your
XMLType
tables / views
See Also:
Repository Terminology
The following lists describes terms used in Oracle XML DB Repository:
13-4
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).
See Also: Chapter 18, "Oracle XML DB Resource Security"
Many terms used by Oracle XML DB have common synonyms used in other
contexts, as shown in Table 131.
Table 131 Synonyms for Oracle XML DB Foldering Terms
Synonym
Oracle XML DB
Foldering Term
Usage
Collection
Folder
WebDAV
Directory
Folder
Operating systems
Privilege
Privilege
Permission
Right
Privilege
Various
WebDAV Folder
Folder
Web Folder
Role
Group
Access control
Revision
Version
RCS, CVS
File system
Repository
Operating systems
Hierarchy
Repository
Various
File
Resource
Operating systems
Binding
Link
WebDAV
Context
Folder
JNDI
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.
13-6
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:
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.
Note: Error handling in path name resolution differentiates
between invalid resource names and resources that are not folders
for compatibility with file systems. Since Oracle XML DB resources
are accessible from outside the Repository (using SQL), denying
read access on a folder that contains a resource will not prevent
read access to that resource.
Deleting Resources
Deletion of a link deletes the resource pointed to by the link if and only if that was
the last link to the resource and the resource is not versioned. Links in Oracle XML
DB Repository are analogous to Unix hard links.
See Also: "Deleting Repository Resources: Examples" on
page 15-10
Figure 132 illustrates Oracle XML DB data access options. A high level discussion
of which data access option to select is described in Chapter 2, "Getting Started with
Oracle XML DB", "Oracle XML DB Application Design: b. Access Models" on
page 13-4.
See Also: Table 133, "Accessing Oracle XML DB Repository: API
Options"
Figure 132 Oracle XML DB Repository Data Access Options
Oracle XML DB
Data Access Options
Query-based
Access
Path-based
Access
Use SQL
Use Repository
Available Language
and XMLType APIs
Available Languages
and APIs
PL/SQL
JNDI
FTP
HTTP / WebDav
13-8
Use Windows Explorer to open and access Oracle XML DB folders and
resources the same way you access other directories or resources in the
Windows NT file system, as shown in Figure 133.
Access Repository data using HTTP/WebDAV from an Internet Explorer
browser, such as when viewing Web Folders, as shown in Figure 134.
Figure 134 Accessing Repository Data Using HTTP/WebDAV and Navigational Access From IE
Browser: Viewing Web Folders
Direct database access from file-oriented applications using the database like a
file system
A connection object is established, and the protocol may decide to read part of
the request.
2.
The protocol decides if the user is already authenticated and wants to reuse an
existing session or if the connection must be reauthenticated (generally the
case).
3.
An existing session is pulled from the session pool, or a new one is created.
4.
If authentication has not been provided and the request is HTTP Get or Head,
the session is run as the ANONYMOUS user. If the session has already been
authenticated as the ANONYMOUS user, there is no cost to reuse the existing
session. If authentication has been provided, the database reauthentication
routines are used to authenticate the connection.
5.
6.
If the requested path name maps to a servlet (for HTTP only), the servlet is
invoked using the Java VM. The servlet code writes out the response to a
response stream or asks XMLType instances to do so.
Query-Based Access
Query-Based Access
Oracle XML DB provides two Repository views to enable SQL access to Repository
data:
PATH_VIEW
RESOURCE_VIEW
RESOURCE_VIEW
No link properties
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:
All servlets must be distributable. They must expect to run in different VMs.
WAR and web.xml files are not supported. Oracle XML DB supports a subset
of the XML configurations in this file. An XSL stylesheet can be applied to the
web.xml to generate servlet definitions. An external tool must be used to create
database roles for those defined in the web.xml file.
JSP (Java Server Pages) support can be installed as a servlet and configured
manually.
Only one servlet context (that is, one Web application) is supported.
See Also: Chapter 20, "Writing Oracle XML DB Applications in
Java"
Table 133 lists common Oracle XML DB Repository operations and describes how
these operations can be accomplished using each of the three methods. The table
shows functionality common to three methods. Note that not all the methods are
equally suited to a particular set of tasks.
See Also:
Data Access
Operation
Path-Based Access:
Resource API for
Java/JNDI
Creating a resource
r = new Resource();
jndictx.bind(String oldpath, r)
Query-Based Access:
RESOURCE_VIEW API
Path-Based
Path-Based Access: Resource API Access:
for PL/SQL
Protocols
INSERT INTO PATH_VIEW VALUES (path,
res, linkprop)
HTTP PUT;
FTP PUT
r = jndictx.lookup(String path);
r.setContents(InputStream s);
r.save()
Updating properties
of a resource by path
name
r = jndictx.lookup(String path)
r.setXXX(Object val); r.save()
r = jndictx.lookup(String path);
Unlinking a resource,
deleting it if it is the
last link
r=jndictx.unbind(String path);
N/A
N/A
Moving a resource or
folder
r = jndictx.rename(String oldpath,
String newpath);
WebDAV MOVE;
WebDav COPY;
N/A
r.setACL(XMLType acl);
r.save()
Creating a link to an
existing resource
r = jndictx.lookup(String oldpath);
Getting binary/text
representation of
resource contents by
path name
r =jndictx.lookup(String path);
jndictx.bind(r);
r.getContents();
HTTP PUT;
FTP PUT
N/A
FTP: quote
rm-rf<resource>
FTP RENAME
FTP N/A
Data Access
Operation
Path-Based Access:
Resource API for
Java/JNDI
Query-Based Access:
RESOURCE_VIEW API
Path-Based
Path-Based Access: Resource API Access:
for PL/SQL
Protocols
Getting XMLType
representation of
resource contents by
path name
N/A
N/A
Getting resource
properties by path
name
r = jndictx.lookup(String path);
WebDAVPROPFIND
(depth = 0);
Listing a directory
jndictx.listBindings(String
path);
WebDAV PROPFIND
(depth=1);
FTP LS
Creating a folder
jndictx.bind(String path);
ICall dbms_xdb.createFolder(VARCHAR2)
WebDAVMKCOL;
FTP MKDIR
Unlinking a folder
jndictx.unbind(String path);
DELETEFROMPATH_VIEWWHERE
EQUALS_PATH(res, :path) > 0
HTTP DELETE;FTP
RMDIR
Forcibly deleting a
folder and all links to
it
jndictx.destroySubcontext()
Call dbms_xdb.deleteFolder(VARCHAR2)
Getting a resource
with a row lock
xdb.jndictx.lookup(String path,
boolean rowLocked,
null);
N/A
Putting a WebDAV
lock on the resource
r = jndictx.lookup(String path);
DBMS_XDB.lock(lock_type INTEGER);
WebDAV LOCK;
r.getXXX();
FTP N/A
N/A
FTP: quote rm.rf
<folder>
r.lock(int lock_type);
WebDAV UNLOCK;
QUOTE UNLOCK
Committing changes
java.sql.Connection.commit();
COMMIT;
Automatically
commits at the end of
each request
Rollback changes
java.sql.Connection.rollback();
ROLLBACK;
N/A
</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>
14
Oracle XML DB Versioning
This chapter describes how to create and manage versions of Oracle XML DB
resources. It contains the following sections:
Version control on a resource. You have the option to turn on or off version
control on an Oracle XML DB resource. See "Creating a Version-Controlled
Resource (VCR)".
Updating process of a version-controlled resource. When Oracle XML DB
updates a version-controlled resource, it also creates a new version of the
resource, and this version will not be deleted from the database when the
version-controlled resource is deleted by you. See "Updating a
Version-Controlled Resource (VCR)".
Loading a version-controlled resource is similar to loading any other regular
resource in Oracle XML DB using the path name. See "Creating a
Version-Controlled Resource (VCR)".
Loading a version of the resource. To load a version of a resource, you must first
find the resource object id of the version and then load the version using that id.
The resource object id can be found from the resource version history or from
the version-controlled resource itself. See "Oracle XML DB Resource ID and
Pathname".
Note: In this release, Oracle XML DB versioning supports version
14-2
Description
Version control
Versionable resource
Versionable resource is an Oracle XML DB resource that can be put under version
control.
Version-controlled
resource (VCR).
Version resource.
Version resource is a version of the Oracle XML DB resource that is put under
version control. Version resource is a read-only Oracle XML DB resource. It cannot
be updated or deleted. However, the version resource will be removed from the
system when the version history is deleted from the system.
Checked-out resource.
resid := DBMS_XDB_VERSION.MakeVersioned(/home/SCOTT/versample.html);
-- Obtain the resource
res := DBMS_XDB_VERSION.GetResoureceByResId(resid);
ACL
When a VCR is created the first version resource of the VCR is created, and the VCR
is a reference to the newly-created version.
See "Version Resource or VCR Version" on page 14-4.
Example 142 DBMS_XDB_VERSION.makeVersioned(): Creating a Version-Controlled
Resource (VCR)
14-4
The following example shows how to get the resource id of the new version after
checking in/home/index.html:
-- Declare a variable for resource id
declare
resid DBMS_XDB_VERSION.RESID_TYPE;
res XMLType;
begin
-- Get the id as user checks in.
resid := DBMS_XDB_VERSION.checkin(/home/SCOTT/versample.html);
-- Obtain the resource
res := DBMS_XDB_VERSION.GetResourceByResId(resid);
end;
/
Example 144 Oracle XML DB: Creating and Updating a Version-Controlled Resource
(VCR)
-- Variable definitions.
declare
resid1 DBMS_XDB_VERSION.RESID_TYPE;
resid2 DBMS_XDB_VERSION.RESID_TYPE;
begin
-- Put a resource under version control.
resid1 := DBMS_XDB_VERSION.MakeVersioned(/home/SCOTT/versample.html);
-- Checkout to update contents of the VCR
DBMS_XDB_VERSION.Checkout(/home/SCOTT/versample.html);
-- Use resource_view to update versample.html
update resource_view
set res = sys.xmltype.createxml(
<Resource xmlns="http://xmlns.oracle.com/xdb/XDBResource.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/XDBResource.xsd
http://xmlns.oracle.com/xdb/XDBResource.xsd">
<Author>Jane Doe</Author>
<DisplayName>versample</DisplayName>
<Comment>Has this got updated or not ?? </Comment>
<Language>en</Language>
<CharacterSet>ASCII</CharacterSet>
<ContentType>text/plain</ContentType>
</Resource>)
where any_path = /home/SCOTT/versample.html;
-- Checkin the change
resid2 := DBMS_XDB_VERSION.Checkin(/home/SCOTT/versample.html);
end;
/
-- At this point, you can download the first version with the resource object
ID,
-- resid1 and download the second version with resid2.
-- Checkout to delete the VCR
DBMS_XDB_VERSION.Checkout(/home/SCOTT/versample.html);
-- Delete the VCR
delete from resource_view where any_path = /home/SCOTT/versample.html;
-- Once the delete above is done, any reference
-- to the resource (that is, checkin, checkout,and so on, results in
-- ORA-31001: Invalid resource handle or path name "/home/SCOTT/versample.html"
14-6
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.
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.
Checkout
In Oracle9i Release 2 (9.2), the VCR checkout operation is executed by calling
DBMS_XDB_VERSION.CheckOut(). If you want to commit an update of a
resource, it is a good idea to commit after checkout. If you do not commit right after
checking out, you may have to rollback your transaction at a later point, and the
update is lost.
Example 145 VCR Checkout
For example:
-- Resource /home/SCOTT/versample.html is checked out.
DBMS_XDB_VERSION.CheckOut(/home/SCOTT/versample.html);
Checkin
InOracle9i Release 2 (9.2), the VCR checkin operation is executed by calling DBMS_
XDB_VERSION.CheckIn(). Checkin takes the path name of a resource. This path
name does not have to be the same as the path name that was passed to checkout,
but the checkin and checkout path names must be of the same resource.
For example:
-- Resource /home/SCOTT/versample.html is checked in.
declare
resid DBMS_XDB_VERSION.RESID_TYPE;
begin
resid := DBMS_XDB_VERSION.CheckIn(/home/SCOTT/versample.html);
end;
/
Uncheckout
InOracle9i Release 2 (9.2), uncheckout is executed by calling DBMS_XDB_
VERSION.UncheckOut(). This path name does not have to be the same as the
path name that was passed to checkout, but the checkin and checkout path names
must be of the same resource.
Example 147
VCR Uncheckout
For example:
-- Resource /home/SCOTT/versample.html is unchecked out.
declare
resid DBMS_XDB_VERSION.RESID_TYPE;
begin
resid := DBMS_XDB_VERSION.UncheckOut(/home/SCOTT/versample.html);
end;
/
14-8
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.
Description
FUNCTION
Turns a regular resource whose path name is given into a version controlled
resource. If two or more path names are bound with the same resource, a copy of
the resource will be created, and the given path name will be bound with the
MakeVersioned(pathname newly-created copy. This new resource is then put under version control. All
VARCHAR2) RETURN
other path names continue to refer to the original resource.
MakeVersioned
dbms_xdb.resid_type;
pathname - the path name of the resource to be put under version control.
return - This function returns the resource ID of the first version (root) of the
VCR. This is not an auto-commit SQL operation. It is legal to call MakeVersioned
for VCR, and neither exception nor warning is raised. It is illegal to
makeversioned for folder, version resource, and ACL. An exception is raised if
the resource doesnt exist.
PROCEDURE
Checkout
pathname - the path name of the VCR to be checked out. This is not an
auto-commit SQL operation. Two users of the same workspace cannot checkout
the same VCR at the same time. If this happens, one user must rollback. As a
result, it is a good idea for you to commit the checkout operation before updating
a resource. That way, you do not loose the update when rolling back the
transaction. An exception is raised when:
Checkout(pathname
VARCHAR2);
FUNCTION
Checkin
Checkin(pathname
VARCHAR2) RETURN
dbms_xdb.resid_type;
Description
FUNCTION
Uncheckout
Uncheckout(pathname
VARCHAR2) RETURN
dbms_xdb.resid_type;
return - the resource id of the version before the resource is checked out. This is
not an auto-commit SQL operation. UncheckOut does not have to take the same
path name that was passed to checkout operation. However, the uncheckout
path name and the checkout path name must be of the same resource for the
operations to function correctly. If the resource has been renamed, the new name
must be used to uncheckout because the old name is either invalid or bound with
a different resource at the time being. An exception is raised if the path name
does not exist. If the path name has been changed, the new path name must be
used to checkin the resource.
FUNCTION
GetRoot
GetFirst(vh_id dbms_
xdb.resid_type) RETURN
dbms_xdb.resid_type;
return - first version resource id. An exception is raised if the vh_id is illegal.
14-11
Description
Given a version resource or a VCR, gets the predecessors of the resource by path
name, the path name of the resource.
GetPredecessors
GetPredecessors(pathnam
e VARCHAR2) RETURN
resid_list_type;
GetPredsByResId(resid
dbms_xdb.resid_type)
RETURN resid_list_type;
FUNCTION
Given a version resource or a VCR, gets the predecessors of the resource by resid
(resource id.)
Given a version resource or a VCR, gets the successors of the resource by
pathname, the path name of the resource.
GetSuccessors
GetSuccessors(pathname
VARCHAR2) RETURN
resid_list_type;
GetSuccsByResId(resid
dbms_xdb.resid_type)
RETURN resid_list_type;
FUNCTION
GetResourceByResId
If you have the version ID or path name, you can load it using that ID.
If you dont have its ID, you can call getPredecessors() to get the ID.
Can We Use Version Control for Data Other Than Oracle XML DB Data?
Answer: Only Oracle XML DB resources can be put under version control in this
release.
14-13
15
RESOURCE_VIEW and PATH_VIEW
This chapter describes the SQL-based mechanisms, RESOURCE_VIEW and PATH_
VIEW, used to access Oracle XML DB Repository data. It discusses the SQL
operators UNDER_PATH and EQUALS_PATH used to query resources based on their
path names and the SQL operators PATH and DEPTH that return the resource path
names and depth.
It contains the following sections:
UNDER_PATH
EQUALS_PATH
PATH
DEPTH
RESOURCE
VIEW
SQL
Queries
PATH
VIEW
SQL
Queries
Oracle XML DB
Repository
Oracle XML DB
Resource Table
Content
Properties
Access through:
JNDI
WebDav
FTP
DBMS_XDB
Path-based
Access
15-2
Datatype
-------XMLTYPE
VARCHAR2
Description
------------------------------------------------------A resource in Oracle XML Repository
A path that can be used to access the resource in the
Repository
See Also: Appendix G, "Example Setup scripts. Oracle XML DBSupplied XML Schemas"
Datatype
-------VARCHAR2
XMLTYPE
XMLTYPE
Description
----------------------------Path name of a resource
The resource referred by PATH
Link property
See Also: Appendix G, "Example Setup scripts. Oracle XML DBSupplied XML Schemas"
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.
RESOURCE_VIEW Columns
Resource as Path
an XMLType
PATH_VIEW Columns
Path
Resource as Link as
an XMLType XMLType
15-4
/home
R1
R2
/corp
/role
po_westcoast
po_eastcoast
Target Resource
With PATH_VIEW, to acces the target
resource node;You can create a link.
This provides two access paths R1 or R2
to the target node, for faster access.
RESOURCE_VIEW Example:
select path(1) from resource_view where under_path(res, '/sys',1);
displays one path to the resource:
/home/corp/po_westcoast
PATH_VIEW Example:
select path from path_view;
displays all pathnames to the resource:
/home/corp/po_westcoast
/home/role/po_eastcoast
Get a resource
Create a resource
Delete a resource
Update a resource
Update resources
Delete resources
Get resources
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 154 shows the UNDER_PATH syntax.
Figure 154 UNDER_PATH Syntax
,
UNDER_PATH
levels
column
,
,
correlation_integer
path_string
Description
INTEGER UNDER_PATH(resource_column,
pathname);
15-6
UNDER_PATH
Description
INTEGER UNDER_PATH(resource_column,
depth,
pathname);
INTEGER UNDER_PATH(resource_column,
pathname,
correlation)
INTEGER UNDER_PATH(resource_column,
depth,
pathname,
correlation)
Note that only one of the accessible paths to the resource needs to be
under the path argument for a resource to be returned.
EQUALS_PATH
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 155.
EQUALS_PATH INTEGER EQUALS_PATH( resource_column,pathname);
column
path_string
correlation_integer
)
where:
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:
DEPTH
DEPTH is an ancillary operator that returns the folder depth of the resource under
the specified starting path.
DEPTH INTEGER DEPTH( correlation);
where:
15-8
Example 152 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 153 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 154 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 155 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 156 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....
Therefore you should guarantee that a container is deleted only after its children
have been deleted.
Example 1510 Recursively Deleting Paths
For example, to recursively delete paths under /public), you may want to try the
following:
delete from
(select 1 from resource_view
where UNDER_PATH(res, /public, 1) = 1
order by depth(1) desc);
15-11
</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 151 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 152 on page 15-9.
The query plan for Example 151 will be more optimal than that of
Example 152.
15-13
16
Oracle XML DB Resource API for PL/SQL
(DBMS_XDB)
This chapter describes the Oracle XML DB Resource API for PL/SQL (DBMS_XDB)
used for accessing and managing Oracle XML DB Repository resources and data
using PL/SQL. It includes methods for managing the resource security and Oracle
XML DB configuration.
It contains the following sections:
Overview of DBMS_XDB
16-1
Overview of DBMS_XDB
The DBMS_XDB provides the PL/SQL application developer with an API that
manages:
Link
LockResource
GetLockToken
UnlockResource
16-2
CreateResource
CreateFolder
DeleteResource
2.
If the resource or folder does not need further processing or managing, they are
simply output.
16-3
3.
If the resource or folder need further processing or managing you can apply
any or all of the following methods as listed in Table 161:
Link()
LockResource()
GetLockToken()
UnlockResource()
DeleteResource()
Resource Path
createResource()
createFolder()
Available methods:
link()
lockResource()
getLockToken()
unlockResource()
deleteResource()
16-4
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;
16-5
getAclDocument
ACLCheckPrivileges
checkPrivileges
getprivileges
changePrivileges
setAcl
16-6
1.
2.
You can then use any or all of the DBMS_XDB methods listed in Table 162 to
perform security management tasks:
getAclDocument()
ACLCheckPrivileges()
checkPrivileges()
getPrivileges()
changePrivileges()
setACL()
Available methods:
GetAclDocument()
ACLCheckPrivileges()
checkPrivileges()
changePrivileges()
setAcl()
XMLType instance
or positive integer
or N/A
16-7
commit;
select dbms_xdb.getacldocument(/public/mydocs/emp_scott.xml) from
dual;
declare
r
pls_integer;
ace
xmltype;
ace_data varchar2(2000);
begin
ace_data :=
<ace
xmlns="http://xmlns.oracle.com/xdb/acl.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/acl.xsd
http://xmlns.oracle.com/xdb/acl.xsd
DAV:http://xmlns.oracle.com/xdb/dav.xsd">
<principal>SCOTT</principal>
<grant>true</grant>
<privilege>
<all/>
</privilege>
</ace>;
ace := xmltype.createxml(ace_data);
r := dbms_xdb.changeprivileges(/public/mydocs/emp_scott.xml, ace);
dbms_output.put_line(retval = || r);
commit;
end;
/
select dbms_xdb.getacldocument(/public/mydocs/emp_scott.xml) from
dual;
select dbms_xdb.getprivileges(/public/mydocs/emp_scott.xml) from dual;
call dbms_xdb.deleteresource(/public/mydocs/emp_scott.xml);
call dbms_xdb.deleteresource(/public/mydocs);
commit;
16-8
CFG_get
Argument: None
Return value: XMLType for session configuration information
CFG_refresh
Argument: None
Return value: N/A
CFG_update
To manage the Oracle XML DB configuration you must first retrieve the
configuration instance using cfg_get.
2.
You can then optionally also modify the Oracle XML DB configuration xmltype
instance in order to update it, or simply output the Oracle XML DB
configuration.
3.
To update the Oracle XML DB configuration resource use cfg_update. You need
to either input a new Oracle XML DB configuration xmltype instance or use a
modified version of the current configuration.
4.
16-9
cfg_get
cfg_update
cfg_refresh
RebuildHierarchicalIndex
Argument: None
Return value: N/A
Remove index
entries from
xdb.xdb$h_index
using: DELETE
16-11
commit;
execute dbms_xdb.RebuildHierarchicalIndex;
17
Oracle XML DB Resource API for Java/JNDI
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:
17-2
Oracle XML DB Resource API for Java/JNDI allows Java applications in the
server or client to access and manipulate objects stored in Oracle XML DB
Repository.
JNDI is flexible enough to allow an object to be returned for a given path
without imposing the limitations of current file systems on the interface. The
object returned is commonly a Java bean with methods for each element and
attribute of the XML element loaded.
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).
Note: In this release, Oracle XML DBs implementation of JNDI
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"
Resource manipulation. You can create, update, remove, rename, and move an
Oracle XML DB resource, and look up an Oracle XML DB resource by name.
Folder manipulation. You can create, update, remove, rename, move, and list
the contents of a folder.
Retrieve contents of the Oracle XML DB resource. Using Oracle extensions, you
can update the properties of the Oracle XML DB resource.
Save contents to the database.
Use the Java API for XMLType to access and modify parts of the XMLType
object.
Use the save() method to write changes to the database.
Use the JNDI bind() family to bind the Oracle XML DB resource to a new
path name.
The Oracle XML DB Resource API for Java includes a set of subinterfaces that
indicate resource type information as follows:
17-4
Oracle XML DB Resource API for Java includes interfaces for objects such as
workspaces, branches, and baselines (as defined by the WebDAV versioning
specification). Context and Resource are Java bean-based accessors. Since they
are XMLType subclasses, they can implement the Java API for XMLType.
JNDI SPI resides in Oracle9i database in the internal SYS schema in the package.
The package xdb.jar.xdb.jar can also be used by applications for further
development. Applications developed to use Oracle XML DB Resource API for
Java/JNDI must also be loaded in Oracle9i database in order to use the JNDI API.
Description
PROVIDER_URL
INITIAL_CONTEXT_FACTORY
Table 171 Oracle XML DB Resource API for Java/JNDI: Parameters (Cont.)
Parameter Name
Description
XDB_RESOURCE_TYPE
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:
17-6
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.
Operation
Path
Environment variables
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.
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.
A bean
oracle.xdb.XMLType
The object type is dependent on the document stored and the environment
returned.
17-8
Table 172 Oracle XML DB Resource API for Java: JNDI Context Input Parameters
JNDI Input Parameters Name
Valid Values
Description
Context.PROVIDER_URL
Context.INITIAL_CONTEXT_FACTORY
oracle.xdb.spi.XDBContextF
actory
XDBContext.RETURN_OBJECT_TYPE
Resource, contents
XDBContext.COUNTRY
XDBContext.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.
Bean: Generated as a result of the lookup operation if the object being looked
up is an XML schema-based XML document and a bean for the XML schema
has been generated.
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
Here is a way to find out properties of an Oracle XML DB purchase order object
using JNDI alone. JNDI allows properties to be looked up using a string property
name. This API is useful when the properties to be retrieved are not known at
compile time, as well as to provide the same interface as JNDI service providers
other than Oracle XML DB, like an LDAP directory.
17-11
Example 172 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();
Here is a Java Bean version of the DOM example. It uses JNDI to locate the object
with the same setup:
Context
PurchaseOrder
Boolean
String
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 174 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();
17-13
18
Oracle XML DB Resource Security
This chapter describes Access Control Lists (ACL) based security mechanism for
Oracle XML DB resources. It describes how to create ACLs, set and change ACls on
resources, and how ACL security interacts with other database security
mechanisms.
This chapter contains the following sections:
18-2
Database users.
ACE (access control entry): Part of an ACL that grants or denies access to a
particular principal. An ACL consists of a list of ACEs where ordering is
irrelevant. There can be only one grant ACE and one deny ACE for a particular
principal in a single ACL.
Note: Many grant ACEs (or deny ACEs) may apply to a particular
Access control list (ACL): A list of access control entry elements, with the
element name ace, that defines access control to a resource. An ACE either
grants or denies privileges for a principal.
Note: ACLs are stored as Oracle XML DB resources, so they also
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:
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.
18-4
18-6
Element
Description
<principal>
<grant>
<privilege>
When an ACL is stored in Oracle XML DB, the aggregate privileges retain their
identity, that is, they are not decomposed into the corresponding leaf privileges. In
WebDAV terms, these are non-abstract aggregate privileges, so they can be used in
ACEs.
Atomic Privileges
Table 182 lists the atomic privileges supported by Oracle XML DB.
Table 182 Atomic Privileges
Privilege Name
Description
Database
Counterpart
read-properties
SELECT
read-contents
SELECT
update
UPDATE
link
INSERT
unlink
DELETE
linkto
N/A
unlinkfrom
N/A
read-acl
SELECT
write-acl-ref
UPDATE
update-acl
UPDATE
resolve
SELECT
dav:lock
UPDATE
dav:unlock
UPDATE
dav: prefix are part of the WebDAV namespace and others are part
of the Oracle XML DB ACL namespace, which is:
http://xmlns.oracle.com/xdb/acl.xsd
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 183 lists the aggregate privileges defined by Oracle XML DB, along with the
atomic privileges of which they are composed.
Table 183 Aggregate Privileges
Aggregate Privilege
Name
Atomic Privileges
all
dav:all
dav:read
dav:write
dav:read-acl
read-acl
dav:write-acl
write-acl-ref, update-acl
Table 184 shows the privileges required for some common operations on resources
in Oracle XML DB Repository. The Privileges Required column assumes that you
already have resolve privilege on container C and all its parent containers, up to
the root of the hierarchy.
Table 184 Privileges Needed for Operations on Oracle XML DB Resources
Operation
Description
Privileges Required
CREATE
DELETE
UPDATE
update on R
18-8
Table 184 Privileges Needed for Operations on Oracle XML DB Resources (Cont.)
Operation
Description
Privileges Required
GET
read-properties, read-contents on R
SET_ACL
dav:write-acl on R
LIST
read-properties on C, read-properties on
resources in C. Only those resources on which
the user has read-properties privilege are
listed.
Each principal will have two individual ACEs at most, one for granting
privileges and one for denying privileges.
Each ACL has a list of ACEs. An ACE has the following elements:
Named ACLs also have a name attribute and an optional type restrictor, for
example, http://xmlns.oracle.com/xdb/XDBDemo.xsd#PurchaseOrder,
that specifies that the ACL may only be applied to instances of that XML element
(and elements in a substitution group with that element). Note that a privilege that
is neither granted nor denied to a user is assumed to be denied.
To evaluate an ACL, the database collects the list of ACEs applying to the user
logged into the current database session. The list of currently active roles for the
given user is maintained as a part of the session and is used to match ACEs along
with the current user.
To check if a user has a certain privilege, you need to know the ID of the ACL and
the owner of the object being secured. The Oracle XML DB hierarchy automatically
associates an ACL ID and owner with an object that is mapped into its file system
(they are stored in a table in the Oracle XML DB schema).
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:
The owner of the folder is changed to the user, by updating the resource_view.
You can also make the user's folder completely private by changing the ACL to
another system ACL, such as, all_owner_acl.xml
connect system/manager
Rem Create an Oracle XML DB administrator user (has XDBADMIN role)
grant connect, resource, xdbadmin to xdbadmn identified by xdbadmn;
Rem Create Oracle XML DB user
grant connect, resource to xdbuser identified by xdbuser;
conn xdbadmn/xdbadmn
It returns an XMLType instance of <acl> element representing the ACL for the
resource at res_path.
ACL insertion: Can be at most one grant ACE and one deny ACE for a
particular principal in an ACL
ACL deletion: If a resource is currently using the ACL, the ACL cannot be
deleted.
19
Using FTP, HTTP, and WebDAV Protocols
This chapter describes how to access Oracle XML DB Repository using FTP,
HTTP/WebDAV protocols. It contains the following sections:
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.
19-2
Java"
Figure 191 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
Figure 191 Oracle XML DB Architecture: Protocol Server
FTP
Client
FTP
Server
Network
HTTP
WebDAV
Client
Protocol
Server
Foldering
Configuration
Management
HTTP /
WebDAV
Server
ACL
Security
DB".
For examples of the usage of these parameters, see the configuration file
/xdbconfig.xml, in Oracle XML DB Repository.
See Also: Appendix A, "Installing and Configuring Oracle XML
DB"
Table 191 Common Protocol Configuration Parameters
19-4
Parameter
Description
extension-mappings/mime-mappings
extension-mappings/lang-mappings
extension-mappings/encoding-mappings
Description
extension-mappings/charset-mappings
session-pool-size
/xdbconfig/sysconfig/call-timeout
session-timeout
/xdbconfig/sysconfig/default-lock-timeout
Description
ftp-port
ftp-protocol
session-timeout
Description
http-port
Description
http-protocol
session-timeout
server-name
max-header-size
max-request-body
webappconfig/welcome-file-list
Name resolution
ACL-based security
The ability to store and retrieve any content. Oracle XML DB Repository can
store both binary data input through FTP and XML schema-based documents.
See Also:
19-6
http://rfc.sunsite.dk/rfc/rfc959.html
http://256.com/gray/docs/rfc2616/
http://www.faqs.org/rfcs/rfc2518.html
If the incoming XML document specifies an XML schema, the Oracle XML DB
storage to use is decided by that XML schema. This functionality comes in
handy when you need to store XML documents object-relationally in the
database, using simple protocols like FTP or WebDAV instead of having to
write SQL statements.
If the incoming XML document is not XML schema-based, it is stored as a
binary document.
Record-oriented files, for example, only the FILE structure of the STRU
command is supported. This is the most widely used structure for transfer of
files. It is also the default specified by the specification. Structure mount is not
supported.
Append.
Abort.
19-8
byte-range headers
Java"
Access Control
WebDAV is a set of extensions to the HTTP protocol that allow you to edit or
manage your files on remote Web servers. WebDav can also be used, for example,
to:
Lock-NULL resources create actual zero-length resources in the file system, and
cannot be converted to folders.
Depth-infinity locks
2.
3.
Click on Next.
5.
6.
Click on Finish.
You can now access Oracle XML DB Repository just like you access any Windows
folder.
20
Writing Oracle XML DB Applications in Java
This chapter describes how to write Oracle XMl DB applications in Java. It includes
design guidelines for writing Java applications including servlets, and how to
configure the Oracle XML DB servlets.
It contains these sections:
Because Java in the database runs in the context of the database server process, the
methods of deploying your Java code are restricted to one of the following ways:
You can run Java code as a stored procedure invoked from SQL or PL/SQL or
Stored procedures are easier to integrate with SQL and PL/SQL code, and require
using Oracle Net Services as the protocol to access Oracle9i database.
Servlets work better as the top level entry point into Oracle9i database, and require
using HTTP as the protocol to access Oracle9i database.
Which Oracle XML DB APIs Are Available Inside and Outside the Database?
In this release, some of Oracle XML DB APIs are only available to applications
running in the server. Table 201 illustrates which Oracle XML DB APIs are
available in each architecture in this release. The NO fields will become YES in
a forthcoming release.
Oracle XML DB APIs AVailable Inside and Outside Oracle9i Database
Table 201 Oracle XML DB APIs Inside and Outside Oracle9i Database
20-2
YES
YES
XMLType class
YES
YES
YES
YES
NO
YES
NO
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.
The Servlet WAR file (web.xml) is not supported in its entirety. Some web.xml
configuration parameters must be handled manually. For example, creating
roles must be done using the SQL CREATE ROLE command.
Only one ServletContext (and one web-app) is currently supported.
Stateful servlets (and thus the HttpSession class methods) are not supported.
Servlets must maintain state in the database itself.
Description
Comment
auth-method
Java
no
--
charset
Oracle
yes
For example:
ISO8859, UTF8
charset-mapping
Oracle
yes
--
context-param
Java
no
description
Java
yes
display-name
Java
yes
20-4
Table 202 XML Elements Defined for Servlet Deployment Descriptors (Cont.)
XML Element Name Defined By Supported?
Description
Comment
distributable
Java
no
errnum
Oracle
yes
error-code
Java
yes
error-page
Java
yes
Can be specified
through an HTTP
error, an uncaught
Java exception, or
through an uncaught
Oracle error message
exception-type
Java
yes
--
extension
Java
yes
--
facility
Oracle
yes
form-error-page
Java
no
form-login-config
Java
no
form-login-page
Java
no
icon
Java
Yes
init-param
Java
Yes
jsp-file
Java
No
Not supported
lang
Oracle
Yes
lang-mapping
Oracle
Yes
--
large-icon
Java
Yes
--
Table 202 XML Elements Defined for Servlet Deployment Descriptors (Cont.)
XML Element Name Defined By Supported?
Description
Comment
load-on-startup
Java
Yes
--
location
Java
Yes
login-config
Java
No
mime-mapping
Java
Yes
--
mime-type
Java
Yes
For example:
text/xml or
application/octet-str
eam
OracleError
Oracle
Yes
--
param-name
Java
Yes
param-value
Java
Yes
Value of a parameter
--
realm-name
Java
No
role-link
Java
Yes
Refers to a database
role name. Make sure
to capitalize by
default!
role-name
Java
Yes
security-role
Java
No
security-role-ref
Java
Yes
servlet
Java
Yes
20-6
--
Table 202 XML Elements Defined for Servlet Deployment Descriptors (Cont.)
XML Element Name Defined By Supported?
Description
Comment
servlet-class
Java
Yes
--
servlet-language
Oracle
Yes
Either Java, C, or
PL/SQL. Currently,
only Java is supported
for customer-defined
servlets.
servlet-mapping
Java
Yes
servlet-name
Java
Yes
servlet-schema
Oracle
Yes
session-config
Java
No
HTTPSession is not
supported
session-timeout
Java
No
HTTPSession is not
supported
small-icon
Java
Yes
--
taglib
Java
No
taglib-uri
Java
No
taglib-location
Java
No
url-pattern
Java
Yes
Table 202 XML Elements Defined for Servlet Deployment Descriptors (Cont.)
XML Element Name Defined By Supported?
Description
Comment
web-app
Java
No
welcome-file
Java
Yes
welcome-file-list
Java
Yes
--
Note:
20-8
1.
If a connection has not yet been established, Oracle listener hands the
connection to a shared server dispatcher.
2.
When a new HTTP request arrives, the dispatcher wakes up a shared server.
3.
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.
6.
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"
Methods
HttpServletRequest
getSession(), isRequestedSessionIdValid()
HttpSession
ALL
HttpSessionBindingListener
ALL
20-11
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.
Note: You will not be allowed to actually delete the
Part VI
Oracle Tools that Support Oracle XML DB
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:
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:
21-1
21-2
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.
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.
See Also: "Managing XML Schema and Related Database
Objects" on page 21-27.
Oracle XML DB is now ready for you to insert conforming XML documents.
21-3
Figure 211 Managing Oracle XML DB with Enterprise Manager: Main Tasks
Oracle Enterprise Manager
Oracle XML DB Management
Configure
Oracle XML DB
- xdbconfig.xml
Create and
Manage
Resources
- including
resource
security
Manage
XML Schema
- Create tables and
views based on XML
Schema
- Create XMLType, tables
- Create tables with
XMLType columns
21-4
21-5
21-6
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 213 and See Figure 214.
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.
21-7
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:
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.
21-8
21-9
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
21-11
Category: FTP
ftp-log-level: The level of logging for FTP error and warning conditions.
Category: HTTP
http-log-level: The level of logging for HTTP error and warning conditions.
Figure 215 Enterprise Manager: Oracle XML DB Resources Tree Showing Resources
Folder Selected
21-13
21-15
Last Modifier - the name of the user who last modified the resource
Modified - the date and time that the resource was last changed
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 218.
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.
3.
Click the Revert button to abandon any changes you have made to the File
Name field.
Figure 218 Enterprise Manager: Individual Oracle XML DB Resource - Security Page
21-17
You can perform the following Oracle XML DB tasks from the Enterprise Manager
Content Menu:
Create Resource
Figure 2110 shows how you can use the Create XML DB Resource dialog box to
create an XML DB resource container or 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 2110 Enterprise Manager: Create Oracle XML DB Resource Dialog Box
21-19
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.
See Also: "Enterprise Manager and Oracle XML DB: ACL
Show Contents
Figure 2112 is an example of a Show Contents dialog box. It displays the contents
of the selected resource file.
Figure 2112 Enterprise Manager: Show Contents Menus of Individual Oracle XML
DB Resource
Show Grantee
Figure 2111 shows the Show Grantee of XML DB Resource dialog box. It displays
a list of all granted privileges on a 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.
21-21
To view or modify user (or role) security: In the Navigator, under the Oracle
XML DB database in question > Security >Users >user (or > Security > Roles >
role). In the detail view, select the XML tag. See Figure 2114. This user security
option is described in more detail in "Granting and Revoking User Privileges
with User > XML Tab" on page 21-23.
To view or modify a resources security: Select the individual resource node
under the Resources folder in the left navigation panel. Select the Security tag
in the detail view. See Figure 2115.
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.
21-23
Figure 2114 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.
Atomic Privileges
all
read-properties
read-contents
update
read-acl
21-25
write-acl-Ref
update-acl
linkto
unlinkfrom
dav:lock
dav:unlock
dav:read-acl
Aggregate Privileges
dav:write-acl
21-27
Schema Owners. Under the individual XML schema owners, the tree lists the
XML schemas owned by the owner(s). Here you can see:
http://xmlns.oracle.com/xdb/XDBResource.xsd
http://xmlns.oracle.com/xdb/XDBSchema.xsd
http://xmlns.oracle.com/xdb/XDBStandard.xsd
Top level elements. Under each XML schema, the tree lists the top level
elements. These elements are used to create the XMLType tables, tables with
XMLType columns, and views. For example, Figure 2116 shows top level
elements servlet and LINK. The number and names of these elements are
dictated by the relevant XML schema 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:
*
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.
21-29
21-31
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:
Options Page
From the Options page you can select the following options:
See Figure 2119. Press Create from either the General Tab or Options Tab to register
this XML schema.
21-33
Creating Tables
You have two main options when creating tables:
Creating Views
To create an XMLType view, see "Creating a View Based on XML Schema" on
page 21-39.
Store as defined by the XML schema. When you select this option, hidden
columns are created based on the XML schema definition annotations. Any
SELECTs or UPDATEs on these columns are optimized.
Store as CLOB. When you select CLOB the LOB Storage tab dialog appears.
Here you can customize the CLOB storage. See Figure 2121.
21-35
From the Create Table property sheet, enter the desired name of the table you
are creating on the General page.
2.
Select the table owner from the drop-down list Schema. Leave Tablespace at
the default setting.
3.
4.
Enter the Name. Enter the Datatype; select XMLType from the drop-down list.
The XMLType Options dialog window appears. See Figure 2123.
21-37
Figure 2122 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.
Store as CLOB. When you select CLOB the LOB Storage tab dialog
appears. Here you can customize the CLOB storage.
Figure 2123 Enterprise Manager: Creating Tables With XMLType Column - XMLType
Options
Enter the desired view name. Under Schema, select the view owner from the
drop-down list.
2.
Enter the SQL statement text in the Query Text window to create the view.
Select the Advanced tab. See Figure 2125.
From here you can select Force mode
3.
Select the As Object option. The view can be set to Read Only or With Check
Option.
21-39
4.
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.
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...
21-41
Provide the owner and name of the index. Under Name enter the name of the
required index. Under Schema select the owner of the index from the
drop-down list.
2.
3.
Under the lower Schema select the table owner from the drop-down list.
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.
21-43
22
Loading XML Data into Oracle XML DB
This chapter describes how XML datacan be loaded into Oracle XML DB using
SQL*Loader.
It contains the following sections:
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
To load internal LOBs (BLOBs, CLOBs, and NCLOBs) or XML columns from a
primary datafile, you can use the following standard SQL*Loader formats:
22-2
Delimited fields
A single LOB field into which the entire contents of a file can be read
All of the previously mentioned field types can be used to load XML columns.
22-4
Part VII
XML Data Exchange Using Advanced
Queueing
Part VII of this manual describes XML data exchange using Oracle Advanced
Queueing (AQ) and the AQs XMLType support. Part VII contains the following
chapter:
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?
IDAP Architecture
What Is AQ?
What Is AQ?
Oracle Advanced Queuing (AQ) provides database integrated message queuing
functionality. AQ:
Message management
Message transformation
This is an intra- and inter-business scenario where XML messages are passed
asynchronously among applications using AQ.
23-2
Figure 231 shows XML payload messages transported using AQ in the following
ways:
The figure also shows that AQ clients can access data using OCI, Java, or PL/SQL.
Internet Users
XML-Based Internet
Transport
(HTTP(s), SMTP)
OCI, PL/SQL,
Java clients
Oracle
Internet Access
Rules and
Transformations
Advanced
queues
Internet
Propagation
MQ Series
Internet
Propagation
(Oracle
Net)
Rules and
Transformations
Rules and
Transformations
Advanced
queues
Advanced
queues
Global Agents,
Global Subscriptions,
Global Events
23-4
Advantages of Using AQ
AQ provides the flexibility of configuring communication between different
applications.
All request and response tags are scoped in the SOAP namespace.
The sender includes namespaces in IDAP elements and attributes in the SOAP
body.
IDAP Architecture
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
See Also: Oracle9i Application Developers Guide - Advanced
Queuing
IDAP Architecture
Figure 232 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
Messages
over HTTP
Oracle9i
Server
AQ
Servlet
AQ Client
AQ Queue
Web Server
23-6
IDAP Architecture
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 231 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);
IDAP Architecture
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 Developers Guide - Advanced Queuing the section on Creating
Transformations in Chapter 8.
Example 232 Using AQ and XMLType Queue Payloads: Dequeuing Messages
23-8
=>
=>
=>
=>
=>
'OS.OS_bookedorders_que',
dopt,
mprop,
deq_order_data,
deq_msgid);
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.
Example 233 PL/SQL (DBMS_AQADM Package)
The following calls create the priority queues for the Order Entry application.
/* Create a priority queue table for OE: */
EXECUTE dbms_aqadm.create_queue_table( \
queue_table
=> 'OE_orders_pr_mqtab', \
sort_list
=>'priority,enq_time', \
comment
=> 'Order Entry Priority \
MultiConsumer Orders queue table',\
multiple_consumers => TRUE, \
queue_payload_type => 'BOLADM.order_typ', \
compatible
=> '8.1', \
primary_instance
=> 2, \
secondary_instance => 1);
EXECUTE dbms_aqadm.create_queue ( \
queue_name
queue_table
=> 'OE_bookedorders_que', \
=> 'OE_orders_pr_mqtab');
Assume that a customer, John, wants to send an enqueue request using SOAP. The
XML message will have the following format.
<?xml version="1.0"?>
<Envelope xmlns= "http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<AQXmlSend xmlns = "http://ns.oracle.com/AQ/schemas/access">
<producer_options>
<destination>OE.OE_bookedorders_que</destination>
</producer_options>
<message_set>
<message_count>1</message_count>
<message>
<message_number>1</message_number>
<message_header>
<correlation>ORDER1</correlation>
<priority>1</priority>
<sender_id>
<agent_name>john</agent_name>
</sender_id>
</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.
See Also:
You can either define an object type with (CLOB, RAW,...) attributes, and store it
as a single message
You can use the AQ message grouping feature and store it in multiple
messages. But the message properties will be associated with a group. To use
the message grouping feature, all messages must be the same payload type.
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
message. Refer to the latest AQ document, Oracle9i Application Developers Guide Advanced Queuing to get specific details and see more examples.
If you store XML as CLOBs then you can definitely search it using Oracle9i Text
(aka interMedia Text), but this only helps you find a particular message that
matches a criteria.
If you need to do aggregation operations over the metadata, view the metadata
from existing relational tools, or use normal SQL predicates on the metadata,
then having it only stored as XML in a CLOB is not going to be good enough.
You can combine Oracle9i Text XML searching with some amount of redundant
metadata storage as factored out columns and use SQL statements that combine
normal SQL predicates with the Oracle9i Text CONTAINS() clause to have the best
of both.
See Also: Chapter 7, "Searching XML Data with Oracle Text".
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:
A
Installing and Configuring Oracle XML DB
This appendix describes the ways you can manage and configure your Oracle XML
DB applications. It contains the following sections:
A-1
The Oracle XML DB tablespace holds the data that is stored in Oracle XML DB
Repository. This includes data that is stored in the Repository using:
It is possible to store data in tables outside this tablespace and access that data
through the Repository by having REFs to that data stored in the tables in this
tablespace.
Warning: The Oracle XML DB tablespace should not be
A-2
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.
Note: If the Listener is running on a non-standard port (for
example, not 1521) then in order for the protocols to register with
the correct listener the init.ora file must contain a local_
listener entry. This references a TNSNAME entry that points to
the correct listener. After editing the init.ora parameter you
must regenerate the SPFILE entry using CREATE SPFILE.
For example:
catqm.sql change_on_install XDB TEMP
Note: Make sure that the database is started with Oracle9i Release
Post Installation
After the manual installation, carry out these tasks:
1.
A-3
2.
3.
Enterprise Manager"
Oracle XML DB is managed through a configuration resource stored in Oracle XML
DB Repository, /sys/xdbconfig.xml.
The Oracle XML DB configuration file is alterable at runtime. Simply updating the
configuration file, causes a new version of the file to be generated. At the start of
A-4
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.
A-5
<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:
A-6
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>
A-7
</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>
A-8
<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.
A-9
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.
You have modified the configuration and now want the session to pick up the
latest version of the configuration information.
It has been a long running session, the configuration has been modified by a
concurrent session, and you want the current session to pick up the latest
version of the configuration information.
If updates to the configuration are made, Oracle XML DB Configuration API is
aware of them.
See Also: Oracle9i XML API Reference - XDK and Oracle XML DB
B
XML Schema Primer
This appendix includes introductory information about the W3C XML Schema
Recommendation. It contains the following sections:
Simple Types
Element Content
Annotations
Attribute Groups
Nil Values
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
B-2
</billTo>
<comment>Hurry, my lawn is going wild!</comment>
<items>
<item partNum="872-AA">
<productName>Lawnmower</productName>
<quantity>1</quantity>
<USPrice>148.95</USPrice>
<comment>Confirm this is electric</comment>
</item>
<item partNum="926-AA">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
</item>
</items>
</purchaseOrder>
The complex types in the instance document, and some simple types, are defined in
the purchase order schema. The other simple types are defined as part of XML
Schema's repertoire of built-in simple types.
B-4
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="partNum" type="SKU" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<!-- Stock Keeping Unit, a code for identifying products -->
<xsd:simpleType name="SKU">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
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:
Attribute declarations
Element declarations
Secondary Components
The secondary components, which must have names, are as follows:
Identity-constraint 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
B-6
Complex types, allow elements in their content and may carry attributes
Simple types, cannot have element content and cannot carry attributes.
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.
Be called name, street, city, state, and zip as specified by the values of
the declarations' name attributes
Appear in the same sequence (order) in which they are declared. The first four
of these elements will each contain a string, and the fifth will contain a number.
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>
B-8
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:
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.
Note: The concepts of a fixed value and a default value are
Attributes
Notes
required, -, -
(1, 1) 37, -
required, 37, -
n/a
(0, 1) -, -
optional, -, -
(0, 1) 37, -
optional, 37, -
(0, 1) -, 37
optional, -, 37
(0, 2) -, 37
n/a
(0, 0) -, -
prohibited, -, -
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.
Note: This rationale also allows a comment element to appear as
Naming Conflicts
The preceding section described how to:
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.
Simple Types
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 B2 lists all the simple types built
into XML Schema, along with examples of the different types.
Table B2 Simple Types Built into XML Schema
Simple Type
string
--
normalizedString
token
byte
-1, 126
unsignedByte
0, 126
base64Binary
GpM7
--
hexBinary
0FB7
--
integer
positiveInteger
1, 126789
negativeInteger
-126789, -1
nonNegativeInteger
0, 1, 126789
nonPositiveInteger
-126789, -1, 0
int
-1, 126789675
unsignedInt
0, 1267896754
long
-1, 12678967543233
Simple Types
unsignedLong
0, 12678967543233
short
-1, 12678
unsignedShort
0, 12678
decimal
float
equivalent to
single-precision 32-bit
floating point, NaN is
not a number. Note: 2
double
equivalent to
double-precision 64-bit
floating point. Note: 2\
boolean
true, false 1, 0
--
time
13:20:00.000, 13:20:00.000-05:00
dateTime
1999-05-31T13:20:00.000-05:00
duration
P1Y2M3DT10H30M12.3S
date
1999-05-31
gMonth
--05--
May, Notes: 2, 5
gYear
1999
1999, Notes: 2, 5
gYearMonth
1999-02
gDay
---31
gMonthDay
--05-31
Name
shipTo
QName
po:USAddress
Simple Types
NCName
USAddress
XML Namespace
NCName, that is,
QName without the
prefix and colon
anyURI
http://www.example.com/,
http://www.example.com/doc.ht
ml#ID5
--
language
en-GB, en-US, fr
ID
--
IDREF
--
IDREFS
--
ENTITY
--
ENTITIES
--
NOTATION
--
NMTOKEN
US,Brsil
NMTOKENS
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.
Simple Types
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}"
Simple Types
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 B3. Atomic types, list types, and the
union types described in the next section are collectively called simple types. The
Simple Types
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:
Simple Types
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 Amrique Latine
Even though "Amrique Latine" may exist as a single string outside of the list,
when it is included in the list, the whitespace between Amrique and Latine
effectively creates a fourth item, and so the latter example will not conform to the
3-item list type.
Union Types
Atomic types and list types enable an element or an attribute value to be one or
more instances of one atomic type. In contrast, a union type enables an element or
attribute value to be one or more instances of one type drawn from the union of
multiple atomic and list types. To illustrate, we create a union type for representing
American states as singleton letter abbreviations or lists of numeric codes. The
zipUnion union type is built from one atomic type and one list type:
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>
Element Content
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:
Element Content
</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:
Element Content
<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"/>
Element Content
<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
Annotations
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.
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
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:
Attribute Groups
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<!-- attributeGroup replaces individual declarations -->
<xsd:attributeGroup ref="ItemDelivery"/>
</xsd:complexType>
</xsd:element>
<xsd:attributeGroup name="ItemDelivery">
<xsd:attribute name="partNum" type="SKU" use="required"/>
<xsd:attribute name="weightKg" type="xsd:decimal"/>
<xsd:attribute name="shipBy">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="air"/>
<xsd:enumeration value="land"/>
<xsd:enumeration value="any"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:attributeGroup>
Using an attribute group in this way can improve the readability of schemas, and
facilitates updating schemas because an attribute group can be 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.
The XML Schema language serves a similar purpose to DTDs, but it is more flexible
in specifying XML document constraints and potentially more useful for certain
applications.
XML Example
Consider the XML document:
<?xml version="1.0">
<publisher pubid="ab1234">
<publish-year>2000</publish-year>
<title>The Cat in the Hat</title>
<author>Dr. Seuss</author>
<artist>Ms. Seuss</artist>
<isbn>123456781111</isbn>
</publisher>
DTD Example
Consider a typical DTD for the foregoing XML document:
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
...
</complexType>
</element></schema>
DTD Limitations
DTDs, also known as XML Markup Declarations, are considered deficient in
handling certain applications which include the following:
Exchange of metadata
E-commerce
Inter-database operations
DTD Features
Built-In Datatypes
XML schemas specify a set of built-in datatypes. Some DTDs do not support datatypes other than character
of them are defined and called primitive datatypes, and strings.
they form the basis of the type system: string, boolean,
float, decimal, double, duration, dateTime, time, date,
gYearMonth, gYear, gMonthDat, gMonth, gDay,
Base64Binary, HexBinary, anyURI, NOTATION,
QName
Others are derived datatypes that are defined in terms
of primitive types.
User-Defined Datatypes
Users can derive their own datatypes from the built-in The publish-year element in the DTD example cannot
datatypes. There are three ways of datatype derivation: be constrained further.
restriction, list, and union. Restriction defines a more
restricted datatype by applying constraining facets to
the base type, list simply allows a list of values of its
item type, and union defines a new type whose value
can be of any of its member types.
For example, to specify that the value of publish-year
type to be within a specific range:
--
<element name="publish-year">
<simpleType>
<restriction base="short"
<minInclusive value="1970"/
<maxInclusive value="2000"/>
</restriction>
</simpleType>
</element>
Constraining facets are: length, minLength, maxLength,
pattern, enumeration, whiteSpace, maxInclusive,
maxExclusive, minInclusive, minExclusive, totalDigits,
fractionDigits
Note that some facets only apply to certain base types.
DTD Features
--
DTD Features
minOccurs, maxOccurs
Identity Constraints
None.
Streams of bytes
</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>
C
XPath and Namespace Primer
This appendix describes introductory information about the W3C XPath
Recommendation, Namespace Recommendation, and the Information Set (infoset).
It contains the following sections:
Location Paths
Introducing the W3C XML Path Language (XPath) 2.0 Working Draft
C-2
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.
String Functions
Boolean functions
Number functions
Both XSLT and XPointer extend XPath by defining additional functions; some of
these functions operate on the four basic types; others operate on additional
data types defined by XSLT and XPointer.
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.
C-4
Location Paths
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.
Location Paths
Description
child::para
child::*
child::text()
child::node()
attribute::name
attribute::*
nodedescendant::para
ancestor::div
ancestor-or-self::div
descendant-or-self::para
self::para
child::chapter/descendant::para
child::*/child::para
/descendant::para
/descendant::olist/child::item
Selects all the item elements that have an olist parent and that
are in the same document as the context node
child::para[position()=1]
child::para[position()=last()]
child::para[position()=last()-1]
Selects the last but one para child of the context node
child::para[position()>1]
Selects all the para children of the context node other than the
first para child of the context node
following-sibling::chapter[position()=1]
preceding-sibling::chapter[position()=1]
C-6
Location Paths
Description
/descendant::figure[position()=42]
/child::doc/child::chapter[position()=5]/child::section
[position()=2]
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]
child::*[self::chapter or self::appendix][position()=last()]
Description
para
text()
@name
@*
para[1]
para[last()]
*/para
/doc/chapter[5]/section[2]
Location Paths
Description
chapter//para
//para
//olist/item
.//para
..
../@lang
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
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.
C-8
Location Paths
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
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 ::= '@'?
::=
RelativeLocationPath
| AbsoluteLocationPath
::=
'/' RelativeLocationPath?
| AbbreviatedAbsoluteLocationPath
::=
Step
| RelativeLocationPath '/' Step
| AbbreviatedRelativeLocationPath
Nodes
The tree contains nodes. There are seven types of node:
Root Nodes
Element Nodes
Text Nodes
Attribute Nodes
Namespace 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.
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
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.
A defaulted attribute is treated the same as a specified attribute. If an attribute was
declared for the element type in the DTD, but the default was declared as
#IMPLIED, and the attribute was not specified on the element, then the element's
attribute set does not contain a node for the attribute.
Some attributes, such as xml:lang and xml:space, have the semantics that they
apply to all elements that are descendants of the element bearing the attribute,
unless overridden with an instance of the same attribute on another descendant
element. However, this does not affect where attribute nodes appear in the tree: an
element has attribute nodes only for attributes that were explicitly specified in the
start-tag or empty-element tag of that element or that were explicitly declared in the
DTD with a default value.
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
Note: An attribute xmlns="" "undeclares" the default
namespace.
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.
Note: For element nodes and root nodes, the string-value of a
node is not the same as the string returned by the DOM nodeValue
method.
Expanded-Name
Some types of node also have an expanded-name, which is a pair consisting of:
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
Introducing the W3C XML Path Language (XPath) 2.0 Working Draft
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.
PrefixedAttName
| DefaultAttName
[2] PrefixedAttName ::= 'xmlns:' NCName
[NSC: Leading "XML" ]
[3] DefaultAttName ::= 'xmlns'
[4] NCName ::= (Letter | '_') (NCNameChar)*
/* An XML Name, minus the ":" */
[5] NCNameChar ::= Letter | Digit | '.' | '-' | '_' | CombiningChar
| Extender
The attribute's value, a URI reference, is the namespace name identifying the
namespace. The namespace name, to serve its intended purpose, should have the
characteristics of uniqueness and persistence. It is not a goal that it be directly
usable for retrieval of a schema (if any exists). An example of a syntax that is
designed with these goals in mind is that for Uniform Resource Names [RFC2141].
However, it should be noted that ordinary URLs can be managed in such a way as
to achieve these same goals.
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 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:
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>
All element types and attribute names contain either zero or one colon.
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).
D
XSLT Primer
This appendix describes introductory information about the W3C XSL and XSLT
Recommendation. It contains the following sections:
Introducing XSL
Introducing 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:
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
D-2
Introducing XSL
How to use XSL to apply style sheets to transform one document into another
The formatting objects used in XSL are based on prior work on Cascading Style
Sheets (CSS) and the Document Style Semantics & Specification Language (DSSSL).
XSL is designed to be easier to use than DSSSL.
Introducing XSL
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.
D-4
http://w3.org/TR/REC-xml-names
Data"
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.
D-6
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>
D-8
</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>
E
Java DOM and Java Bean API for XMLType,
Resource API for Java/JNDI: Quick
Reference
This appendix contains a quick reference for the following Oracle XML DB Java
APIs:
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-1
Description
XDBAttribute
Implements the W3C DOM Node interface for interacting with XOBs.
XDBCData
XDBCharData
XDBComment
XDBDocument
Table E1 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
XDBNodeList
Implements org.w3c.dom.NodeList.
XDBNotation
Implements org.w3c.dom.Notation.
XDBProcInst
XDBText
Implements org.w3c.dom.Text.
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-3
Table E1 Java DOM API for XMLType (mostly oracle.xdb.dom) Classes (Cont.)
Java DOM API for XMLType
Description
XMLType
(package oracle.xdb)
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 E1 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()
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
Description
Attribute
Get/setAttribute{attrname}
Complextype
Get/set{complextype
classname}.
Scalar data
Table E3 lists the mapping used by the Java Bean API for XMLType between XML
Schema, SQL, and Java datatypes.
Table E3 Mapping From XML Schema to SQL and Java Datatypes
XML Schema Datatype
SQL 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 E3 Mapping From XML Schema to SQL and Java Datatypes (Cont.)
XML Schema Datatype
SQL 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/JNDI"
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-7
Description
XDBContext Class
Implements javax.naming.context.
Methods:
XDBContextFactory() - Constructor for class
XDBContextFactory. public XDBContextFactory();
XDBNameParser Class
Implements javax.naming.NameParser
XDBNamingEnumeration Class
Implements javax.naming.NamingEnumeration
Description
XDBResource Class
XDBResource()
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-9
Description
getAuthor()
getComment()
getContent()
getContentType()
getCreateDate()
getDisplayName()
getLanguage()
getLastModDate()
getOwnerId()
setACL()
setAuthor()
setComment()
setContent()
E-10
Description
setContentType()
setCreateDate()
setDisplayName()
setLanguage()
setLastModDate()
setOwnerId()
Java DOM and Java Bean API for XMLType, Resource API for Java/JNDI: Quick Reference E-11
E-12
F
Oracle XML DB XMLType API, PL/SQL and
Resource PL/SQL APIs: Quick Reference
This appendix provides a summary of the following Oracle XML DB SQL and
PL/SQL APIs:
XMLType API
DBMS_XMLSCHEMA
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 F1 lists the XMLType API functions.
See Also:
F-2
XMLType API
Table F1
XMLType API
Function
Description
XMLType()
Parameters:
xmlData - data in the form of a CLOB, REF cursor, VARCHAR2 or
object type.
schema - optional schema URL used to make the input conform to
the given schema.
validated - flag to indicate that the instance is valid according to the
given XMLSchema. (default 0)
wellformed - flag to indicate that the input is wellformed. If set,
then the database would not do well formed check on the input
instance. (default 0)
--
--
createXML()
STATIC FUNCTION createXML( xmlval IN
varchar2) RETURN XMLType deterministic
STATIC FUNCTION createXML( xmlval IN clob)
RETURN XMLType
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-3
XMLType API
Table F1
Function
Description
existsNode()
Parameters:
xpath - XPath expression to test.
nsmap - optional namespace mapping.
extract()
isFragment()
MEMBER FUNCTION isFragment() RETURN
number deterministic
getClobVal()
MEMBER FUNCTION getClobVal() RETURN clob
deterministic
getNumVal()
MEMBER FUNCTION getNumVal() RETURN
number deterministic
getStringVal()
MEMBER FUNCTION getStringVal() RETURN
varchar2 deterministic
transform()
MEMBER FUNCTION transform(xsl IN
XMLType, parammap in varchar2 := NULL)
RETURN XMLType deterministic
Parameters:
xpath - XPath expression to apply.
nsmap - optional prefix to namespace mapping information.
Determines if the XMLType instance corresponds to a well-formed
document, or a fragment. Returns 1 or 0 indicating if the XMLType
instance contains a fragment or a well-formed document. Returns 1
or 0 indicating if the XMLType instance contains a fragment or a
well-formed document..
Returns a CLOB containing the serialized XML representation; if
the return is a temporary CLOB, it must be freed after use.
F-4
XMLType API
Table F1
Function
Description
toObject()
Parameters:
SELF - instance to be converted. Implicit if used as a member
procedure.
object - converted object instance of the required type may be
passed in to this function.
schema - schema URL. Mapping of the XMLType instance to the
converted object instance can be specified using a schema.
element - top-level element name. This specifies the top-level
element name in the XMLSchema document to map the XMLType
instance.
isSchemaBased()
MEMBER FUNCTION isSchemaBased return
number deterministic
getSchemaURL()
MEMBER FUNCTION getSchemaURL return
varchar2 deterministic
getRootElement()
MEMBER FUNCTION getRootElement return
varchar2 deterministic
createSchemaBasedXML()
MEMBER FUNCTION
createSchemaBasedXML(schema IN varchar2 :=
NULL) return sys.XMLType deterministic
createNonSchemaBasedXML()
MEMBER FUNCTION
createNonSchemaBasedXML return XMLType
deterministic
getNamespace()
MEMBER FUNCTION getNamespace return
varchar2 deterministic
schemaValidate()
MEMBER PROCEDURE schemaValidate
Validates the XML instance against its schema if it has not already
validated. For non-schema based documents an error is raised. If
validation fails an error is raised; else, the documents status is
changed to validated.
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-5
Table F1
Function
Description
isSchemaValidated()
setSchemaValidated()
MEMBER PROCEDURE setSchemaValidated(flag
IN BINARY_INTEGER := 1)
isSchemaValid()
member function isSchemaValid(schurl IN
VARCHAR2 := NULL, elem IN VARCHAR2 :=
NULL) return NUMBER deterministic
F-6
Description
DOM Node
isNull()
makeAttr()
makeCDataSection()
makeCharacterData()
makeComment()
makeDocumentFragment()
Description
makeDocumentType()
makeElement()
makeEntity()
makeEntityReference()
makeNotation()
makeProcessingInstruction()
makeText()
makeDocument()
writeToFile()
writeToBuffer()
writeToClob()
getNodeName()
getNodeValue()
setNodeValue()
getNodeType()
getParentNode()
getChildNodes()
getFirstChild()
getLastChild()
getPreviousSibling()
getNextSibling()
getAttributes()
getOwnerDocument()
insertBefore()
replaceChild()
removeChild()
appendChild()
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-7
F-8
Description
hasChildNodes()
cloneNode()
isNull()
getNamedItem()
setNamedItem()
removeNamedItem()
item()
getLength()
isNull()
item()
getLength()
DOM Attr
isNull()
makeNode()
getQualifiedName()
getNamespace()
getLocalName()
getExpandedName()
getName()
getSpecified()
getValue()
setValue()
isNull()
makeNode()
Description
isNull()
makeNode()
getData()
setData()
getLength()
substringData()
appendData()
insertData()
deleteData()
replaceData()
DOM Comment
isNull()
makeNode()
DOM Implementation
isNull()
hasFeature()
isNull()
makeNode()
isNull()
makeNode()
findEntity()
findNotation()
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference F-9
Description
getPublicId()
getSystemId()
writeExternalDTDToFile()
writeExternalDTDToBuffer()
writeExternalDTDToClob()
getName()
getEntities()
getNotations()
DOM Element
isNull()
makeNode()
getQualifiedName()
getNamespace()
getLocalName()
getExpandedName()
getChildrenByTagName()
getElementsByTagName()
resolveNamespacePrefix()
getTagName()
getAttribute()
setAttribute()
removeAttribute()
getAttributeNode()
setAttributeNode()
removeAttributeNode()
normalize()
Description
DOM Entity
isNull()
makeNode()
getPublicId()
getSystemId()
getNotationName()
isNull()
makeNode()
DOM Notation
isNull()
makeNode()
getPublicId()
getSystemId()
isNull()
makeNode()
getData()
getTarget()
setData()
DOM Text
isNull()
makeNode()
splitText()
DOM Document
isNull()
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference
F-11
Description
makeNode()
newDOMDocument()
freeDocument()
getVersion()
setVersion()
getCharset()
setCharset()
getStandalone()
setStandalone()
writeToFile()
writeToBuffer()
writeToClob()
writeExternalDTDToFile()
writeExternalDTDToBuffer()
writeExternalDTDToClob()
getDoctype()
getImplementation()
getDocumentElement()
createElement()
createDocumentFragment()
createTextNode()
createComment()
createCDATASection()
createProcessingInstruction()
createAttribute()
Creates an Attribute.
createEntityReference()
getElementsByTagName()
Functions/Procedures
Description
parse()
newParser()
parseBuffer()
parseClob()
parseDTD()
parseDTDBuffer()
parseDTDClob()
setBaseDir()
showWarnings()
setErrorLog()
setPreserveWhitespace()
setValidationMode()
getValidationMode()
setDoctype()
Sets DTD.
getDoctype()
getDocument()
freeParser()
getReleaseVersion()
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference
F-13
Description
newProcessor()
processXSL()
showWarnings()
setErrorLog()
newStylesheet()
transformNode()
selectNodes()
selectSingleNodes()
Selects the first node from the tree that matches the
given pattern.
valueOf()
setParam()
removeParam()
resetParams()
freeStylesheet()
freeProcessor()
DBMS_XMLSCHEMA
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 F5
summarizes the DBMS_XMLSCHEMA functions and procedures.
See Also: Chapter 5, "Structured Mapping of XMLType"
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference
F-15
DBMS_XMLSCHEMA
Description
registerSchema()
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN
VARCHAR2, local IN BOOLEAN :=
TRUE, genTypes IN BOOLEAN :=
TRUE, genbean IN BOOLEAN :=
FALSE, genTables IN BOOLEAN :=
TRUE, force IN BOOLEAN :=
FALSE, owner IN VARCHAR2 :=
null);
Parameters:
schemaURL - URL that uniquely identifies the
schema document. This value is used to derive the
path name of the schema document within the XDB
hierarchy.
schemaDoc - a valid XML schema document
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN CLOB,
local IN BOOLEAN := TRUE,
genTypes IN BOOLEAN := TRUE,
genbean IN BOOLEAN := FASLE,
force IN BOOLEAN := FALSE,
owner IN VARCHAR2 := null);
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN BFILE,
local IN BOOLEAN := TRUE,
genTypes IN BOOLEAN := TRUE,
genbean IN BOOLEAN := FALSE,
force IN BOOLEAN := FALSE,
owner IN VARCHAR2 := null);
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN
SYS.XMLType, local IN BOOLEAN
:= TRUE, genTypes IN BOOLEAN :=
TRUE, genbean IN BOOLEAN :=
FALSE, force IN BOOLEAN :=
FALSE, owner IN VARCHAR2 :=
null);
procedure
registerSchema(schemaURL IN
VARCHAR2, schemaDoc IN
SYS.URIType, local IN BOOLEAN :=
TRUE, genTypes IN BOOLEAN :=
TRUE, genbean IN BOOLEAN :=
FALSE, force IN BOOLEAN :=
FALSE, owner IN VARCHAR2 :=
null);
DBMS_XMLSCHEMA
Description
registerURI()
procedure registerURI(schemaURL
IN varchar2, schemaDocURI IN
varchar2,
local IN
BOOLEAN := TRUE, genTypes IN
BOOLEAN := TRUE, genbean IN
BOOLEAN := FALSE, genTables IN
BOOLEAN := TRUE, force IN
BOOLEAN := FALSE, owner IN
VARCHAR2 := null);
deleteSchema()
procedure
deleteSchema(schemaURL IN
varchar2, delete_option IN pls_
integer := DELETE_RESTRICT);
generateBean()
compileSchema()
procedure compileSchema(
schemaURL IN varchar2);
generateSchema()
function
generateSchemas(schemaName IN
varchar2, typeName IN varchar2,
elementName IN varchar2 := NULL,
schemaURL IN varchar2 := NULL,
annotate IN BOOLEAN := TRUE,
embedColl IN BOOLEAN := TRUE )
return sys.XMLSequenceType;
function generateSchema(
schemaName IN varchar2,
typeName IN varchar2,
elementName IN varchar2 := NULL,
recurse IN BOOLEAN := TRUE,
annotate IN BOOLEAN := TRUE,
embedColl IN BOOLEAN := TRUE )
return sys.XMLType;
DBMS_XMLSCHEMA contstants:
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference
F-17
DELETE_INVALIDATE,CONSTANT NUMBER := 2;
Description
USER_XML_SCHEMAS
ALL_XML_SCHEMAS
DBA_XML_SCHEMAS
DBA_XML_TABLES
USER_XML_TABLES
ALL_XML_TABLES
DBA_XML_TAB_COLS
USER_XML_TAB_COLS
ALL_XML_TAB_COLS
DBA_XML_VIEWS
USER_XML_VIEWS
ALL_XML_VIEWS
DBA_XML_VIEW_COLS
USER_XML_VIEW_COLS
ALL_XML_VIEW_COLS
Some of these methods can be used for both Oracle XML DB resources and
arbitrary database objects. AclCheckPrivileges() enables database users
access to Oracle XML DB ACL-based security mechanism without having to
store their objects in the Oracle XML DB hierarchy.
Description
getAclDocument()
FUNCTION getAclDocument(
abspath IN VARCHAR2) RETURN
sys.xmltype;
getPrivileges()
FUNCTION getPrivileges( res_path
IN VARCHAR2) RETURN
sys.xmltype;
changePrivileges()
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference
F-19
Description
checkPrivileges()
setacl()
PROCEDURE setacl( res_path IN
VARCHAR2, acl_path IN
VARCHAR2);
AclCheckPrivileges()
FUNCTION AclCheckPrivileges(
acl_path IN VARCHAR2, owner IN
VARCHAR2, privs IN xmltype)
RETURN pls_integer;
LockResource()
FUNCTION LockResource( path IN
VARCHAR2, depthzero IN
BOOLEAN, shared IN boolean)
RETURN BOOLEAN;
GetLockToken()
PROCEDURE GetLockToken( path
IN VARCHAR2, locktoken OUT
VARCHAR2);
UnlockResource()
FUNCTION UnlockResource( path
IN VARCHAR2, deltoken IN
VARCHAR2) RETURN BOOLEAN;
Description
CreateResource()
FUNCTION CreateResource(path IN
VARCHAR2,data IN VARCHAR2)
RETURN BOOLEAN;
FUNCTION CreateResource(path IN
VARCHAR2, data IN
SYS.XMLTYPE) RETURN
BOOLEAN;
FUNCTION CreateResource(path IN
VARCHAR2, datarow IN REF
SYS.XMLTYPE) RETURN
BOOLEAN;
FUNCTION CreateResource(path IN
VARCHAR2, data IN CLOB)
RETURN BOOLEAN;
FUNCTION CreateResource(path
IN VARCHAR2, data IN BFILE)
RETURN BOOLEAN;
CreateFolder()
DeleteResource()
Link()
CFG_Refresh()
PROCEDURE CFG_Refresh;
CFG_Get()
CFG_Update()
PROCEDURE CFG_Update(
xdbconfig IN SYS.XMLTYPE);
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 F8 summarizes the DBMS_XMLGEN functions and procedures.
See Also: Chapter 10, "Generating XML Data from the Database"
Table F8 DBMS_XMLGEN Functions and Procedures
Function/Procedure
Description
newContext()
setRowTag()
setRowSetTag ()
getXML()
getNumRowsProcessed()
setMaxRows()
setSkipRows()
setConvertSpecialChars()
convert()
useItemTagsForColl()
restartQUERY()
RESOURCE_VIEW, PATH_VIEW
Description
closeContext()
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 F9 summarizes the Oracle XML DB Resource API for PL/SQL operators.
See Also: Chapter 15, "RESOURCE_VIEW and PATH_VIEW"
Table F9 RESOURCE_VIEW, PATH_VIEW Operators
Operator
Description
UNDER_PATH
INTEGER UNDER_PATH(
resource_column, pathname);
Parameters:
EQUALS_PATH INTEGER
EQUALS_PATH(resource_column,
pathname);
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference
F-23
DBMS_XDB_VERSION
Description
PATH
DEPTH
DEPTH INTEGER DEPTH(
correlation);
DBMS_XDB_VERSION
DBMS_XDB_VERSION along with DBMS_XDB implement the Oracle XML DB
versioning API.
Table F10 summarizes the DBMS_XDB_VERSION functions and procedures.
See Also: Chapter 14, "Oracle XML DB Versioning"
Table F10 DBMS_XDB_VERSION Functions and Procedures
Function/Procedure
Description
MakeVersioned()
FUNCTION MakeVersioned(
pathname VARCHAR2) RETURN
dbms_xdb.resid_type;
Checkout()
Checkin()
FUNCTION Checkin( pathname
VARCHAR2) RETURN dbms_
xdb.resid_type;
Uncheckout()
FUNCTION Uncheckout( pathname
VARCHAR2) RETURN dbms_
xdb.resid_type;
GetPredecessors()
FUNCTION GetPredecessors(
pathname VARCHAR2) RETURN
resid_list_type;
DBMS_XDBT
Description
GetPredsByResId()
GetResourceByResId()
FUNCTION GetResourceByResId(
resid resid_type) RETURN
XMLType;
GetSuccessors()
FUNCTION GetSuccessors(
pathname VARCHAR2) RETURN
resid_list_type;
GetSuccsByResId()
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:
Oracle XML DB XMLType API, PL/SQL and Resource PL/SQL APIs: Quick Reference
F-25
DBMS_XDBT
Description
dropPreferences()
createPreferences()
createDatastorePref()
createFilterPref()
createLexerPref()
createWordlistPref()
createStoplistPref()
createStoragePref()
createSectiongroupPref()
createIndex()
configureAutoSync()
G
Example Setup scripts. Oracle XML DBSupplied XML Schemas
This appendix describes a few example setup scripts for use with the examples in
Chapter 3, "Using Oracle XML DB". It also includes the structure of Resource View
and Path View and the Oracle XML DB supplied XML schema:
G-1
DBMS_LOB.fileclose(targetFile);
return charContent;
end;
/
show errors
declare
result boolean;
begin
result := dbms_xdb.createfolder(/public/&4);
end;
/
commit;
quit
G-3
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
/
--
G-5
) = 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;
G-7
/
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>
G-9
<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:
G-10
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-11
Datatype
-------XMLTYPE
VARCHAR2
Description
------------------------------------------------------A resource in Oracle XML Repository
A path that can be used to access the resource in the
Repository
Datatype
-------VARCHAR2
XMLTYPE
XMLTYPE
Description
----------------------------Path name of a resource
The resource referred by PATH
Link property
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">
G-12
<restriction base="string">
<minLength value="1" fixed="false"/>
<maxLength value="4000" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="ResMetaStr">
<restriction base="string">
<minLength value="1" fixed="false"/>
<maxLength value="128" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="SchElemType">
<restriction base="string">
<minLength value="1" fixed="false"/>
<maxLength value="4000" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="GUID">
<restriction base="hexBinary">
<minLength value="8" fixed="false"/>
<maxLength value="32" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="LocksRaw">
<restriction base="hexBinary">
<minLength value="0" fixed="false"/>
<maxLength value="2000" fixed="false"/>
</restriction>
</simpleType>
<simpleType name="LockScopeType">
<restriction base="string">
<enumeration value="Exclusive" fixed="false"/>
<enumeration value="Shared" fixed="false"/>
</restriction>
</simpleType>
<complexType name="LockType" mixed="false">
<sequence>
<element name="owner" type="string"/>
<element name="expires" type="dateTime"/>
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-13
G-14
</sequence>
<attribute name="Hidden" type="boolean"/>
<attribute name="Invalid" type="boolean"/>
<attribute name="VersionID" type="integer"/>
<attribute name="ActivityID" type="integer"/>
<attribute name="Container" type="boolean"/>
<attribute name="CustomRslv" type="boolean"/>
</complexType>
<element name="Resource" type="res:ResourceType"/>
</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.
Note : The "systemPrivileges" element below lists
all supported
system privileges and their aggregations.
</documentation>
<appinfo>
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-15
<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>
<!-- privilegeNameType (this is an emptycontent type) -->
<complexType name = "privilegeNameType"/>
<!-- privilegeName element
All system and user privileges are in the
substitutionGroup
of this element.
-->
<element name = "privilegeName"
type="xdbacl:privilegeNameType"
xdb:defaultTable=""/>
<!-- all system privileges in the XDB ACL namespace -->
<element name = "read-properties"
type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "read-contents"
type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "read-acl" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
xdb:defaultTable=""/>
<element name = "update" type="xdbacl:privilegeNameType"
substitutionGroup="xdbacl:privilegeName"
G-16
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=""/>
<!-- privilege element -->
<element name = "privilege" xdb:SQLType = "XDB$PRIV_T"
xdb:defaultTable="">
<complexType> <sequence>
<any maxOccurs="unbounded" />
</sequence> </complexType>
</element>
<!-- ace element -->
<element name = "ace" xdb:SQLType = "XDB$ACE_T"
xdb:defaultTable="">
<complexType> <sequence>
<element name = "grant" type = "boolean"/>
<element name = "principal" type = "string"/>
<element ref="xdbacl:privilege" minOccurs="1"/>
</sequence> </complexType>
</element>
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-17
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">
<element name="xdbconfig" xdb:defaultTable="XDB$CONFIG">
<complexType><sequence>
<!-- predefined XDB properties - these should NOT be
changed -->
G-18
<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"/>
<!-- protocol specific properties -->
<element name="protocolconfig">
<complexType><sequence>
<!-- these apply to all protocols -->
<element name="common">
<complexType><sequence>
<element name="extension-mappings">
<complexType><sequence>
<element name="mime-mappings"
type="xdbc:mime-mapping-type"/>
<element name="lang-mappings"
type="xdbc:lang-mapping-type"/>
<element name="charset-mappings"
type="xdbc:charset-mapping-type"/>
<element name="encoding-mappings"
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-19
type="xdbc:encoding-mapping-type"/>
</sequence></complexType>
</element>
<element name="session-pool-size"
type="unsignedInt"
default="50"/>
<element name="session-timeout"
type="unsignedInt"
default="6000"/>
</sequence></complexType>
</element>
<!-- FTP specific -->
<element name="ftpconfig">
<complexType><sequence>
<element name="ftp-port" type="unsignedShort"
default="2100"/>
<element name="ftp-listener" type="string"/>
<element name="ftp-protocol" type="string">
<!--simpleType>
<restriction base="string">
<enumeration value="tcp"/>
<enumeration value="tcps"/>
</restriction>
</simpleType-->
</element>
<element name="logfile-path" type="string"
default="/sys/log/ftplog.xml"/>
<element name="log-level" type="unsignedInt"
default="1"/>
<element name="session-timeout"
type="unsignedInt"
default="6000"/>
</sequence></complexType>
</element>
<!-- HTTP specific -->
<element name="httpconfig">
<complexType><sequence>
<element name="http-port"
G-20
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
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>
<!-- customized error pages -->
<complexType name="error-page-type">
<sequence>
<element name="error-page" minOccurs="0"
maxOccurs="unbounded">
<complexType><sequence>
<choice>
<element name="error-code">
G-22
<simpleType>
<restriction base="positiveInteger">
<minInclusive value="100"/>
<maxInclusive value="999"/>
</restriction>
</simpleType>
</element>
<!-- Fully qualified classname of a Java
exception type -->
<element name="exception-type"
type="string"/>
<element name="OracleError">
<complexType><sequence>
<element name="facility" type="string"
default="ORA"/>
<element name="errnum"
type="unsignedInt"/>
</sequence></complexType>
</element>
</choice>
<element name="location" type="anyURI"/>
</sequence></complexType>
</element>
</sequence>
</complexType>
<!-- parameter for a servlet: name, value pair and a
description -->
<complexType name="param">
<sequence>
<element name="param-name" type="string"/>
<element name="param-value" type="string"/>
<element name="description" type="string"/>
</sequence>
</complexType>
<complexType name="servlet-config-type">
<sequence>
<element name="servlet-mappings">
<complexType><sequence>
<element name="servlet-mapping" minOccurs="0"
Example Setup scripts. Oracle XML DB- Supplied XML Schemas G-23
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"
G-24
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
G-26
Glossary
Access control entry (ACE)
An entry in the access control list that grants or denies access to a given principal.
access control list (ACL)
A list of access control entries that determines which principals have access to a
given resource or resources.
ACE
Access Control Entry. See access control entry.
ACL
Access Control List. See access control list.
API
Application Program Interface. See application program interface.
application program interface (API)
A set of public programmatic interfaces that consist of a language and message
format to communicate with an operating system or other programmatic
environment, such as databases, Web servers, JVMs, and so forth. These messages
typically call functions and methods available for application development.
application server
A server designed to host applications and their environments, permitting server
applications to run. A typical example is Oracle9iAS, which is able to host Java, C,
C++, and PL/SQL applications in cases where a remote client controls the interface.
See also Oracle Application Server.
Glossary-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.
Binary Large Object (BLOB)
A Large Object datatype whose content consists of binary data. Additionally, this
data is considered raw as its structure is not recognized by the database.
BLOB
See Binary Large Object.
Business-to-Business (B2B)
A term describing the communication between businesses in the selling of goods
and services to each other. The software infrastructure to enable this is referred to as
an exchange.
Business-to-Consumer (B2C)
A term describing the communication between businesses and consumers in the
selling of goods and services.
callback
A programmatic technique in which one process starts another and then continues.
The second process then calls the 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.
Cascading Style Sheets
A simple mechanism for adding style (fonts, colors, spacing, and so on) to Web
documents.
CDATA
See character data.
CDF
Channel Definition Format. Provides a way to exchange information about channels
on the internet.
CGI
See Common Gateway Interface.
character data (CDATA)
Text in a document that should not be parsed is put within a CDATA section. This
allows for the inclusion of characters that would otherwise have special functions,
such as &, <, >, and so on. CDATA sections can be used in the content of an element
or in attributes.
child element
An element that is wholly contained within another, which is referred to as its
parent element. For example <Parent><Child></Child></Parent> illustrates a
child element nested within its parent element.
Class Generator
A utility that accepts an input 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.
Character Large Object (CLOB)
The LOB datatype whose value is composed of character data corresponding to the
database character set. A CLOB may be indexed and searched by the Oracle Text
search engine.
CLOB
See Character Large Object.
command line
The interface method in which the user enters in commands at the command
interpreters prompt.
Common Gateway Interface (CGI)
The programming interfaces enabling Web servers to execute other programs and
pass their output to HTML pages, graphics, audio, and video sent to browsers.
Common Object Request Broker API (CORBA)
An Object Management Group standard for communicating between distributed
objects across a network. These self-contained software modules can be used by
applications running on different platforms or operating systems. CORBA objects
and their data formats and functions are defined in the Interface Definition
Language (IDL), which can be compiled in a variety of languages including Java, C,
C++, Smalltalk and COBOL.
Common Oracle Runtime Environment (CORE)
The library of functions written in C that provides developers the ability to create
code that can be easily ported to virtually any platform and operating system.
Content
The body of a resource in Oracle XML DB and what you get when you treat the
resource like a 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.
Database Access Descriptor (DAD)
A DAD is a named set of configuration values used for database access. A DAD
specifies information such as the database name or the Oracle Net service name, the
ORACLE_HOME directory, and Globalization Support configuration information
such as language, sort type, and date language.
datagram
A text fragment, which may be in XML format, that is returned to the requester
embedded in an HTML page from a SQL query processed by the XSQL Servlet.
DBURITYPE
The Oracle9i datatype used for storing instances of the datatype that permits
XPath-based navigation of database schemas.
DOCTYPE
The term used as the tag name designating the DTD or its reference within an XML
document. For example, <!DOCTYPE person SYSTEM "person.dtd"> declares
the root element name as person and an external DTD as person.dtd in the file
system. Internal DTDs are declared within the DOCTYPE declaration.
Document Object Model (DOM)
An in-memory tree-based object representation of an XML document that enables
programmatic access to its elements and attributes. The DOM object and its
interface is a W3C recommendation. It specifies the Document Object Model of an
XML Document including the APIs for programmatic access. DOM views the
parsed document as a tree of objects.
Document Type Definition (DTD)
A set of rules that define the allowable structure of an XML document. DTDs are
text files that derive their format from SGML and can either be included in an XML
document by using the DOCTYPE element or by using an external file through a
DOCTYPE reference.
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.
Enterprise Java Bean (EJB)
An independent program module that runs within a JVM on the server. CORBA
provides the infrastructure for EJBs, and a container layer provides security,
transaction support, and other common functions on any supported server.
entity
A string of characters that may represent either another string of characters or
special characters that are not part of the documents character set. Entities and the
text that is substituted for them by the parser are declared in the DTD.
Glossary-6
existnode
The SQL operator that returns a TRUE or FALSE based upon the existence of an
XPath within an XMLType.
eXtensible Markup Language (XML)
An open standard for describing data developed by the World Wide Web
Consortium (W3C) using a subset of the SGML syntax and designed for Internet
use.
eXtensible Stylesheet Language Formatting Object (XSLFO)
The W3C standard specification that defines an XML vocabulary for specifying
formatting semantics. See FOP.
eXtensible Stylesheet Language Transformation (XSLT)
Also written as XSL-T. The XSL W3C standard specification that defines a
transformation language to convert one XML document into another.
eXtensible Stylesheet Language (XSL)
The language used within stylesheets to transform or render XML documents.
There are two W3C recommendations covering XSL stylesheetsXSL
Transformations (XSLT) and XSL Formatting Objects (XSLFO).
(W3C) eXtensible Stylesheet Language. XSL consists of two W3C recommendations:
XSL Transformations for transforming one XML document into another and XSL
Formatting Objects for specifying the presentation of an XML document. XSL is a
language for expressing stylesheets. It consists of two parts:
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
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.
Integrated Development Environment (IDE)
A set of programs designed to aide in the development of software run from a
single user interface. JDeveloper is an IDE for Java development as it includes an
editor, compiler, debugger, syntax checker, help system, and so on, to permit Java
software development through a single user interface.
interMedia
The collection of complex datatypes and their access in Oracle. These include text,
video, time-series, and spatial data.
Internet Inter-ORB Protocol (IIOP)
The protocol used by CORBA to exchange messages on a TCP/IP network such as
the Internet.
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.
Java 2 Platform, Enterprise Edition (J2EE)
The Java platform (Sun Microsystems) that defines multitier enterprise computing.
Java API for XML Processing (JAXP)
Enables applications to parse and transform XML documents using an API that is
independent of a particular XML processor implementation.
JavaBean
An independent program module that runs within a JVM, typically for creating
user interfaces on the client. Also known as Java Bean. The server equivalent is
called an Enterprise JavaBean (EJB). See also Enterprise JavaBean.
Java Database Connectivity (JDBC)
The programming API that enables Java applications to access a database through
the SQL language. JDBC drivers are written in Java for platform independence but
are specific to each database.
Java Developers Kit (JDK)
The collection of Java classes, runtime, compiler, debugger, and usually source code
for a version of Java that makes up a Java development environment. JDKs are
designated by versions, and Java 2 is used to designate versions from 1.2 onward.
Java Naming and Directory Interface
A programming interface from Sun for connecting Java programs to naming and
directory services such as DNS, LDAP and NDS. Oracle XML DB Resource API for
Java/JNDI supports JNDI.
Glossary-10
Glossary-11
JVM
See Java virtual machine.
LAN
See local area network.
Large Object (LOB)
The class of SQL data type that is further divided into Internal LOBs and External
LOBs. Internal LOBs include BLOBs, CLOBS, and NCLOBs while External LOBs
include BFILES. See also BFILES, Binary Large Object, Character Large Object.
lazy type conversions
A mechanism used by Oracle XML DB to only convert the XML data for Java when
the Java application first asks for it. This saves typical type conversion bottlenecks
with JDBC.
listener
A separate application process that monitors the input process.
LOB
See Large Object.
local area network (LAN)
A computer communication network that serves users within a restricted
geographical area. LANs consist of servers, workstations, communications
hardware (routers, bridges, network cards, and so on) and a network operating
system.
name-level locking
Oracle XML DB provides for name-level locking rather than collection-level locking.
When a name is added to a collection, an exclusive write lock is not placed on the
collection, only that name within the collection is locked. The name 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
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 Request Broker (ORB)
Software that manages message communication between requesting programs on
clients and between objects on servers. ORBs pass the action request and its
parameters to the object and return the results back. Common implementations are
JCORB and EJBs. See also CORBA.
Object View
A tailored presentation of the data contained in one or more object tables or other
views. The output of an Object View query is treated as a table. Object Views can be
used in most places where a table is used.
OC4J
Oracle9iAS Containers for J2EE, a J2EE deployment tool that comes with
JDeveloper.
OCT
See Ordered Collection in Tables.
OE
Oracle Exchange.
OIS
See Oracle Integration Server.
Oracle9iAS (iAS)
The Oracle application server that integrates all the core services and features
required for building, deploying, and managing high-performance, n-tier,
transaction-oriented Web applications within an open standards framework.
Oracle9iFS
The Oracle 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.
Ordered Collection in Tables (OCT)
When elements of a VARRAY are stored in a separate table, they are referred to as
an Ordered Collection in Tables.
Oracle Text
An Oracle tool that provides full-text indexing of documents and the capability to
do SQL queries over documents, along with XPath-like searching.
Oracle XML DB
A high-performance XML storage and retrieval technology provided with Oracle
database server. It is based on the W3C XML data model.
ORB
See Object Request Broker.
Organization for the Advancement of Structured Information (OASIS)
An organization of members chartered with promoting public information
standards through conferences, seminars, exhibits, and other educational events.
XML is a standard that OASIS is actively promoting as it is doing with SGML.
parent element
An element that surrounds another element, which is referred to as its child
element. For example, <Parent><Child></Child></Parent> illustrates a parent
element wrapping its child element.
Parsed Character Data (PCDATA)
The element content consisting of text that should be parsed but is not part of a tag
or nonparsed data.
parser
In XML, a software program that accepts as input an XML document and
determines whether it is well-formed and, optionally, valid. The Oracle XML Parser
supports both SAX and DOM interfaces.
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.
Secure Sockets Layer (SSL)
The primary security protocol on the Internet; it utilizes a public key /private key
form of encryption between browsers and servers.
Server-Side Include (SSI)
The HTML command used to place data or other content into a Web page before
sending it to the requesting browser.
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.
Simple API for XML (SAX)
An XML standard interface provided by XML parsers and used by event-based
applications.
Simple Object Access Protocol (SOAP)
An XML-based protocol for exchanging information in a decentralized, distributed
environment.
SOAP
See Simple Object Access Protocol.
SQL
See Structured Query Language.
SSI
See Server-Side Include.
SSL
See Secure Sockets Layer.
Structured Generalized Markup Language (SGML)
An ISO standard for defining the format of a text document implemented using
markup and DTDs.
Structured Query Language (SQL)
The standard language used to access and process data in a relational database.
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).
Transmission Control Protocol/Internet Protocol (TCP/IP)
The communications network protocol that consists of the TCP which controls the
transport functions and IP which provides the routing mechanism. It is the standard
for Internet communications.
Transviewer
The Oracle term used to describe the Oracle XML JavaBeans included in the XDK
for Java.
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.
Uniform Resource Identifier (URI)
The address syntax that is used to create URLs and XPaths.
Uniform Resource Locator (URL)
The address that defines the location and route to a file on the Internet. URLs are
used by browsers to navigate the World Wide Web and consist of a protocol prefix,
port number, domain name, directory and subdirectory names, and the file name.
For example http://technet.oracle.com:80/tech/xml/index.htm specifies the
location and path a browser will travel to find OTNs XML site on the World Wide
Web.
Universal Description, Discovery and Integration (UDDI)
This specification provides a platform-independent framework using XML to
describe services, discover businesses, and integrate business services on the
Internet.
URI
See Uniform Resource Identifier.
URL
See Uniform Resource Locator.
user interface (UI)
The combination of menus, screens, keyboard commands, mouse clicks, and
command language that defines how a user interacts with a software application.
User Interface XML (UIX)
A set of technologies that constitute a framework for building web applications.
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.
Web Request Broker (WRB)
The cartridge within OAS that processes URLs and sends them to the appropriate
cartridge.
Web Services Description Language (WSDL)
A general purpose XML language for describing the interface, protocol bindings,
and deployment details of Web services.
well-formed
The 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.
wide area network (WAN)
A computer communication network that serves users within a wide geographic
area, such as a state or country. WANs consist of servers, workstations,
communications hardware (routers, bridges, network cards, and so on), and a
network operating system.
Working Group (WG)
The committee within the W3C that is made up of industry members that
implement the recommendation process in specific Internet technology areas.
World Wide Web Consortium (W3C)
An international industry consortium started in 1994 to develop standards for the
World Wide Web. It is located at www.w3c.org.
Glossary-21
Glossary-22
XML Query
The W3Cs effort to create a standard for the language and syntax to query XML
documents.
XML Schema
The W3Cs effort to create a standard to express simple data types and complex
structures within an XML document. It addresses areas currently lacking in DTDs,
including the 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
access control entries (ACEs), 18-9
elements in, 18-6
access control lists (ACLs), 18-2
bootstrap, 18-4
concurrency resolution, 18-5
default, 18-4
defined, 13-5
features, 18-5
managing, 18-11
managing from Enterprise Manager, 21-22
restrictions, 18-12
security, row-level, 18-13
setting the resource property, 18-11
summary, 1-12
term explained, 1-30
updating, 18-10
using, 18-9
accessing
Java examples for, 9-4
using XDBUriType, 3-44
with JDBC, 9-4
XML documents using Java, 9-3
adding
XMLType columns, 4-8
Advanced Queuing (AQ)
definition, 23-2
enqueuing, 23-9
hub-and-spoke architecture support, 23-4
IDAP, 23-5
message management support, 23-4
messaging scenarios, 23-2
point-to-point support, 23-2
Index-1
B
B*Tree, 1-12, 4-6, 5-52
indexing, 3-26
bootstrap ACL, 18-4
C
CASCADE mode, 5-13
cascading style sheets, see CSS, D-7
catalog views, F-18
cfg_get, 16-9, A-9
cfg_refresh, A-10
CharacterData, 8-21
Classes
XDBContextFactory
initial contexts for JNDI, 17-6
CLOB storage of XMLType, 4-5
collection attribute, 5-38
collection index, 5-61
collections, 3-32, 18-6
columnProps attribute, 5-71
complexType
collections, 3-32
cycling, 5-49
cycling between, 5-47
elements, B-3
handling inheritance, 5-42
in XML schema, explained, B-35
mapping any and any attributes, 5-46
mapping to SQL, 5-38
restrictions, 5-42
concatenating
elements using XMLConcat, 10-16
configuring
Index-2
API, A-9
protocol server in Oracle XML DB, 19-4
servlet, example, 20-12
servlets in Oracle XML DB, 20-4
using Enterprise Manager, 21-7
constraints
on XMLType columns, 5-52
structured storage, 3-33
using with XMLType tables, 3-22
CONTAINS, 4-38, 7-6
compared against existsNode, 7-38
compared to existsNode(),extract(), 4-41
contents, element, 13-6
CREATE TABLE
XMLType storage, 5-51
createFolder(), 16-3
createXML
inserting with CLOB, example, 4-15
inserting with string, 4-16
summarized, 3-17
creating
XML schema-based tables, columns, 5-23
XMLType columns, 4-8
XMLType table, 4-7
CSS and XSL, D-7
CTX_DDL.Add_Field_Section, 7-26
CTXAPP
role, 7-6
CTXSYS.PATH_SECTION_GROUP, 7-36
CTXXPATH, 4-41
indexes, 7-45
storage preferences, 7-47
cycling in complexTypes
self-referencing, 5-49
D
data integrity
in structured, unstructured storage, 3-26
Oracle XML DB, 3-33
date
format conversion in updateXML(), 5-71
format conversions for XML, 5-63
mapping to SQL, 5-36
DBMS_METADATA, 12-5
DBMS_XDB, F-19
AclCheckPrivileges, database objects,
cfg_get, A-9
cfg_refresh, A-10
changePrivilege, 18-12
checkPrivileges, 18-13
configuration management, 16-8
getAclDocument, 18-12
Link, 16-2
LockResource, 16-2
overview, 16-2
rebuilding hierarchical index, 16-11
security, 16-5
DBMS_XDB_VERSION, 14-2, F-24
subprograms, 14-9
DBMS_XDBT, F-25
DBMS_XMLDOM, 8-5, 8-12, F-6
DBMS_XMLGEN, 10-20, F-22
generating complex XML, 10-29
generating XML, 10-2
DBMS_XMLPARSER, 8-24, F-13
DBMS_XMLSCHEMA, 5-7, F-15
deleteSchema, 5-7
generateSchema() function, 5-18
generateSchemas() function, 5-18
mapping of types, 5-32
registerSchema, 5-7
DBMS_XSLPROCESSOR, 8-28, F-14
dbmsxsch.sql, F-15
DBUri, 12-10
and object references, 12-17
identifying a row, 12-15
identifying a target column, 12-16
retrieving column text value, 12-16
retrieving the whole table, 12-14
security, 12-37
servlet, 12-34
servlet, installation, 12-36
syntax guidelines, 12-13
URL specification, 12-12
XPath expressions in, 12-13
DBUri-refs, 12-9
HTTP access, 12-34
where it can be used, 12-17
DBUriType
18-13
defined, 12-2
examples, 12-25
notation for fragments, 12-12
stores references to data, 12-6
default table
creating, 5-71
defining a, 3-40
defaultTable attribute, 5-71
deleteSchema, 9-21
deleting
resources, 3-39, 15-10
rows using extract(), 4-37
rows with XMLType columns, 4-37
using extract(), 4-37
XML schema using DBMS_XMLSCHEMA, 5-13
DEPTH, 15-8
dequeuing
with AQ XML servlet, 23-11
document
fidelity, explained, 1-4
no order, 5-65
no order with extract(), 5-69
order, 5-63
order with extract(), 5-68
order, query rewrites with collection, 5-61
ordering preserved in mapping, 5-69
DOM
differences, and SAX, 8-6
explained, 1-28
fidelity, 5-21
fidelity, default, 5-57
fidelity, in structured storage, 4-5
fidelity, structured or unstructured
storage, 3-27
fidelity, summarized, 1-4
fidelity, SYS_XDBPD$, 5-22
introduced, 8-5
Java API, 9-2
Java API features, 9-16
Java API, XMLType classes, 9-18
NodeList, 8-21
non-supported, 8-5
DOM API for PL/SQL, 8-5
DOMDocument, 9-19
dropping
Index-3
XMLType columns,
DTD
limitations, B-33
4-8
E
elementFormDefault, 5-62
elements
access control entries (ACEs), 18-6
any, 13-6
complexType, B-3
Contents, Resource index, 13-6
simpleType, B-3
XDBBinary, 13-11
XML, 8-4
enqueuing
adding new recipients after, 23-14
using AQ XML servlet, 23-9
EQUALS_PATH
summary, 15-5
syntax, 15-8
existsNode
and CONTAINS, querying, 7-38
dequeing messages, 2-10
finding XML elements, nodes, 4-20
indexing with CTXXPATH, 7-45
query rewrite, 5-52
XPath rewrites, 5-63
extract, 5-68
deleting, 4-37
dequeing messages, 2-10
mapping, 5-69
query rewrite, 5-52
querying XMLType, 4-26
rewrite in XPath expressions, 5-68
extracting
data from XML, 4-27
extractValue, 4-23
creating indexes, query rewrite, 5-67
query rewrite, 5-52
rewrites in XPath expressions, 5-66
F
factory method,
Index-4
12-25
G
genbean flag, 9-21
generating
DBUriType using SYS_DBURIGEN,
generating XML
DBMS_XMLGEN example, 10-29
12-29
19-5
element forest
XMLColAttVal, 10-19
from SQL, DBMS_XMLGEN, 10-20
one document from another, 10-12
SQL, SYS_XMLGEN, 10-41
SYS_XMLAgg, 10-50
using SQL functions, 10-2
XML SQL Utility (XSU), 10-54
XMLAgg, 10-17
XMLConcat, 10-15
XMLElement, 10-5
XMLForest, 10-9
XMLSequence, 10-11
XSQL, 10-51
getClobVal
summarized, 3-17
getNameSpace
summarized, 3-17
getRootElement
summarized, 3-17
getXMLType, 9-18
global XML schema, 5-11
groups, 18-6
H
HASPATH, 4-39, 7-10
operator, 7-12
path existence searching, 7-20
path searching, 7-19
HTTP
access for DBUri-refs, 12-34
accessing Java servlet or XMLType, 20-3
accessing Repository resources, 13-11
configuration parameters, WebDAV, 19-5
creating default tables, 5-71
HttpUriType, DBUriType, 12-23
improved performance, 19-2
Oracle XML DB servlets, 20-8
protocol server, features, 19-8
requests, 20-8
servlets, 20-4
UriFactory, 12-38
using UriRefs to store pointers, 12-7
HttpUriType
23-4
I
IDAP
architecture, 23-6
transmitted over Internet, 23-5
XML schema, 23-12
index
collection, 5-61
Index Organized Table (IOT), 5-72
indexing
B*Tree, 3-26
function-based on existsNode(), 4-38
in structured, unstructured storage, 3-26
Oracle Text, CTXXPATH, 7-45
Oracle Text, XMLType, 7-34
XMLType, 4-38
Information Set
W3C introducing XML, C-26
inheritance
in XML schema, restrictions in
complexTypes, 5-44
INPATH, 4-39, 7-10
operator, 7-12
INPATH operator, 7-12
inserting
into XMLType, 4-9
new instances, 5-52
XML data into XMLType columns, 4-15
installing
from scratch, Oracle XML DB, A-2
manually without DBCA, A-3
instance document
specifying root element namespace, 5-5
XML, described, B-36
Internet Data Access Presentation (IDAP)
SOAP specification for AQ, 23-5
isFragment
summarized, 3-17
isSchemaValid, 6-10
isSchemaValidated, 6-9
Index-5
J
Java
Oracle XML DB guidelines, 20-3
using JDBC to access XMLType objects, 20-3
writing Oracle XML DB applications, 20-2
Java bean
deleteSchema, 9-21
genbean flag, 9-21
generated example, 9-24
generated names, 9-21
generated with XML schema registration, 5-17
only for XML schema-based, 5-18
Java Bean API for XMLType, 9-20, E-6
using, 9-21
Java DOM API for XMLType, E-2
Java Stored Procedure, 9-26
JDBC
accessing documents, 9-4
manipulating data, 9-6
using SQL to determine object properties, 17-13
JNDI, 9-3, E-7
bind(), 9-17
context inputs, 17-8
context outputs, 17-10
determining properties, 17-11
oracle.xdb.spi, 17-3
support, 17-2
using Resource API, 17-4
L
Lazy Manifestation (LM), 3-25
LDAP
Oracle XML DB, in, 18-5
Least Recently Used (LRU), 3-25
Link, 16-2
LOBs
mapping XML fragments to, 5-40
location path, C-5
LockResource, 16-2
M
maintainDOM, 5-65
maintainOrder attribute,
Index-6
5-38
mapping
collection predicates, 5-60
complexType any, 5-46
complexTypes to SQL, 5-38
overriding using SQLType attribute, 5-33
predicates, 5-59
scalar nodes, 5-59
simpleContent to object types, 5-45
simpleType XML string to VARCHAR2, 5-37
simpleTypes, 5-34
SQL to Java, 9-23
type, setting element, 5-32
XML to Java bean, XML schema entities, 9-23
maxOccurs, 5-38
MIME
overriding with DBUri servlet, 12-35
modes
CASCADE, 5-13
FORCE, 5-13
MULTISET operator
using with SYS_XMLGEN selects, 10-46
N
NamedNodeMap object, 8-21
namespace
defining, 3-28
handling in query rewrites, 5-62
handling in XPath, 5-62
W3C introducing, C-18
XDBResource, 13-17
XML schema URL, 5-5
xmlns, D-4
XMLSchema-Instance, 3-21
naming SQL objects
SQLName, SQLType attributes, 5-25
navigational access, 13-9
nested
generating nested XML using DBMS_
XMLGEN, 10-31
object tables, 3-32
sections in Oracle Text, 7-54
XML, generating with XMLElement, 10-7
XMLAgg functions and XSQL, 10-51
newDOMDocument, 8-20
5-61
O
object references and DBUri, 12-17
operators
CONTAINS, 4-38, 7-6
CONTAINS compared, 4-41
DEPTH, 15-8
EQUALS_PATH, 15-8
HASPATH, 7-12
INPATH, 7-12
MULTISET and SYS_XMLGEN, 10-46
PATH, 15-8
UNDER_PATH, 15-6
WITHIN, 7-7, 7-11
XMLIsValid, 6-9
Oracle Enterprise Manager
configuring Oracle XML DB, 21-7
console, 21-7
creating a view based on XML schema, 21-39
creating function-based index, 21-42
creating resources, 21-12
features, 21-3
granting privileges, XML Tab, 21-23
managing security, 21-22
managing XML schema, 21-27
Oracle Net Services, 1-12
Oracle Text
advanced techniques, 7-45, 7-49
ALTER INDEX, 7-10
attribute sections, constraints, 7-52
building query applications, 7-21
comparing CONTAINS and existsNode, 7-38
conference Proceedings example, 7-56
CONTAINS and XMLType, 4-38
CONTAINS operator, 7-6
creating index on XMLType columns, 4-11
creating on XMLType columns, 4-39
CTXSYS, 7-5
CTXXPATH, 7-45
DBMS_XDBT, F-25
installing, 7-4
Index-7
XDBResource.getLanguage(), E-10
XDBResource.getLastModDate, E-10
XDBResource.getOwnerId, E-10
XDBResource.setACL, E-10
XDBResource.setAuthor, E-10
XDBResource.setComment, E-10
XDBResource.setContent, E-10
XDBResource.setContentType, E-11
XDBResource.setCreateDate, E-11
XDBResource.setDisplayName, E-11
XDBResource.setInheritedACL, E-11
XDBResource.setLanguage, E-11
XDBResource.setLastModDate, E-11
XDBResource.setOwnerId, E-11
oracle.xdb.XDBResource
JNDI, 17-7
oracle.xdb.XMLType, 9-18
JNDI, 17-7
ora.contains
creating a policy for, 7-42
XPath full-text searches, 7-40
ordered collections in tables (OCTs), 5-72
default storage of VARRAY, 5-38
rewriting collection index, 5-61
P
PATH, 15-8
PATH_SECTION_GROUP
using, 7-10
PATH_VIEW, 3-38
structure, 15-3
Path-based access
explained, 13-9
pathname
resolution, 13-7
performance
improved using Java writeToStream, 13-12
improvement for structured storage, 3-25
piecewise update, 1-5
PL/SQL DOM
examples, 8-22
methods, 8-12
PL/SQL DOM API for XMLType, F-6
PL/SQL Parser for XMLType, F-13
Index-8
Q
query access
using RESOURCE_VIEW and PATH_
VIEW, 15-2
query results
presenting, 7-21, 7-34
query rewrite, 5-52
query-based access
using SQL, 13-12
querying
resources, 3-38
XML data, 4-17
XMLType, 4-18
XMLType,transient data,
4-26
R
rebuilding hierarchical indexes, 16-11
REF attribute, 5-39, 5-48
registerHandler, 12-26
Reinstalling
Oracle XML DB
reinstalling, A-4
Repository, 3-34, 13-4
based on WebDAV, 3-35
hierarchy explained, 3-35
query-based access, 3-36
where is the data stored, 13-6
resource id
new version, 14-5
RESOURCE_VIEW
explained, 15-2
PATH_VIEW differences, 15-4
querying resource documents, 3-38
structure, 15-3
resources
access using UNDER_PATH, 15-9
accessing Repository, 13-8
accessing with protocols, 19-6
changing privileges, 18-12
configuration management, 16-8
controlling access to, 18-7
creating from Enterprise Manager, 21-12
defined, 13-4
deleting, 13-7
deleting non-empty containers, 15-11
deleting using DELETE, 15-10
extending metadata properties, 13-17
inserting data using RESOURCE_VIEW, 15-9
management using DBMS_XDB, 16-2
managing, 18-11
multiple simultaneous operations, 15-12
required privileges for operations, 18-8
retrieving access control lists (ACLs), 18-12
setting property in access control lists
(ACLs), 18-11
storage options, 3-40
updating, 15-11
ResourceType
extending, 13-18
S
scalar nodes, mapping, 5-59
scalar value
converting to XML document using SYS_
XMLGEN, 10-45
schemaLocation, 5-9
schemaValidate, 3-24, 6-9
method, 5-15
searching CLOBs, 1-24
security
access control entries (ACEs), 18-6
aggregate privileges, 18-8
DBUri, 12-37
management using DBMS_XDB, 16-5
management with Enterprise Manager, 21-22
user and group access, 18-6
servlets
accessing Repository data, 13-13
and session pooling, 20-9
APIs, 20-10
AQ XML, 23-11
configuring, 20-12
configuring Oracle XML DB, 20-4
DBUri, URL into a query, 12-34
example, 20-10
explained, 1-30
installing, 20-11
session pooling, 20-9
session pooling and Oracle XML DB, 19-2
testing the, 20-12
writing Oracle XML DB HTTP, 20-4
XML manipulation, with, 20-3
session pooling, 20-9
protocol server, 19-2
setSchemaValidated, 6-10
Simple Object Access Protocol (SOAP) and
IDAP, 23-5
simpleContent
Index-9
Index-10
T
tableProps attribute, 5-71
tablespace
do not drop, A-2
transform, 6-2
triggers
BEFORE INSERT trigger, 3-24
BEFORE INSERT, using with XMLType,
creating XMLType, 4-37
using with XMLType, 4-37
3-23
U
UDT
generating an element from, 10-9
generating an element using XMLForest,
UNDER_PATH, 3-38, 15-6
summary, 15-5
UPDATE_VAL
binding XMLType objects to SQL, 17-2
updateXML, 5-70
creating views, 4-35
mapping NULL values, 4-35
replacing contents of node tree, 3-13
updating text node value, 3-12
10-10
updating
resources, 3-38, 15-11
same node more than once, 4-36
upgrading
existing installation, A-4
URI
base, C-28
UriFactory, 12-25
configuring to handle DBUri-ref, 12-38
factory method, 12-25
generating UriType instances, 12-25
registering ecom protocol, 12-27
registering new UriType subtypes, 12-26
registerURLHandler, 12-26
Uri-ref, see also Uri-reference, 12-4
Uri-reference
database and session, 12-17
datatypes, 12-6
DBUri, 12-10
DBUri and object references, 12-17
DBUri syntax guidelines, 12-13
DBUri-ref, 12-9
DBUri-ref uses, 12-17
DBUriType examples, 12-25
explained, 12-4
HTTP access for DBUri-ref, 12-34
UriFactory package, 12-25
UriType examples, 12-23
UriTypes, 12-22
UriTypes, 12-22
benefits, 12-6
creating Oracle Text index on column, 7-37
examples, 12-23
subtypes, advantages, 12-28
URL
identifying XML schema, for, 5-5
V
validating
examples, 6-10
isSchemaValid, 6-10
isSchemaValidated, 6-9
schemaValidate, 6-9
SetSchemaValidated, 6-10
W
W3C DOM Recommendation, 8-9
WebDAV
oracle.xdb.spi, 17-3
protocol server, features, 19-10
standard introduced, 3-35
WebFolder
creating in Windows 2000, 19-11
WITHIN
in Oracle Text, 7-7
limitations, 7-11
syntax, 7-11
writeToStream, 13-12
X
XDB$RESOURCE table, 13-18
XDBBinary, 13-5, 13-11
explained, 1-29
xdbconfig.xml, 19-2
XDBResource
JNDI Context output, 17-10
namespace, 13-17
xsd, 13-17
XDBSchema.xsd, 5-20
XDBUri, 12-5
XDBUriType
accessing non-schema content, 3-44
accessing Repository content, 3-44
defined, 12-2
stores references to Repository, 12-6
XDK for PL/SQL, backward compatibility,
8-2
Index-11
XML
binary datatypes, 5-35
fragments, mapping to LOBs, 5-40
primitive datatypes, 5-37
primitive numeric types, 5-35
XML DB Resource API for Java/JNDI, 17-2
XML DB, Oracle, 3-5
XML schema
and Oracle XML DB, 1-7, 5-5
benefits, 5-6
compared to DTD, B-31
complexType declarations, 5-42
creating default tables during registration, 5-71
cyclical references, 5-75
cyclical references between, 5-72
DTD limitations, B-33
elementFormDefault, 5-62
Enterprise Manager, managing them
from, 21-27
features, B-34
generating Java beans, 5-17
global, 5-11
inheritance in, complexType restrictions, 5-44
key feature explained, 1-5
local, 5-10
local and global, 5-10
managing and storing, 5-20
mapping to SQL object types, 8-10
navigating in Enterprise Manager, 21-28
registering, 5-8
registering using DBMS_XMLSCHEMA, 5-8
root, 5-20
SQL and Java datatypes, 9-23
SQL mapping, 5-29
storage and access, 5-12
storage of XMLType, 3-28
unsupported constructs in query rewrites, 5-55
updateXML(), 5-70
URLs, 5-16
validating an XML document, 3-22
W3C Recommendation, 3-17, 5-3
xdb.SQLType, 3-30
XMLType methods, 5-20
XML schema, creating a view in Enterprise
Manager, 21-39
Index-12
Index-13
Index-14