Вы находитесь на странице: 1из 394

Oracle 10g: XML Fundamentals

Volume 1 - Student Guide

n l y
e O
U s
A I
O
l &
D17320GC10
na
Edition 1.0

te r
August 2004
D39787 I n
c l e
r a
O
Author Copyright © 2004, Oracle. All rights reserved.

Glenn Stokol This documentation contains proprietary information of Oracle Corporation. It is


provided under a license agreement containing restrictions on use and disclosure and
is also protected by copyright law. Reverse engineering of the software is prohibited.
Technical Contributors If this documentation is delivered to a U.S. Government Agency of the Department of
and Reviewers Defense, then it is delivered with Restricted Rights and the following legend is
applicable:
Gert Van Barneveld Restricted Rights Legend
Mark Bauer
Use, duplication or disclosure by the Government is subject to restrictions for
Brian Boxx commercial computer software and shall be deemed to be Restricted Rights software
Scott Brewton under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013,
Niall Commiskey Rights in Technical Data and Computer Software (October 1988).

Ken Cooper This material or any portion of it may not be copied in any form or by any means
Olivier Le Diouris without the express prior written permission of Oracle Corporation. Any other copying
is a violation of copyright law and may result in civil and/or criminal penalties.
Mark Drake
Shelley Higgins If this documentation is delivered to a U.S. Government Agency not within the
Craig Hollister Department of Defense, then it is delivered with “Restricted Rights,” as defined in
FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).
Taj-ul Islam
Peter Laseau The information in this document is subject to change without notice. If you find any
problems in the documentation, please report them in writing to Education Products,
Yi. L. Lu Oracle Corporation, 500 Oracle Parkway, Redwood Shores, CA 94065. Oracle
Jack Melnick Corporation does not warrant that this document is error-free.
Steve Muench All references to Oracle and Oracle products are trademarks or registered trademarks
Valli Pataballa of Oracle Corporation.
Sunitha Patel
All other products or company names are used for identification purposes only, and
Marcus Pecher may be trademarks of their respective owners.
Aniket Raut
Mark Scardina
John Soltani n l y
Priya Vennapusa
Ulrich Vogel
e O
Jinyu Wang
Ted Witiuk
U s
Publisher
A I
Michael Sebastian
O
l &
n a
te r
I n
c l e
r a
O
Contents

Preface

I Introduction
Objectives I-2
Course Objectives I -3
Course Agenda I-4
Extensible Markup Language I-7
Advantages of Using XML I-8
XML Standards I-9
Document Object Model I-10
Simple API for XML I-11
Oracle XML Support I-12
XML in Oracle JDeveloper 10g I-13
Building XML Applications with Oracle Technology I-14
Course Environment and Data I-15
Creating a Workspace and Project in JDeveloper I-16
Creating an XML Document in JDeveloper I-17
Adding an XML Document to a Project I-18
Viewing an XML Document in a Browser I-19
Summary I-20
Practice I: Overview I-21

1 Introducing the XML Document


n l y
Objectives 1-2
Extensible Markup Language 1-3
e O
Example: A Simple XML Page 1-4
XML Document Structure 1-5
U s
The XML Declaration 1-6
Components of an XML Document 1-7
XML Elements 1-8 A I
Markup Rules for Elements 1-9
O
XML Attributes 1-10

l
Using Elements Versus Attributes 1-11&
XML Entities 1-12

n a
XML Comments 1-13

te r
A Well-Formed XML Document 1-14
Class Activity 1-15

I n
Comparing XML and HTML 1-16
XML Development 1-17

l e
Editing XML in Oracle JDeveloper 10g 1-18

c
Summary 1-19

r a
Practice 1: Overview 1-20

O
iii
2 Validating XML with Document Type Definitions (DTDs)
Objectives 2-2
What Is a Document Type Definition? 2-3
Why Validate an XML Document? 2-4
General DTD Rules 2-5
The Contents of a DTD 2-6
Example of a Simple DTD Declaration 2-7
Referencing the DTD 2-8
Element Declarations 2-9
Specifying Cardinality of Elements 2-11
Attribute Declarations 2-12
CDATA and Enumerated Attribute Types 2-13
NOTATION Declaration and Attribute Type 2-14
Specifying Default Attribute Values 2-15
Entities in XML 2-16
General Entity Declarations 2-17
Parameter Entities 2-19
Complete DTD: Example 2-20
Validating XML Against a DTD 2-21
Summary 2-22
Practice 2: Overview 2-23

3 Modularizing XML with Namespaces


Objectives 3-2
What Is an XML Namespace? 3-3
Why Use XML Namespaces? 3-4
n l y
Declaring XML Namespaces 3-5
XML Namespace Prefixes 3-6
e O
Example of XML Namespace Declarations 3-7
Scope of XML Namespace Declarations 3-8
U s
Invoking the ShowXmlNS Tool 3-9
Summary 3-10
Practice 3: Overview 3-11 A I
O
Objectives 4-2
l &
4 Validating XML by Using XML Schema

What Is an XML Schema? 4-3

n a
The Benefits of XML Schemas 4-4

te r
An Example XML Schema Document 4-5
Validating an XML Document with an XML Schema Document 4-6

I n
Referencing an XML Schema with the schemaLocation Attribute 4-7
Components of an XML Schema 4-8

l e
Example of XML Schema Components 4-9

c
The <schema> Declaration 4-10

r a
Global and Local Declarations 4-12
Declaring an Element 4-14
O Built-in XML Schema Data Types 4-15
Declaring a <simpleType> Component 4-17
Using <list> and <union> SimpleTypes 4-19
Declaring <complexType> Components 4-20

iv
Declaring a <sequence> 4-21
Declaring a <choice> 4-22
Declaring an Empty Element 4-23
Using Element Wildcards 4-24
Declaring Attributes 4-25
Attribute Declarations: Example 4-26
Declaring and Referencing an <attributeGroup> 4-27
Documenting the XML Schema 4-28
Creating an XML Schema Document in JDeveloper 4-29
Using the JDeveloper XML Schema Editor 4-30
Using the JDeveloper XML Schema-Aware XML Editor 4-31
Registering an XML Schema with JDeveloper 4-32
Using the XML Schema-Aware XML Editor 4-33
Validating an XML Document with its XML Schema in JDeveloper 4-34
Validating an XML Document with its XML Schema by Using oraxml 4-35
Applications for XML Schema 4-36
XML Schema Versus DTD 4-37
Converting a DTD to an XML Schema 4-38
Summary 4-39
Practice 4: Overview 4-40

5 Navigating XML Documents by Using XPath


Objectives 5-2
What Is XML Path Language? 5-3
The XPath Model 5-4
XPath Expressions 5-5
n l y
The Location Path Expression 5-6
Results of Location Path Expressions 5-7
e O
Location Steps in XPath Expressions 5-8
XPath Axes 5-9
U s
XPath Node Test Types 5-10
Unabbreviated and Abbreviated Expressions 5-11
A I
O
Abbreviated XPath Expression: Examples 5-13
XPath Predicates 5-14

XPath Functions 5-17


l &
Operators in XPath Expressions 5-16

Boolean Functions 5-18


n a
Number Functions 5-19

te
Node-Set Functions 5-20r
I n
String Functions 5-21
XSLT and XPath 5-22

c l e
Testing XPath Expressions 5-23
Using the TestXPath Tool 5-24

r a
Summary 5-25
Practice 5: Overview 5-26

O
6 Transforming XML by Using XSL Transformations
Objectives 6-2
What Is XSL? 6-3
XSL Transformations 6-4
The XSLT Stylesheet 6-5
v
XSLT Stylesheet: Example 6-6
Using an XSLT Stylesheet with an XML Document 6-7
Viewing the Transformed Document 6-8
JDeveloper Support for XSLT 6-9
Creating Template Rules 6-10
Getting Input Text with <xsl:value-of> 6-11
Applying Template Rules 6-12
Controlling Template Activation Order 6-14
Template Rules and Priorities 6-15
Default Template Rules 6-16
Effects of Default Template Rules 6-17
Looping with <xsl:for-each> 6-18
Specifying Output Formats 6-19
Attribute Value Templates 6-20
Creating Elements with Attributes 6-21
Sorting an XML Document 6-22
Conditional Processing with <xsl:if> 6-23
Conditional Processing with <xsl:choose> 6-24
Modes 6-25
Example of Using Modes 6-26
Calling Templates by Name 6-29
Creating and Using Parameters 6-30
Using the oraxsl Utility 6-31
Summary 6-33
Practice 6: Overview 6-34
n l y
7 XSQL Pages Publishing Framework
Objectives 7-2
e O
Web Application Architecture 7-3
XSQL Pages Publishing Framework 7-4
U s
Applications and Benefits of XSQL Pages 7-5
Structure of a Simple XSQL Page 7-6
A I
O
Creating an XSQL Page in JDeveloper 7-7
Creating Database Connections 7-8

Viewing an XSQL Page 7-10


l &
Creating an <xsql:query> Action Element 7-9

a
Customizing the <xsql:query> Output 7-11

n
te r
Using Parameters in XSQL Pages 7-12
Supplying Parameters to XSQL Pages 7-13
Parameters and Order of Precedence 7-14

I n
Providing a Fallback Query 7-15

l e
Results of Fallback Query: Example 7-16
An XSQL Page with Multiple Queries 7-17
c
r a
Transforming an XSQL Page with XSLT 7-18
XSQL Page with XSLT: Example 7-19

O Summary 7-20
Practice 7: Overview 7-21

vi
8 Additional Features in XSQL Pages
Objectives 8-2
Using CURSOR Expressions 8-3
Exchanging Data with XSQL Parameters 8-4
Setting Page Parameters 8-5
Including Parameters in an XSQL Page 8-7
Setting HTTP Cookie Values 8-9
Setting HTTP Session Variables 8-10
Aggregating Information 8-12
Including External Well-Formed XML 8-13
Results of Including XML 8-14
Data Manipulation by Using XSQL 8-15
Results of DML: Example 8-16
Posting XML Documents for DML Operations 8-17
Handling Posted XML Data 8-18
Transforming XML to Canonical Form 8-20
Summary 8-21
Practice 8: Overview 8-22

9 Introduction to Oracle XML DB (XML DB)


Objectives 9-2
What Is Oracle XML DB? 9-3
When to Use Oracle XML DB 9-4
How Is Oracle XML DB Implemented? 9-6
Oracle XML DB: Features 9-7
XMLType 9-10
n l y
When to Use XMLType 9-11
XML Schema Support in Oracle Database 10g 9-12
e O
XMLType and XML Schema 9-15
XML Schema Management 9-17
U s
Registering an XML Schema 9-18
Storage and Access Infrastructure 9-20
Local and Global XML Schemas 9-21 A I
Deleting an XML Schema 9-22
O
Validating XML 9-24
l &
Example of Deleting an XML Schema 9-23

Schema Validation 9-25

n a
te r
Overview of XML Repository 9-28
What Is the Repository? 9-29
XML Repository: Features 9-30

I n
Repository Support for Internet Protocols 9-31

e
Oracle XML DB Versioning 9-32

l
Benefits of Oracle XML DB 9-33
c
Summary 9-34

r a
Practice 9: Overview 9-35

O
vii
10 Generating XML from an Oracle Database 10g
Objectives 10-2
SQL/XML Generation Functions 10-3
The XMLElement() SQL/XML Function 10-4
XML Elements with Attributes 10-5
The XMLForest() SQL/XML Function 10-6
Generating Nested XML Elements 10-7
The XMLSequence() SQL/XML Function 10-8
The XMLConcat() SQL/XML Function 10-9
The XMLAgg() SQL/XML Function 10-11
Generating Master-Detail Content 10-12
A Complex Master-Detail: Example 10-13
The XMLColAttVal() SQL/XML Function 10-14
Native XML Generation 10-15
Using SYS_XMLGEN() 10-16
Using SYS_XMLAGG() 10-18
DBMS_XMLGEN 10-19
Summary 10-20
Practice 10: Overview 10-21

11 Managing XML Data in an Oracle 10g Database


Objectives 11-2
XMLType 11-3
The Benefits of Using XMLType 11-4
Declaring an XMLType 11-5
XMLType Storage Characteristics 11-6
n l y
Unstructured Versus Structured Storage 11-7
CLOB Versus Object-Relational Storage 11-8
e O
Loading Data into XMLType 11-9
Overview of Querying XML 11-10
U s
Subset of XMLType Member Functions 11-11
Querying an XMLType by Using XPath 11-12
Using the existsNode() Function 11-13 A I
Using the extract() Function 11-14
O
l &
Combining extract() and existsNode() 11-16
Using the extractValue() Function 11-17

a
Filtering with extractValue() 11-18

n
Summary 11-19

te r
Practice 11: Overview 11-20

I n
12 Creating XMLType Views
Objectives 12-2

l e
What Are XMLType Views? 12-3

c
Creating XMLType Views 12-4

r a
Creating Non-Schema-Based Views 12-5
Non-Schema XMLType Views with SQL/XML Functions 12-6
O Non-Schema XMLType Views with Object Types and SYS_XMLGEN() 12-7
Creating XML Schema-Based Views 12-8

viii
XML Schema XMLType Views with SQL/XML Functions 12-9
Using Namespaces with SQL/XML Functions 12-11
XML Schema XMLType Views with Object Types 12-12
Creating XMLType Views from XMLType Tables 12-13
DML with XMLType Views 12-14
Example of an Updateable XMLType View 12-15
Summary 12-17
Practice 12: Overview 12-18

13 Executing SQL Operations on XML


Objectives 13-2
Overview of Transforming XML 13-3
Transform Functions 13-4
Using the XMLTransform() Function 13-5
Results of Using the XMLTransform() Function 13-7
Benefits of XML Transformation 13-8
Updating XML 13-9
Using the updateXML() Function 13-10
Piecewise Update of XML 13-11
Deleting Rows Based on XML Contents 13-13
Indexing XML Data 13-14
Function-Based Indexes 13-15
Using a CTXXPATH Index 13-16
Using a Context Index 13-17
Summary 13-18
Practice 13: Overview 13-19
n l y
14 Accessing XML Through URIs
e O
Objectives 14-2
Definitions 14-3
U s
URI Support in Oracle Database 14-4
The DBUri Servlet 14-5
Retrieving Table Data as an XML Document 14-6 A I
Retrieving a Single Row as XML 14-7
O
Retrieving Column Data 14-9
l &
Retrieving Multiple Rows as XML 14-8

a
Retrieving the Column Text 14-10

n
te r
Using Multiple Predicates 14-11
Applying a Stylesheet 14-12
Results After Applying a Stylesheet 14-13

I
Summary 14-14
n
Practice 14: Overview 14-15

c l e
r a
O
ix
Appendix A: Practice Solutions

Appendix B: Table Descriptions and Data

Appendix C: Additional Information About Document Type Definitions


Objectives C-2
Declaration Types in a DTD (Revisited) C-3
Referencing the DTD (Revisited) C-4
Element Declarations (Revisited) C-5
Cardinality of Elements (Revisited) C-7
Attribute Declarations (Revisited) C-8
CDATA and Enumerated Attribute Types C-9
The ENTITY and ENTITIES Attribute Types C-10
The ID Attribute Type C-12
The IDREF and IDREFS Attribute Types C-13
The NMTOKEN and NMTOKENS Attribute Types C-14
Entities in XML (Revisited) C-15
Summary C-16

Appendix D: Using Oracle XML Developer’s Kit


Objectives D-2
Overview of XML Developer’s Kit D-3
XML Trees D-4
XML Trees: Example D-5
XML Developer’s Kit Components D-6
XML Parsers D-8
n l y
XSL Transformation (XSLT) Processors D-9
Oracle XML Schema Processors D-11
Using XML Schema Processors D-12
e O
XML Class Generators D-13
Using XML Class Generators D-14
U s
Oracle XDK for JavaBeans D-15
XML SQL Utility D-17
A I
Applications of XSU D-18
XSU Command-Line Utility D-19 O
Using the OracleXML Utility D-20
l &
n a
Updating and Deleting by Using XSU API D-22
Generating an XML Schema with XSU D-23
TransX Utiliity D-25

te r
Using TransX Utility D-26
Summary D-28
I n
c l e
Appendix E: Managing External Tools in JDeveloper
Objectives E-2

r a
External Tools with JDeveloper E-3
Managing External Tools E-4

O Adding an External Tool E-5


Editing an External Tool E-9
Removing an External Tool E-10
Summary E-11

x
Preface

n l y
e O
U s
A I
O
l &
na
te r
I n
c le
ra
O
n l y
e O
U s
A I
O
l &
na
te r
I n
c le
ra
O
Profile

Before You Begin This Course


Before you begin this course, you should have thorough knowledge of SQL, and SQL*Plus or
iSQL*Plus. The following Oracle University course is a prerequisite:
• Oracle Database 10g: Introduction to SQL
How This Course Is Organized
Oracle 10g: XML Fundamentals is an instructor-led course featuring lectures and hands-on
exercises. Online demonstrations and practice sessions reinforce the concepts and skills that are
introduced.

n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O

Preface-3
Related Publications

Oracle Publications
Title Part Number
Oracle® XML DB Developer’s Guide (10g Release 1) B10790-01
Oracle® XML Developer’s Kit Programmer's Guide (10g Release 1) B10794-01
Oracle® Database SQL Reference (10g Release 1) B10759-01
PL/SQL Packages and Types Reference (10g Release 1) B10802-01

Additional Publications
• System release bulletins
• Installation and user’s guides
• Read-me files
• International Oracle Users Group (IOUG) articles
• Oracle Magazine

n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O

Preface-4
Typographic Conventions

Typographic Conventions in Text


Convention Element Example
Bold Emphasized words and phrases To navigate within this application, do
in Web content only not click the Back and Forward buttons.

Bold italic Glossary terms (if there is a The algorithm inserts the new key.
glossary)

Brackets Key names Press [Enter].

Caps and Buttons, Click the Executable button.


lowercase check boxes, Select the Registration Required check
triggers, box.
windows
Assign a When-Validate-Item trigger.
Open the Master Schedule window.

Carets Menu paths Select File > Save.

Commas Key sequences Press and release these keys one at a


n l y
time:
[Alt], [F], [D]
e O
U s
A I
O
l &
n a
te r
I n
c le
r a
O

Preface-5
Typographic Conventions (continued)

Typographic Conventions in Text (continued)


Convention Object or Term Example
Courier New, Code output, Code output: debug.seti (‘I’,300);
case sensitive SQL and PL/SQL
SQL code elements: Use the SELECT command to view
code elements, Java
information stored in the last_name column of the emp
code elements,
table.
directory names,
filenames, Java code elements: Java programming involves the
passwords, String and StringBuffer classes.
pathnames, URLs, Directory names: bin (DOS), $FMHOME (UNIX)
user input,
usernames Filenames: Locate the init.ora file.
Passwords: Use tiger as your password.
Pathnames: Open c:\my_docs\projects.
URLs: Go to http://www.oracle.com.
User input: Enter 300.
Usernames: Log on as scott.
Initial cap Graphics labels Customer address (but Oracle Payables)
(unless the term is a
proper noun)
n l y
Italic Emphasized words
and phrases in print
Do not save changes to the database.

e O
For further information, see Oracle7 Server SQL
publications, titles of
books and courses,
Language Reference Manual.

U s
variables

A I
Enter user_id@us.oracle.com, where user_id is
the name of the user.
Plus signs Key combinations
O
Press and hold these keys simultaneously:
[Control] + [Alt] + [Delete]

l &
Quotation
marks
Lesson and chapter
titles in cross
n a
This subject is covered in Unit II, Lesson 3, “Working with
Objects.”

te r
references, interface
elements with long Select the “Include a reusable module component” and

I n
names that have only
initial caps
click Finish.

cl e Use the “WHERE clause of query” property.

r a
O

Preface-6
Typographic Conventions (continued)

Typographic Conventions in Navigation Paths


This course uses simplified navigation paths to direct you through Oracle applications, as in
the following example.
Invoice Batch Summary
(N) Invoice > Entry > Invoice Batches Summary (M) Query > Find (B) Approve
This simplified path translates to the following sequence of steps:
1. (N) From the Navigator window, select Invoice > Entry > Invoice Batches Summary.
2. (M) From the menu, select Query > Find.
3. (B) Click the Approve button.
Notation:
(N) = Navigator (I) = icon
(M) = menu (H) = hyperlink
(T) = tab (B) = button

n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O

Preface-7
n l y
e O
U s
A I
O
l &
na
te r
I n
c le
ra
O
Introduction

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Discuss the goals of the course and the agenda
• Define XML and standards covered in this course
• List Oracle product support for XML
• Describe the course environment and data
• Use JDeveloper to create, open, and edit an XML
document
• View an XML document in a browser

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
This introductory lesson discusses the course goals and daily agenda of the topics to be
covered. The XML terminology and XML standards used in this course are briefly
described.
O
l &
Oracle products that support development of XML data, XML applications, and storage for
XML data are identified. The course technical environment and data used are described

n a
followed by instructions about using JDeveloper to open and edit XML documents, and
r
about using a Web browser to view the document.

te
I n
c l e
r a
O
Oracle 10g: XML Fundamentals I-2
Course Objectives

After completing this course, you should be able to do


the following:
• Create XML documents
• Validate XML documents by using standard XML
techniques
• Transform XML documents by using stylesheets
and XPath expressions
• Store and query XML in an Oracle database
• Generate XML from an Oracle database
• Use Oracle XDK tools and utilities

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Course Objectives
U s
After completing this course, you should be able to:
• Create well-formed and valid XML documents
A I
O
• Use tools and XML standards to validate XML documents

XPath expressions
l &
• Transform XML documents by using Extensible Style Sheet Language (XSL) and

a
• Store, generate, query, and retrieve XML data by using an Oracle database
n
r
• Identify and use the capabilities of Oracle XDK and some of its tools

te
I n
c l e
r a
O
Oracle 10g: XML Fundamentals I-3
Course Agenda

Lessons that are to be covered on Day 1:


1. Introducing the XML Document
2. Validating XML with Document Type Definitions
(DTD)
3. Modularizing XML with Namespaces
4. Validating XML by Using XML Schema
5. Navigating XML Documents by Using XPath

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Course Agenda
U s
A I
The agenda is a suggested list of lessons to be covered each day. It is possible that the
schedule may differ each time the course is delivered. Day 1 is devoted to the following
aspects of XML:
O
l &
• An introduction to the course, the environment, and the tools used
• The XML standards and basics of using some of these standards, such as the validation
with a DTD and XML Schema
n a
r
• Using XML Namespaces and XPath expressions

te
I n
c l e
r a
O
Oracle 10g: XML Fundamentals I-4
Course Agenda

Lessons that are to be covered on Day 2:


6. Transforming XML by Using XSL Transformations
(XSLT)
7. XSQL Pages Publishing Framework
8. Additional Features in XSQL Pages
9. Introducing Oracle XML DB (XML DB)
10. Generating XML from an Oracle Database 10g

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Course Agenda (continued)
U s
Day 2 topics cover:

A I
• Transformation of XML by using XSL and XSLT; the last lesson covers XML

O
standards. A review of XPath would be good before starting XSL material.

l &
• The remaining lessons discuss Oracle technology that makes it easier to generate XML
content from data in the database by using SQL. The key areas covered are:
a
- Using the XSQL Pages framework in Oracle Application Server or middle-tier
n
environment

te r
- Using Oracle XML Database to store, retrieve, and generate XML content

I n
c l e
r a
O
Oracle 10g: XML Fundamentals I-5
Course Agenda

Lessons that are to be covered on Day 3:


11. Managing XML Data in an Oracle Database 10g
12. Creating XMLType Views
13. Executing SQL Operations on XML
14. Accessing XML Through URIs

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Course Agenda (continued)
U s
Topics on Day 3 include:

A I
• Further exploration into the XML capabilities of the XDB in the Oracle database by
using functionality accessible through SQL.
O
servlet in the database
l &
• Generating XML data from database tables by using URL requests to the DBUri

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals I-6
Extensible Markup Language

Extensible Markup Language (XML) describes data


objects called XML documents that are composed of
markup and data.

Web data XML processors

Markup and data XML document


Custom tags

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Extensible Markup Language
U s
XML describes data objects called XML documents that:

A I
• Are composed of markup language for structuring the document data

O
• Support custom tags for data definition, transmission, validation, and interpretation

• Are processed by XML processors


l &
• Have become a standard way to describe data on the Web

n a
XML was developed by an XML working group headed by the World Wide Web

te r
Consortium (W3C) with the following design goals:
• XML is usable over the Internet.

I n
• It supports a wide variety of applications.

c l e
• It is compatible with Standard Generalized Markup Language (SGML).
• XML can be processed using easy-to-write programs.

r a
• It has a minimum number of optional features.
• XML is human-legible and reasonably clear.
O
• XML enables quick design preparation.
• It enables formal and concise design.
• The XML documents are easy to create.
• The XML documents can be verbose.

Oracle 10g: XML Fundamentals I-7


Advantages of Using XML

XML enables:
• A simple and extensible way to describe data
• The ability to interchange data
• Simplified business-to-business communication
• Writing of smart agents
• The ability to perform smart searches
A sample XML document:
<?xml version="1.0"?>
<books>
<title>Building Oracle XML Applications</title>
<title>Oracle XML Handbook</title>
<title>Beginning XML Second Edition</title>
</books>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Advantages of Using XML
U s
A I
XML’s strongest point is its ability to perform data interchange. Because different groups of
people rarely standardize on a single set of tools, it takes a significant amount of work for

O
two groups to communicate. XML makes it easy to send structured data across the Web so
that nothing gets lost in translation.

l &
When using XML, you can receive XML-tagged data from your system, and you can receive

n a
XML-tagged data from another system. Neither of the users has to know how the other

te r
user’s system is organized. If another partner or supplier teams up with your organization,
you do not have to write code to exchange data with their system. You simply require them

I n
to follow the document rules defined in the DTD. You can also transform those documents
using XSLT.

c l e
When writing an agent, one of the challenges is to make sense of incoming data. A good

r a
agent interprets information intelligently, and then responds to it accordingly. If the data

O
sent to an agent is structured with XML, it is much easier for the agent to understand exactly
what the data means and how it relates to other pieces of data it may already know.
The slide shows a simple example of an XML document containing a list of book titles. The
XML document can be embellished or restructured depending on how it will be used.

Oracle 10g: XML Fundamentals I-8


XML Standards

Defines and Defines and


validates validates
2 5
Document type XML schema
definition
Locates /Catalog/Item
Uniquely identifies nodes
elements 4 XPath
Used by
1
Applies Transformed
XML language
to
http://www.hr.com/catalog Processed
by 6
3 XML namespace XSL/XSLT Output
stylesheet document

XML processor (DOM and SAX API)


n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Standards
U s
The following XML standards are covered in this course:

A I
1. The XML language specification defines the rules that govern XML document
structure, and how XML processors must read them.
O
2. A document type definition (DTD) provides the definition and relationships of

l &
elements contained in an XML document. A DTD validates an XML document.

a
3. XML Namespaces provide a mechanism to distinguish elements with the same name
n
te r
but different definitions used in the same XML document.
4. The XML Path Language (XPath) provides syntax for searching an XML Document.
XPath expressions are used in an XSL stylesheet to match specific nodes.
I n
5. An XML Schema provides a way to describe the XML document structure using data

c l e
type definitions and uses namespace support. XML Schema is the preferred way to
validate XML documents.

r a
6. The Extensible Style Sheet Language (XSL) is implemented by XSL
Transformations (XSLT) to specify how to transform an XML document into another
Odocument. XSLT uses an XML vocabulary for transforming or formatting XML
documents.
The next two pages briefly discusses XML Programming Models or APIs, such as the
Document Object Model (DOM) and Simple API for XML (SAX), which are used by XML
processors for processing XML documents.
Oracle 10g: XML Fundamentals I-9
Document Object Model

Document Object Model (DOM):


• Defines programming interfaces for accessing and
changing an XML document as a tree structure
• Is defined by a W3C recommendation
DOM API:
• Is platform- and language-independent
• Stores an entire XML document tree in memory
• Can dynamically access and update the content,
structure, and style of documents
• Level 2 provides specialized interfaces dedicated
to XML

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Document Object Model
U s
A I
Document Object Model (DOM) is a W3C standard (recommendation) that defines an API
used to access and manipulate XML (or HTML) documents. When using the DOM API, the

O
whole XML document is read into memory, making its entire tree structure accessible to the
API.

l &
The DOM API Core standard has evolved and is implemented by most XML Parsers, which

n a
typically support some level of DOM specification. Current DOM specification levels are:

documents.
te r
• DOM Level 1 defines ways to navigate and manipulate the content of HTML or XML

I n
• DOM Level 2 extends Level 1 by adding support for XML Namespaces, filtered

c l e
views, ranges, events, and other features.
• DOM Level 3 is a working draft, that is, under development and subject to change.

r a
Oracle XML Parser supports most of DOM Level 2 and some Level 3 features.

O
Note: Using the DOM API to process large documents can consume more memory resource
as compared to working on the documents by using the stream-based processing approach
provided by SAX.

Oracle 10g: XML Fundamentals I-10


Simple API for XML

Simple API for XML (SAX):


• Is an event-based API for reading XML documents
• Reads a document as a serialized (ordered) event
stream of data
• Uses events to notify programs when it detects
document objects, such as start and end tags
• Does not store the document in memory and does
not support random-access manipulation
• Is a good choice for processing very large
documents
• Is developed independently of W3C

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Simple API for XML
U s
A I
Simple API for XML (SAX) processing model is event-based. A program using SAX reads
an XML document as a serialized stream of data, that is, one piece at a time. The SAX XML

O
Parser does not read an entire XML document into memory and uses events to notify the

• A start tag
l &
program when it encounters a document object, such as:

• An end tag
n a
• Character data
• Processing instructions
te r
I n
Your program can then act on these events to save or process the recognized object. An

c l e
important feature of SAX is that the document is not read into memory, like the DOM model
requires. This makes SAX a very good choice when processing very large documents,

a
because the program does not consume as much memory as DOM API.
r
O
Because of its popularity, SAX has become a de facto standard. Many XML Parsers provide
support for the API. Strictly speaking, SAX, which has been developed independently of the
W3C organization, has not been ratified as a standard or recommendation.
Note: Oracle XML Parser includes support for both DOM and SAX API.

Oracle 10g: XML Fundamentals I-11


Oracle XML Support

Oracle products provide support for XML in:


• Development tools

• Middle-tier frameworks

• Database storage Oracle XDK 10g

Includes the Oracle


XML Database (XDB)

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Oracle XML Support
U s
A I
Development Tools and Frameworks: Oracle XML Database (XDB), Oracle JDeveloper
10g, Oracle Internet File System (iFS), Oracle Application Development Framework (ADF)

O
in JDeveloper, Oracle Portal, Oracle Application Server Reports Services, and Oracle

l &
Dynamic Services can be used to build XML applications.
Database and Middle-Tier Frameworks: Oracle Application Server 10g provides the

n a
environment for the XSQL Pages framework, J2EE services which support XML
applications, and Web Services.

te r
Database Storage: In Oracle Database 10g, the Oracle XDB enables XML documents to be
I n
stored in and retrieved from relational tables, XMLType columns, and character large object

l e
(CLOB) types. Oracle Text (interMedia Text) can be used to efficiently search XML

c
documents stored in XMLType or CLOB columns.

r a
Oracle XML Developer’s Kit (XDK) 10g: Oracle XDK 10g is available in Oracle

O
JDeveloper 10g, Oracle Application Server 10g, and Oracle Database 10g. Oracle XDK
provides the following components, tools and utilities:
• XML Parsers, XSLT Processors, XSLT VM, XML Schema processors
• XML Java Beans, XML Class Generator, XSQL Servlet, XML SQL Utility (XSU)
• XML Pipeline Processor, TransX Utility
Oracle 10g: XML Fundamentals I-12
XML in Oracle JDeveloper 10g

Oracle JDeveloper 10g is a development tool that:


• Is used for:
– Building Java, XML, and PL/SQL applications
– Debugging the applications
– Deploying Internet-enabled applications
• Includes Oracle Application Development
Framework (ADF)
• Enables seamless Java, XML, XML
and SQL development of: Java
– Java for distributed code
– XML for portable data
– SQL for querying
SQL

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML in Oracle JDeveloper 10g
U s
A I
Oracle JDeveloper 10g is a powerful development tool for building, debugging, and
deploying J2EE, Web services, and Internet applications. Oracle JDeveloper 10g:

O
• Is an integrated development environment (IDE) that provides end-to-end support for

l &
developing, debugging, and deploying J2EE applications and Web services
• Provides a flexible environment for creating, editing, and debugging XML
a
applications, supporting the latest XML and Internet standards
n
te r
• Provides developers with a set of well-integrated tools to productively develop and
deploy applications by using Java, XML, PL/SQL, and SQL at low cost

I n
• Maximizes developer productivity by supporting the complete development life cycle
from modeling, coding, and debugging to testing and profiling
l e
• Provides access to source code control to manage the entire development process and
c
r a
enable distributed development teams to work cooperatively
• Includes the Oracle Application Development Framework (ADF), previously known as
OBusiness Components for Java, a 100% Java, XML-powered application component
framework that dramatically simplifies the development, deployment, and
customization of Internet-enabled applications
This course makes use of the XML support available in JDeveloper.

Oracle 10g: XML Fundamentals I-13


Building XML Applications with Oracle
Technology

• An XML application is an application process that


operates on XML data, either stored in or
generated from some data source.
• Oracle XML applications can be built in one of the
following ways:
– Nonprogrammatically
– Programmatically

Client
Application Database
server

XML application
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Building an XML Application with Oracle Technology
U s
A I
The diagram illustrates where an XML application processing XML data (solid lines)can run
(dotted lines) on the client, middle tier, or the database. The data may also reside in the
Oracle database in XML or relational form.
O
XML Applications Without Programming
l &
n a
Oracle XML Developer’s Kit (XDK) provides components, such as the XSQL servlet, which
process XSQL pages containing SQL statements and generate a result containing database

te r
data in an XML format. The XSQL servlet can be installed on any Java-enabled Web server,
such as Oracle Application Server 10g. The Oracle DBUri servlet provides a browser-based
I n
interface for easy retrieval and transformation of data stored in an Oracle Database 10g.

l e
XML Applications by Using Programming
c
r a
Applications can be developed with the APIs provided by the Oracle XDK. Web
applications, developed with JDeveloper, can use JDBC to connect with an Oracle database
O
to create powerful yet relatively simple data-driven XML applications.
Oracle Database 10g has inbuilt features for storing, manipulating, transforming and
validating XML data. These features are accessible through the Oracle XDK and XML
functionality available to SQL and PL/SQL services in the database.

Oracle 10g: XML Fundamentals I-14


Course Environment and Data

Client Middle tier Database

Browser Oracle XDK HR Schema


iSQL*Plus and XSQL servlet Oracle XML/DB
SQL*Plus DBUri servlet
Oracle XDK utilities

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Course Environment and Data
U s
Client Software

A I
• Oracle JDeveloper 10g for creating, editing, and validating XML documents

O
• Internet Explorer for viewing XML documents and transformations, interacting with

folder functionality
l &
the XSQL and DBUri servlets in the middle tier, and accessing the Oracle XML/DB

a
• iSQL*Plus or SQL*Plus to execute SQL or PL/SQL operations on the database data
n
te r
• Oracle XML Developer's Kit and Utilities for command-line processing operations
• Java classes that use the Oracle XML Parser:

I n
- The TestXPath class to test XPath expressions on XML documents
- The ShowXmlNS class to display the effects of using XML Namespaces

c l e
Middle-tier Software

r a
• Production environments will run the XSQL servlet in Oracle Application Server 10g.
• Development environments, as in this course, use JDeveloper’s embedded J2EE
O
Container to run the middle-tier software in the client.
Database Software
• Oracle Database 10g with the Oracle XML/DB features installed and enabled
• ORAx schemas that hold copies of the data from the HR Oracle Sample Schema.
Oracle 10g: XML Fundamentals I-15
Creating a Workspace and Project in
JDeveloper

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating a Workspace and Project in JDeveloper
U s
A I
When working with XML documents in JDeveloper, first create or open a workspace with a
project. A workspace contains one or more projects. A project contains one or more

O
application files. The steps to create a new workspace with a project are:
1. Select File > New …

l &
2. Select the General category in the New Gallery window and double-click Workspace
and follow the wizard prompts.
n a
te r
3. In the Create Workspace window:
a. Enter a Workspace Name (this becomes the file name)

I n
b. Enter the Directory Name for the workspace file
c. Ensure that the Add a New Empty Project check box is selected

le
d. Click OK
c
4. In the Create Project window:

r a
a. Enter a Project Name

Ob. Enter the Directory Name for the project


c. Click OK
Note: To open an existing workspace:
1. Select File > Open …
2. Locate and double-click a file name with a .jws extension
Oracle 10g: XML Fundamentals I-16
Creating an XML Document in JDeveloper

3 4

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating an XML Document in JDeveloper
U s
To create a new XML Document in a project:

A I
1. Select the project file in the Navigator and click File > New …
2. Expand the General category and select the XML node
O
3. Double-click XML Document under Items
4. In the Create XML File window:
l &
a. Enter the File Name
n a
c. Click OK
te r
b. Enter, or Browse to, a Directory Name to store the file

I n
The XML document is created as a child entry of the project in the Navigator, and its initial

c l e
content is displayed in the JDeveloper XML Editor window. The XML document also
contains the following line:

r a <?xml version='1.0' encoding='windows-1252'?>


Note: This line of text may differ if JDeveloper is running on a different platform.
O
Oracle 10g: XML Fundamentals I-17
Adding an XML Document to a Project

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Adding an XML Document to a Project
U s
To add an existing XML document to a project:

A I
1. Right-click the project name in the Navigator and click Add to Project …
2. In the Add Files to <project name> window:
O
b. Click Open
l &
a. Browse the directories to locate and select an XML file

n a
The existing XML document will be added as a node to the project and opened in the
JDeveloper XML Editor.

te r
Alternatively, you can use the following sequence:
I n
1. Select the project in the Navigator.

l e
2. Click File > Open…

c
a. Browse the directories to locate and select the XML document or file.

r a
b. Click Open.

O
Oracle 10g: XML Fundamentals I-18
Viewing an XML Document in a Browser

Use Windows
1
Explorer

Double-click

Use a JDeveloper
External Tool

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Viewing an XML Document in a Browser
U s
XML document in the browser, you can:
A I
In the course environment, Windows Internet Explorer is the default browser. To display the

1. Open the Windows Explorer application


O
3. Double-click the XML document file name
l &
2. Navigate to the directory where the XML document resides

a
Note: The browser displays the XML document tree, which can be expanded or collapsed.
n
te r
Alternatively, you can add your browser command line to be initiated from the JDeveloper
Tools menu. This is done by creating an External Tools command by using the Tools >

I
External Tools… menu. n
l e
In this course, JDeveloper is already set up to include Internet Explorer in the Tools menu,

c
as seen in the diagram. To launch the browser from the Tools menu:

r a
1. Select the XML document in Navigator

O
2. Click Tools > Internet Explorer
In this course, you can also right-click the XML file in the JDeveloper Navigator and XML
Editor, and select Internet Explorer from the context menu.
Note: Read Appendix E to learn how to create and access an External Tool from within
JDeveloper.
Oracle 10g: XML Fundamentals I-19
Summary

In this lesson, you should have learned how to:


• Describe XML
• Explain the XML standards covered in this course
• Describe the Oracle tools that support XML
• Use JDeveloper to:
– Create a workspace and project for XML documents
– Create XML documents in a project
– Add existing XML documents to a project
– View an XML document with a browser or by using
an external tool added to the JDeveloper Tools
menu

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
Extensible Markup Language (XML) is used to annotate data by using markup to describe
the data. The markup tags are user defined, and therefore, extensible to suit the requirements
of the author or application that creates the document.
O
l &
The XML standards are W3C recommendations. If you are adhering to the XML
recommendations, your XML documents must have their structure defined by a DTD or an

n a
XML Schema, enabling the document to be validated and meaningfully processed by all its
consumers.

te r
Extensible Style Sheet Language (XSL) processors can consume an XML document
I n
enabling it to be transformed and formatted into another type of document. Using XPath

l e
expressions, XSL processors can search for the desired XML elements to be transformed

c
and formatted according to the rules specified in a stylesheet.

r a
JDeveloper provides tools needed to create, edit, perform well-formed checks, and validate

O
XML documents, and can be enabled to access external tools to perform operations on XML
document. JDeveloper uses a workspace containing a project of related files to develop
XML applications.

Oracle 10g: XML Fundamentals I-20


Practice I: Overview

This practice covers the following topics:


• Opening the course application workspace and
project with JDeveloper
• Creating a basic XML document using JDeveloper
• Opening an existing XML document in JDeveloper
• Viewing XML documents in Internet Explorer

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Practice 1: Overview
U s
JDeveloper needed to create XML documents, such as:
A I
The goal of this practice is to help you become familiar with the basic features of

• Opening a workspace
O
• Creating an XML document
• Opening and existing XML document
l &
n a
You use a browser, such as Internet Explorer, to view simple XML documents to view the

te r
default visual presentation style of XML data in the browser. Initially, the browser displays
the XML document content in a tree-like structure.

I n
Subsequent lessons and practices discuss how to use XML editing features of JDeveloper.

c l e
r a
O
Oracle 10g: XML Fundamentals I-21
Practice I
The goal of this practice is to become familiar with the basic JDeveloper features needed to
create and open XML documents, and to experience the default appearance of an XML
document in an XML-enabled browser.
1. Start Oracle JDeveloper by using the icon on the desktop.

2. Open an existing workspace called XMLFundamentalsWorkspace.jws located


in the E:\labs directory. The workspace contains a project called
XMLLabsProject.

3. Create an XML document called employees.xml.


a. Add the following employees XML element after the XML declaration:

<?xml version='1.0' encoding='windows-1252'?>


<employees>
Company Employee Data
</employees>

Note: The first line, containing the XML Declaration, will automatically be
inserted for you.
b. Save the file by using the File > Save menu (or the Save toolbar icon).

l
4. Open and add an existing XML document called regions.xml to your project. The
XML document is located in the E:\labs\lab directory.
n y
5. View the XML documents in the Internet Explorer browser.
e O
U s
a. In Windows Explorer, double-click employees.xml file in the
E:\labs\lab directory to display the file in the browser.

browser. A I
b. In JDeveloper, use Tools > Internet Explorer to display regions.xml in the

O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals I-22
Introducing the XML Document

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe XML
• Describe the structure of an XML document
• List the components of an XML document
– Elements
– Attributes
– Entities
• Create a well-formed XML document
• Use XML Editor in JDeveloper

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
Extensible Markup Language (XML) is a markup language that provides a universal format
for structured documents and data on the Web. This lesson introduces:
• The structure of an XML document
O
• The components of an XML document

l &
• How to create an XML document that meets the requirements of a well-formed
document
n a
r
• How to use XML Editor in JDeveloper

te
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 1-2
Extensible Markup Language

Extensible Markup Language (XML):


• Describes data objects called XML documents
• Is composed of markup language for structuring
data
• Supports custom tags for definition, transmission,
validation, and interpretation of data
• Conforms to Standard Generalized Markup
Language (SGML)
• Has become a standard way to
describe data on the Web
• Is processed by XML processors

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Extensible Markup Language
U s
A I
XML is the abbreviation for Extensible Markup Language. XML documents look similar to
Hypertext Markup Language (HTML) documents, although they are very different.

O
HTML is a markup language, primarily used for formatting and displaying text and images
in a browser.
l &
a
XML is a markup language for structuring data rather than formatting information.

n
te r
You use XML to create a document that contains structured data that can be used or
interpreted by other applications. The format or structure is straightforward and can be used

I n
by any person or program that can read text.
Unlike HTML, the tags in XML are extensible, and so you can create your own tags as you
l e
need them. HTML has a set of predefined formatting tags that you can use, but you cannot
c
r a
create your own.
XML is part of the World Wide Web Consortium (W3C) standards.
O
Oracle 10g: XML Fundamentals 1-3
Example: A Simple XML Page

<?xml version="1.0"?>
<employees>
<employee>
<employee_id>120</employee_id>
<last_name>Weiss</last_name>
<salary>8000</salary>
</employee>
<employee>
<employee_id>121</employee_id>
<last_name>Fripp</last_name>
<salary>8200</salary>
</employee>
</employees>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example: A Simple XML Page
U s
A I
The example of a simple XML document uses nested elements to describe the employee
data. Elements are identified by tag names, such as employee, employee_id, and

O
last_name. Tag names are distinguishable as markup, rather than data, because they are
surrounded by angle brackets (< and >).

l &
Note: In XML, an element includes the start tag (<employees>), end tag
a
(</employees>), and all the markup and character data contained between the tags.
n
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 1-4
XML Document Structure

An XML document contains the following parts:


1. Prologue
2. Root element
3. Epilogue

<?xml version="1.0" encoding="WINDOWS-1252"?> 1


<!–- this is a comment -->
<employees>
... 2
</employees>

<?gifPlayer size="100,300" ?> 3

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Document Structure
U s
An XML document contains the following parts:
• The prologue, which may contain the following information:
A I
O
- XML declaration (optional in XML 1.0, mandatory in XML 1.1)

document structure
l &
- Document type definition (DTD), which is required only to validate the

a
- Processing instructions and comments, which are optional
n
te r
• The root element, which is also called the “document element”
• An epilogue, which contains processing instructions and comments

I n
An XML document can also contain processing instructions, giving commands or
information to an application that is processing the XML data.

c l e
Processing instructions have the format <?target instructions?>, where the target is

r a
the name of the application that is expected to do the processing, and the instructions consist
of a string of characters that embodies the information or commands for the application to
O
process.

Oracle 10g: XML Fundamentals 1-5


The XML Declaration

XML documents must start with an XML declaration.


The XML declaration:
• Looks like a processing instruction with the xml
name. For example:
<?xml version="1.0" encoding="WINDOWS-1252"?>
<document-root>
...
</document-root>
• Must contain the version attribute
• May (optionally) include:
– The encoding attribute
– The standalone attribute
• Is optional in XML 1.0, but mandatory in XML 1.1
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XML Declaration
U s
A I
It is generally recommended that you start an XML document with an XML declaration. If it
is present, it must be the first line in the document. Although the XML declaration looks like

O
a processing instruction, it is really a simple declaration. In the XML 1.0 recommendation,
an XML document does not require the XML declaration. However in the XML 1.1

l &
specifications, the XML declaration is mandatory.

a
Note: Not all tools and XML Parsers support XML 1.1 syntax.
n
te r
The only attribute that is required in the declaration is the version. Additional attributes
that can be added to the XML declaration include:

I n
• The encoding attribute, which is optional. By default, XML documents are encoded
in UTF-8 format of the Unicode character set. The slide example uses an encoding of

l e
WINDOWS-1252. This is useful for applications (such as those written in Java) that
c
can handle other encoding formats.

r a
• The standalone attribute is optional and may be set to the yes or no value. If

O omitted, the value is assumed to be no. Set the standalone value:


- To no, if an application requires an external DTD to determine proper document
structure
- To yes, when the document does not have DTD, does not change the document
content, or if the DTD is internal.
Oracle 10g: XML Fundamentals 1-6
Components of an XML Document

XML documents comprise storage units containing:


• Parsed data, including the:
– Markup (elements, attributes, entities) used to
describe the data they contain
– Character data described by markup
<?xml version="1.0" encoding="WINDOWS-1252"?>
<employees>
<employee id="100">
<name>Rachael O&apos;Leary</name>
</employee>
</employees>
• Unparsed data, textual or binary information
(graphic and sound data) taken as entered
<![CDATA[ ...unparsed data... ]]>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Components of an XML Document
U s
is textual information comprising:
A I
An XML document comprises storage units containing parsed or unparsed data. Parsed data

O
• Markup that describes the data it contains. Markup includes:

l &
- Elements to describe the data it contains, such as the root element (employees)
and its child elements (employee, name)

a
- Attributes, which are name and value pairs (id="100") included in the start tag
n
of an element

te r
- The entities (&apos;) representing any character data substituted in place of

I n
their appearance
• Character data described by the markup components. For example:

l e
- The value 100 assigned to the id attribute
c
- The data Rachael O'Leary described by the <name> element

r a
- The &apos; entity, which represents the apostrophe (') character

O
Note: The element tree in an XML document defines its layout and logical structure.
Unparsed data, embedded in CDATA sections can be used in an XML document to contain
textual data or encoded binary data, such as graphic and sound files. A CDATA section starts
with <![CDATA[ and ends with ]]> characters. The information contained inside the
CDATA section is not parsed by an XML Parser, and is taken as entered.
Oracle 10g: XML Fundamentals 1-7
XML Elements

• An XML element:
– Has a start tag, end tag, and optional data content
– Tag names are case-sensitive (must be identical)
Tag name
<employee> Start tag
Data
Element <name>Steven King</name>
content
</employee> End tag
Tag name
• Empty elements:
– Do not contain any data <initials></initials>

– May appear as a single tag <initials/>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Elements
U s
An XML element has:
• A start tag, for example, <employee> includes:
A I
- The ‘<’ character
O
- The ‘>’ character.
l &
- A case-sensitive tag name (employee), without leading spaces.

a
• An end tag, for example </employee> is:
n
- The ‘<’ character

te r
- The case-sensitive tag name that must be identical to the start tag name, but

I n
prefixed with a forward slash. Leading spaces are not permitted.
- The ‘>’ character

l e
• Data content that can also contain elements, such as <name> in the slide example.
c
a
In summary, an XML element includes the start tag, end tag, and everything in between.
r
O
Empty elements have no content between the start and end tags. In this case, a shortened
form can be used where the start tag name is followed by a forward slash. For example:
<initials/>.
Tag names are a descriptive term for an XML element and its content–for example,
employee. The tag name is known as the element type name.
Oracle 10g: XML Fundamentals 1-8
Markup Rules for Elements

• There is one root element, sometimes called the


top-level or document element.
• All elements:
– Must have matching start and end tags, or be a self-
closing tag (an empty element)
– Can contain nested elements, such that their tags
do not overlap
– Have case-sensitive tag names subject to naming
conventions: Start with a letter, no spaces, and do
not start with the letters xml
– May contain white space (spaces, tabs, new lines,
and combinations of them) that is considered part
of the element data content

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Markup Rules for Elements
U s
A I
Every XML document must contain one root element (top-level or document element).
XML documents are hierarchical in structure with elements nested within others forming a

O
document tree. The start and end tags for elements must not overlap. For example:
<employee>

</employee>
l &
<first_name>Steven<last_name>king</first_name></last_name>

n a
Here, the <last_name> element overlaps the <first_name> element. This is not

<employee>
te r
permissible. The correct form is:

</employee>
I n
<first_name>Steven</first_name><last_name>king</last_name>

l e
Element start and end tag names must be identical, that is, they are case-sensitive. For
c
example: <Employee>, <employee>, <EMPLOYEE> are all different tag names.

r a
Element tag names must start with a letter or an underscore (_), but not numeric or

O
punctuation characters. After the first letter, numeric, dash (-), and period (.) characters are
allowed, but not white space. Tag names cannot start with the xml letter sequence, or any
case-sensitive combination thereof, such as, XML and Xml. White space, including new
lines, are considered part of the data, that is, no stripping of white space is done. However,
XML Parsers treat end-of-line characters as a single line-feed.
Oracle 10g: XML Fundamentals 1-9
XML Attributes

An XML attribute is a name-value pair that:


• Is specified in the start tag, after the tag name
<?xml version="1.0" encoding="WINDOWS-1252"?>
<employees>
<employee id="100" name='Rachael O&apos;Leary'>
<salary>1000</salary>
</employee>
</employees>

• Has a case-sensitive name


• Has a case-sensitive value that must be enclosed
in matching single or double quotes
• Provides additional information about the XML
document or XML elements
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Attributes
U s
attributes must be specified after one of the following:
A I
Attributes are simple name-value pairs that are associated with a particular element. XML

• The start tag of an element


• The tag name of an empty element O
Example: <employee id="100" email="SKING"/>
l &
a
Attribute names are case-sensitive and follow the naming rules that apply to element names.
n
te r
In general, spaces are not used, but are allowed, on either side of the equal sign.
The attribute values must always be in matching quotes, either single or double quotes. The

I n
slide example shows the employee id attribute value enclosed in double quotes, and the
name attribute value enclosed in single quotes. In the latter case, the &apos; entity must

l e
be used to include the apostrophe (single quote) character in the name value.
c
r a
Attributes provide additional information about the XML document’s content or other XML
elements. Attributes can be used for the following purposes:
O
• Describing how the XML document data is encoded or represented
• Indicating where the links or external resources are located
• Identifying and calling external processes, such as applets and servlets
• Specifying an element instance in the document for facilitating a rapid search
Note: Attributes always have a value–for example, name="" has an empty string value.
Oracle 10g: XML Fundamentals 1-10
Using Elements Versus Attributes

<?xml version="1.0"?>
<employees> 1 Elements
<employee>
<id>100</id>
<last_name>King</last_name>
<salary>24000</salary>
</employee>
</employees>

<?xml version="1.0"?>
<employees> 2 Attributes
<employee id="100" last_name="King"
salary="24000">
<job>President</job>
</employee>
</employees>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using Elements Versus Attributes
U s
In the slide, you see two examples:

A I
1. In Example 1, id, last_name, and salary are defined as elements within the

O
employee element, whose parent is the employees element.
2. In Example 2, id, last_name, and salary are attributes of the employee

l &
element, whose root element is employees.

a
Elements and attributes accomplish approximately the same thing, that is, they describe the
n
about an employee.
te r
data. The examples shown are both valid and communicate the same basic information

I n
Note: In general, it is more robust and flexible to use elements rather than attributes.

c l e
The choice to use elements or attributes is often a matter of preference, but takes some time
and experience to determine the best style to use for different contexts. The easiest and the

r a
most consistent approach is to use elements for data that the user of the document wants to
see, and attributes for metadata representing additional information about the data that the
O
the document may require. The following are additional points to consider:
• Elements are more easily added as your requirements expand.
• Elements may be ordered, but attributes are returned unordered from the document.
• Elements can be structured and may contain other elements.
• Attributes are atomic, that is, they cannot be nested or have attributes of their own.
Oracle 10g: XML Fundamentals 1-11
XML Entities

An XML entity:
• Is a unit of data storage
• Is identified by a case-sensitive name
• Is used as replacement text (substituted) when
referencing its name between an ampersand (&),
and a semicolon (;)
<comment>Salaries must not be &lt; 1000</comment>
• Has predefined names for special XML characters:
– &lt; for less than (<), and &gt; for greater than (>)
– &amp; for ampersand (&)
– &quot; for double quote (")
– &apos; for single quote (')
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Entities
U s
An XML Entity is a unit of data storage that:
• Is identified by a case-sensitive name
A I
O
• Represents replacement text to eliminate a lot of typing in XML documents

l &
• Is referenced by its name prefixed with an ampersand (&) and terminated by a
semicolon (;). The ampersand is referred to as an escape character.

n a
The XML standard predefines entity names for the following special characters:

te r
• The less than sign (<) represented by the name &lt;
• The greater than sign (>) represented by &gt;

I n
• The ampersand (&) represented by &amp;

c l e
• The double quotation mark (") represented by &quot;
• The single quote or apostrophe (') represented by &apos;

r a
In the following example, the XML Parser expects a tag name after the less than (<) sign:

O
<number>150<100</number>
This invalid syntax is corrected by using the &lt; built-in entity to represent the less than
character. Example:
<number>150&lt;100</number>
Note: User-defined entity names can be declared in a document type definition (DTD).
Oracle 10g: XML Fundamentals 1-12
XML Comments

XML comments:
• Start with <!--
• End with -->
• May appear anywhere in the character data of a
document, and before the root element
• Are not elements, and can occupy multiple lines
• May not appear inside a tag or another comment
<?xml version="1.0" encoding="WINDOWS-1252"?>
<!–- Comment: This document has information about
employees in the company -->
<employees>
<name>Steven King</name> <!-- Full name -->
</employees>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Comments
U s
can appear anywhere in the XML document, except inside:
A I
Comments are a way to document what is done inside an XML document. XML comments

O
• The start or end tag of an element. Thus, they are not permissible in attribute values.

l &
• Another comment. Comments cannot be nested.
Because comments are not considered to be an XML element, its appearance does not

n a
violate the tree structure or one-root element requirement for well-formed XML documents.

• Before the root element


te r
The slide example shows a comment:

I n
• After the end tag of the </name> element

l e
Note: In general, a comment must not appear before the XML declaration. However, some

c
XML Parsers, as in Internet Explorer, do not mark it as an error.

r a
Applications must not depend on comments as they are not intended for processing

O
purposes, but merely for making the XML document more meaningful to people reading its
contents.

Oracle 10g: XML Fundamentals 1-13


A Well-Formed XML Document

Every XML document must be well-formed, such that:


• An XML document must have one root element
• An element must have matching start and end tag
names, unless they are empty elements
• Elements can be nested, but cannot overlap
• All attribute values must be quoted
• Attribute names must be unique in the start tag of
an element
• Comments and processing instructions do not
appear inside tags
• The < or & special characters cannot appear in the
character data of an element or attribute value
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
A Well-Formed XML Document
U s
A I
All XML documents must be well-formed to guarantee that it is correctly structured and
adheres to the rules defined in the slide. The slide contains a list of the most common rules

O
to be addressed for well-formed documents; but it is not a complete list.

l &
Note: The less than (<) and ampersand (&) characters are special in XML and cannot appear
as themselves within the character data part of an element, or the value of an attribute. In

n a
character data and attribute values, an XML Parser recognizes:

te r
• The less than (<) sign as a character that introduces the start tag of another element
• The ampersand (&) as an escape character before an entity name terminated by a
semicolon (;)
I n
l e
Therefore, to include special characters in the character data of an element, or attribute

c
value, you must use built-in XML entity names for the special characters. For example, use

r a
&lt; to include the less than character, and &amp; for the ampersand character. The XML

O
Parser replaces the entity reference with its textual or binary representation, as discussed
earlier in this lesson.
Note: The XML 1.1 specification requires the XML declaration to appear at the beginning
of the document. However, the declaration is optional when using XML 1.0.

Oracle 10g: XML Fundamentals 1-14


Class Activity

Identify errors in the following examples:


<?xml version="1.0"?>
<Question>Is this legal?</Question> 1
<Answer>No</Answer>

<!-- An XML document -->


<?xml version="1.0"?> 2

<Question 4You="Is this attribute name correct"/> 3

<EMAIL ID=Mark.Ant@oracle.com></EMAIL> 4

<Question>Is this legal</question> 5

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Class Activity
U s
document element per document.
A I
1. Both <Question> and <Answer> are top-level elements. You can have only one

O
2. In general, you cannot have a comment before the XML declaration, and the root
element is required.

l &
Note: Internet Explorer allows a comment before the XML declaration.

a
3. The attribute name cannot start with a digit.
n
te r
4. The attribute value is not enclosed in quotes.
5. Opening and closing tag names are case-sensitive and must match.

I n
c l e
r a
O
Oracle 10g: XML Fundamentals 1-15
Comparing XML and HTML

• XML
– Is a markup language for describing data
– Contains user-defined markup elements
– Is extensible
– Is displayed as a document tree in a Web browser
– Conforms to rules for a well-formed document
• HTML
– Is a markup language for formatting data in a Web
browser
– Contains predefined markup tags
– Is not extensible
– Does not conform to well-formed document rules

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Comparing XML and HTML
U s
The key difference between XML and HTML is that:
• XML is a markup language for describing data
A I
• HTML is a markup language for formatting data
O
&
The slide covers other important differences between XML and HTML.
l
A Word About XHMTL

n a
te r
The World Wide Web Consortium (W3C) has worked on defining the Extensible HyperText
Markup Language (XHTML) as a successor to HTML.

I n
XHTML is designed to conform with XML standards and well-formed document rules, and
provide a way to reproduce, subset, and extend HTML documents. An XHTML document is
l e
a particular XML document instance intended for processing by a Web browser.
c
r a
Note: Not all browsers support XHTML document, and different browsers often process
XHTML documents in different ways.
O
Oracle 10g: XML Fundamentals 1-16
XML Development

Developing XML documents can be done using:


• A simple text editor, such as Notepad
• A specialized XML editor, such as XMLSpy
• Oracle JDeveloper 10g XML-related features that
include:
– Syntax checking for XML documents
– XML Editor with code insight for XML schema-
driven editing
– Registering of external XML schemas
– Validation of XML documents against registered
XML schemas

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Development and Oracle JDeveloper 10g
U s
A I
There are many ways to develop XML documents from using a simple text editor, such as
Notepad, to rich XML development tools, such as XMLSpy or Oracle JDeveloper 10g.
Oracle JDeveloper 10g includes:
O
l &
• An XML Editor, which is a specialized XML schema-driven editor for editing XML
documents subject to XML language standards
a
• A code insight feature enables JDeveloper to provide you with a choice of elements or
n
te r
attributes that are relevant to the context of the editing location within the document
• The capability to register external XML schemas for use by the schema-driven editor

I n
• The use of registered XML schemas to validate XML documents
• A simple XML syntax check to test whether the document is well-formed

l e
Review of How to Create an XML Document in JDeveloper
c
• Select File > New.

r a
• In the New Gallery window

O - Expand the General category and then select XML node


- Double-click XML Document in the item list
The XML document opens up in the XML Editor. To start using the XML Editor, simply
begin typing the markup and data content in the editor.

Oracle 10g: XML Fundamentals 1-17


Editing XML in Oracle JDeveloper 10g

3
1

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Editing XML in Oracle JDeveloper 10g
U s
A I
The slide shows that when you right-click an XML document in JDeveloper’s Navigator:
1. The Open option causes the elements and data to be displayed hierarchically in the
Structure window. In the Structure window:
O
l &
- Click an element, attribute, or error to navigate to it in the XML Editor.
- Double-click an element, attribute, or error to edit it in the XML Editor.
a
2. The Open option also causes the file’s contents to be displayed in the XML
n
te r
(source/code) Editor window.
3. The Check XML Syntax option checks if the document is well-formed, and displays

I n
XML syntax errors in the Messages tab of the log window.

c l e
Select Tools > Preferences and select XML under the Code Editor node:
• Select the End Tag Completion check box to enable the end tag to be automatically

r a
inserted after completing the start tag.
• Select the Required Attribute Insertion check box for the editor to automatically
O
insert required attributes, when entering a space after the start tag name.
Note: The syntax is highlighted in the editor. JDeveloper automatically inserts the XML
declaration as the first line. Click File > Save to save your changes to the document. Select
View > Structure to display the Structure window, if it is not already open.
Oracle 10g: XML Fundamentals 1-18
Summary

In this lesson, you should have learned how to:


• Describe XML
• Form the structure of an XML document, and add
an XML declaration
• Create an XML document containing elements and
attributes in an XML document
• Use predefined entities for special characters
• Write a well-formed XML document
• Use JDeveloper to edit an XML document

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
XML, which stands for Extensible Markup Language, defines a universal standard for
electronic data exchange. It provides a rigorous set of rules enabling the structure inherent in

O
the data to be easily encoded and unambiguously interpreted using human-readable text

l &
documents. Unlike HTML, the tags are extensible. In XML, you create your own tags as
required, whereas HTML has a set of predefined formatting tags that you can use but you
cannot create your own.
n a
te r
When creating an XML document that is well-formed, you:
• Provide a single root element

I n
• Ensure that start and end tag names are matching

c l e
• Ensure that attributes appear in the start tag of an element
• Ensure that attribute names are unique within the start tag

r a
• Use predefined entity names to replace their references with their textual definition
when used in the data content of XML documents
O
JDeveloper provides tools and features that enable rapid development and syntax checking
of XML documents.

Oracle 10g: XML Fundamentals 1-19


Practice 1: Overview

This practice covers the following topics:


• Writing an XML document by using the features of
XML Editor in Oracle JDeveloper
• Checking whether an XML document is well-
formed
• Testing an XML document with errors that violate
the rules of a well-formed document
• Optionally, answering questions about XML
documents

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Practice 1: Overview
U s
A I
In this practice, you test your understanding of writing an XML document by:
• Opening an existing XML document and cloning some of the elements provided in the
document as a template
O
l &
• Checking the syntax of the document to ensure that it is well-formed
After creating various errors in an XML document, you check and explain the results. There

n a
are optional questions that can be answered about XML documents.

te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 1-20
Practice 1
The goal of this practice is to create a well-formed XML document containing employee
information. You use SQL*Plus to execute a query to obtain the content for your document.
After the document is created, you are instructed to force some errors and explain how the
changes violate the rules of a well-formed document. Optionally, you may answer paper-
based questions to facilitate the understanding of an XML document.
1. Generate XML data from the database for an XML document.
a. Start SQL*Plus by double-clicking the SQL*Plus icon.
b. Log in to the database by using your username (orax), password (oracle), and
the database host/connect string. The instructor must provide you with a number
x and the database connect string for the course.
c. Execute the SQL script called E:\labs\lab\lab_01_01.sql to generate a
list of data for employees in department 60. The script saves the data in a file
called E:\labs\lab\lab_01_01.txt.
2. Modify the employees.xml document in the XMLLabsProject to contain
elements for the employees in department 60.
a. Convert the text Company Employee Data in the <employees> element
into an XML comment.
b. For each employee row in the lab_01_01.txt file, add an employee element
by using the following structure:
<employee>
<employee_id><!-- id --></employee_id>
<first_name><!-- first name --></first_name>
<last_name><!-- last name --></last_name>
n l y
<salary><!-- salary --></salary>
</employee>
e O
There must be five employees.
U s
Hint: You can use the file E:\labs\lab\lab_01_02.xml as a template.

A I
c. Save the changes to your document, and check the employees.xml document
to see whether it is well-formed. Correct the errors and save the changes.

O
d. Display the employees.xml file in your browser.
3. Add an XML document containing department data to the XMLLabsProject and

l &
correct the errors violating the rules of a well-formed document.

a
Note: After checking and before correcting the syntax errors in JDeveloper, you can
n
errors.
te r
optionally view the XML document in the browser to observe how it reports the syntax

I n
a. Add the file E:\labs\lab\departments.xml to your project.
b. Check the XML document syntax, and correct the error reported. Repeat this step

l e
until all the syntax errors are removed.
c
Hint: There are three syntax errors in the document, which are indicated as

r a
warnings in the Structure pane.

O c. Add an attribute called num, which is assigned a value of 1, to the start tag of the
first <department> element. Do not use quotes around the attribute value.
d. Check the XML document syntax, and explain and fix the syntax error. Check
the document syntax to confirm your correction, and save changes to the
document.
Oracle 10g: XML Fundamentals 1-21
Practice 1 (continued)
If you have time:
4. Answer each of the following questions about XML documents:
a. XML is a markup language for formatting and displaying text and images.
True/False

b. XML affords the simple exchange of data between applications.


True/False

c. Element tags within an XML document permit other applications to parse the
document for specific information.
True/False

d. The following syntax represents a well-formed XML document:


<?XML version="1.0"?>
<customer>
<name>Mary Lewis>
<state>VA</state>
</customer>
True/False

e. A root element is ____.


Required to be the first line of an XML document
Container of all other elements
n l y
Not required

e O
f. Elements that contain data must have ____.
Start and end tags
U s
A declaration statement
Attributes A I
O
&
g. Elements are ___________ as requirements expand.
l
Not easily added
n a
Used for metadata and are helpful

Easily added
te r
I n
h. Although not strictly required, including __________ is a good and common

l e
practice.

c
An XML declaration

r a A root element

O Start and end tags

Oracle 10g: XML Fundamentals 1-22


Validating XML with Document Type
Definitions (DTDs)

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe a DTD
• Compare an internal DTD with an external DTD
• Read and write a DTD
• Validate XML documents by using an internal DTD,
an external DTD, or their combination

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
XML documents.
A I
This lesson focuses on the use of document type definitions (DTDs) to control the validity of

References
O
http://www.xml.org/xml/news_market.shtml
l &
a
http://www.jaworski.com/htmlbook/dec-hex.htm (hexadecimal)
n
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 2-2
What Is a Document Type Definition?

A document type definition (DTD):


• Is the grammar for an XML document
• Contains the definitions of
– Elements
– Attributes
– Entities
– Notations
• Contains specific instructions that the XML Parser
interprets to check the document validity
• May be stored in a separate file (external)
• May be included within the document (internal)

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
What Is a Document Type Definition (DTD)?
U s
A I
A DTD provides a list of elements contained in an XML document that collectively
specifies the structure of the document. A DTD defines the set of markup items used in an
XML document, that is, the:
O
• Elements
• Attributes, and their permissible values
l &
• Entities (user-defined)
n a
• Notations

te r
Note: Notations are not frequently used. However, their creation and basic examples are

I n
shown in the subsequent pages of this lesson.

l e
The XML engine interprets the markup defined in DTD to check the document for validity.

c
For example, a DTD may specify that a department must have exactly one department

r a
identification number and one name, but may have multiple employee elements. An XML

O
document indicates to an XML Parser whether it is associated with a DTD and where to
locate the DTD.
A DTD may be found internally (inline) in the document, or externally identified by a
Uniform Resource Locator (URL), which can be a file on disk. If the XML Parser does not
encounter errors, then the XML document is guaranteed to be consistent with the definition.
Oracle 10g: XML Fundamentals 2-3
Why Validate an XML Document?

• Well-formed documents satisfy XML syntax rules,


and not the business requirements about the
content and structure.
• Business rules often require validation of the
content and structure of a document.
• XML documents must satisfy structural
requirements imposed by the business model.
• A valid XML document can be reliably processed
by XML applications.
• Validations can be done by using a DTD or using
an XML schema.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Why Validate an XML Document?
U s
A I
A well-formed XML document is one that meets all the rules of the XML specification.
What if just following the syntax rules is not quite good enough? Your business may require

O
the validation of the actual structure and content of a document. Your document must not

business model. For example:


l &
only follow the XML rules, but also satisfy structural requirements imposed by your

a
Each <employee> element must consist of <employee_id>, <first_name>,
n
te r
<last_name>, <email>, <phone_number>, and <department_id>
elements. If an <employee> element misses any of these elements, it is considered

I n
to be not valid. You may also need to verify whether these elements have a valid value.

c l e
You can perform all these validations by using a document type definition (DTD). DTD was
the first type of mechanism available for validating XML document structure and content. It

r a
lacked the capability of performing data type validations on the content. The XML Schema
recommendation supports validation for different data types, and is rapidly replacing DTD
O
as a way to validate the XML document structure and content.
Note: Theoretically, anything that has not been explicitly permitted in DTD is forbidden.
Some parsers do not always enforce the rules defined by a DTD. Using an XML Schema for
validation is covered in the lesson titled “Validating XML by Using XML Schema.”
Oracle 10g: XML Fundamentals 2-4
General DTD Rules

A DTD:
• Must provide a declaration for items used in an
XML document, such as:
– Elements
– Attributes
– Entities
• Is case sensitive, but spacing and indentation are
not significant
• May use XML comment syntax for documentation,
but comments cannot appear inside declarations
• Forbids using anything that is not explicitly
permitted
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
General DTD Rules
U s
A I
The general syntax of a DTD is different from that of an XML document. To validate an
XML document by using a DTD, the rules in the slide must be followed.

O
The DTD declarations form the definition of elements, attributes, and entities that are used

constructed to be considered as valid.


l &
in an XML document. The definitions describe rules of how the XML document can be

n a
The element, attribute, and entity names are all case sensitive and must match their use in

te r
the XML document. Comments in the XML syntax are allowed, but cannot appear inside
any declarations.
I n
Note: Everything that is not explicitly permitted is forbidden. This means that when an

l e
XML document is validated using a DTD, anything that is not declared or permitted by the
c
DTD is considered to be forbidden, that is, the document is considered to be invalid.

r a
O
Oracle 10g: XML Fundamentals 2-5
The Contents of a DTD

A DTD contains declarations (using the syntax shown)


for:
• Elements:
<!ELEMENT element-name content-model>

• Attributes:
<!ATTLIST element-name attrib-name type default>
• Entities:
<!ENTITY entity-name "replacement text">

• Notations:
<!NOTATION notation_name SYSTEM "text">

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The Contents of a DTD
U s
shows the generic syntax for declaring markup components:
A I
A DTD consists of declarations for markup and data used in an XML document. The slide

O
• Elements, which declare tag names and their content model. The content model for an

l &
element includes other nested markup (elements) and/or character data.
• Attributes, which declare the attribute names for the containing element, the type of
a
attribute (not a data type), and optional default values
n
te r
• Entities, which provide a notation for replacement text
• Notations, used in DTD attribute types to provide a way for identifying how parsed or

I n
unparsed data is encoded, typically used by applications that can process the data

c l e
Note: Notations are not frequently used in DTDs.
The next few pages of this lesson show examples of how to use each of these declarations,

r a
and finally how to use DTD to validate the structure and content of an XML document.

O
Oracle 10g: XML Fundamentals 2-6
Example of a Simple DTD Declaration

Example of a simple DTD with element declarations:


<!ELEMENT employees (employee)>
<!ELEMENT employee (name)>
<!ELEMENT name (#PCDATA)>

A valid XML document based on the DTD is:


<?xml version="1.0"?>
<employees>
<employee>
<name>Steven King</name>
</employee>
</employees>

Note: All child elements must be defined.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example of a Simple DTD Declaration
U s
A I
The DTD in the slide declares three elements: employees, employee, and name. These
elements form a simple hierarchy, where the <employees> element must contain one

O
<employee> element that must contain one <name> element (as shown in the slide).
Note
l &
• The #PCDATA example represents text-only content without child elements.

n a
• The XML document does not reference the DTD in the slide example.

te r
Element names used in the content model represent a single instance of that element. Using
the DTD in the slide, the following XML document will be invalid, because there are two
I n
<employee> child elements:

l e
<?xml version="1.0"?>

c
<employees>

r a <employee><name>Steven King</name></employee>
<employee><name>Ellen Abel</name></employee>
O </employees>
Note: The DTD syntax for declaring an element provides a way to specify a cardinality (a
number of occurrences) for usage of elements in the content model. Specifying a cardinality
is covered after discussing how to declare elements in this lesson.
Oracle 10g: XML Fundamentals 2-7
Referencing the DTD

The XML document references the DTD:


• After the XML declaration and before the root by
using:
<!DOCTYPE employees [ ... ]>
• Externally with the SYSTEM or PUBLIC keywords:
<!DOCTYPE employees SYSTEM "employees.dtd">
<!DOCTYPE employees PUBLIC "-//formal-public-ID">
• Internally in the <!DOCTYPE root [...]> entry:
<?xml version="1.0"?>
<!DOCTYPE employees [
<!ELEMENT employees (#PCDATA)>
]>
<employees>Employee Data</employees>
Note: Use the root element name after <!DOCTYPE.
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Referencing the DTD
U s
<!DOCTYPE root-element-name [declarations]>
A I
The XML document references the DTD to be validated using a specification syntax of:

O
The root element name must be used after the <!DOCTYPE keyword in the declaration. To

l &
use an external DTD, replace the [declarations] part with:
• The SYSTEM keyword and a quoted string containing a URL or a relative path to a file
a
with a .dtd extension, such as employees.dtd in the slide, or a URL such as
n
te r
http://www.myserver.com/dtd/employees.dtd.
• The PUBLIC keyword and a quoted string containing a Formal Public Identifier (FPI).

I n
For example, to reference the public XHTML identifier, use:

e
<!DOCTYPE xhtml PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">

c l
The last slide example in the slide uses an internal DTD with declarations placed between:

r a
• The <!DOCTYPE root-element [ characters
• The closing ]> characters.
O
Note: The <!DOCTYPE name [...]> specification appears after the XML declaration
and before the root element of the XML document. Public identifiers are seldom used. An
XML document can reference both an external DTD and an internal DTD. The internal DTD
takes precedence if an element is defined both externally and internally.
Oracle 10g: XML Fundamentals 2-8
Element Declarations

• Element declaration syntax:


<!ELEMENT element-name content-model>
• Four kinds of content models:
<!ELEMENT job EMPTY> <!-- Empty --> 1

<!–- Elements: single, ordered list, or choice -->


<!ELEMENT employees (employee)> 2
<!ELEMENT employee (employee_id,last_name,job_id)>
<!ELEMENT job_id (manager | worker)>

<!-- Mixed -->


3
<!ELEMENT last_name (#PCDATA)>
<!ELEMENT hire_date (date| (day,month,year))>

<!ELEMENT employee_id ANY> <!–- Any -->

n l4
y
Copyright © 2004, Oracle. All rights reserved.

e O
Element Declarations
U s
A I
Elements are the basic building blocks of DTDs. An element declaration contains the
ELEMENT keyword, followed by the element name, and a content model. The content

O
model defines what can be contained in the element. The four kinds of content models are:
1. Empty: This cannot contain subelements or text. However, an empty element may

l &
hold attributes. Examples of empty element are:

n a
<job/> <job></job> <job id="ST_CLERK"/>
2. Child elements: These are subelements enclosed in brackets, which can be:

te
- A single element name r
- A sequence of element names containing a comma-separated list of names

I n
whose order of appearance is significant For example:

c l e
The <employee> element must contain an <employee_id> element that
appears before the <last_name>, which must appear before the <job_id>.

r a
- A choice of element names, which is a list of names separated by a vertical bar
(|), each representing an alternative choice. For example:
O The <job_id> element may contain either a <manager> element or a
<worker> element, but not both.
- A combination of single element and a list. For example:
<!ELEMENT person (full_name | (first_name, last_name))>

Oracle 10g: XML Fundamentals 2-9


Element Declarations (continued)
3. Mixed: The simplest form of mixed content is a text-only element, known as parsed
character data, using the #PCDATA keyword enclosed in parentheses. When content
is specified as #PCDATA, the element can contain a text string, but not subelements.
For example, using the last_name element declaration, the following XML is valid:

<last_name>Vennapusa</last_name>

Another example of mixed content is shown in the hire_date element declaration,


which can contain either parsed character data or a combination of date, month, and
year elements. The following XML elements will be valid for hire_date:

<hire_date><date>May 20, 1996<date></hire_date>


or
<hire_date>
<day>20</day
<month>May</month>
<year>1996</year>
</hire_date>

4. Any: This content model means that anything can be contained within the element and
is very loose. The ANY content model allows any element declared in the DTD to be

the element content.


n y
used, in any order, using any number of occurrences. That is, the DTD doe not validate
l
Note: You must avoid using ANY because it entirely defeats the purpose of using a
DTD for validating the structure and content of an XML document.
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 2-10
Specifying Cardinality of Elements

Cardinality symbols:
• Indicate the number of children permitted
• Appear as suffixes:
No symbol (default) Mandatory (one and only one)
? (question mark) Optional (zero or one)
* (asterisk) Zero or more (optional)
+ (plus sign) One or more (mandatory)
• Are placed after:
– An element or group in the content model
– The content model
Note: A group is formed using parentheses.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Specifying Cardinality of Elements
U s
A I
The content model indicates how to group subelements by using parentheses, and how many
occurrences of each element is permitted, known as the cardinality. Cardinality is expressed
using the following symbols:
O
• Question mark (?): Indicates an optional or single-valued subelement (zero to one)

l &
• Asterisk (*): Indicates an optional or multivalued subelement (zero to many)
• Plus sign (+): Indicates a mandatory or many-valued subelement (one to many)
a
The symbols can appear, in the content model specification, as a suffix with the individual
n
te r
elements, a group, and the entire content model. By default, the absence of a symbol means
that the element, group, or content model must appear at least once, that is, it is mandatory.
Examples of using symbols are:
I n
1. An <employees> element can contain zero or many <employee> elements:

e
<!ELEMENT employees (employee*)>
l
2. A <department> element must contain at least one or many <employee>
elements:
c
r a <!ELEMENT department (employee+)>

O
3. An <employee> element must have one <last_name> and <salary> element,
and an optional <commission_pct> element:
<!ELEMENT employee (last_name,salary,commission_pct?)>
4. The <jobs> element must have one president, and optionally many managers or
clerks:
<!ELEMENT jobs (president , (manager | clerk)*)>
Oracle 10g: XML Fundamentals 2-11
Attribute Declarations

• The syntax for declaring an attribute is:


<!ATTLIST element-name attrib-name type default>
• Attribute declaration requires:
– An element name
– An attribute name
– An attribute type, specified as:
CDATA, enumerated, ENTITY, ENTITIES, ID, IDREF,
IDREFS, NMTOKEN, NMTOKENS, and NOTATION
– An attribute default, specified as:
#IMPLIED, #REQUIRED, #FIXED, or a literal value
• Example:
<!ELEMENT employee (employee_id, last_name)>
<!ATTLIST employee manager_id CDATA #IMPLIED>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using Attributes
U s
A I
Attributes specify additional information about an element, and form a name-value pair
describing a particular property of the element. Declaring an attribute requires:

O
• An element name identifying the element to which the attribute belongs

l &
• An attribute name specifying the name of the attribute
• An attribute type set to one of the ten possible types of attributes listed in the slide.
a
These are discussed on the next page.
n
te r
• An attribute default specifies a mandatory, or optional, value using:
- #REQUIRED indicating that the attribute must be specified (mandatory)

I n
- #IMPLIED indicating that the attribute is optional
- #FIXED indicating that the attribute is a constant, that is, a supplied single value
l e
- A literal value enclosed in quotes that is used as a default value, when no value is
c
r a
specified in the XML document
An example of XML by using the manager_id attribute declaration is:
O <employee manager_id="100">
<employee_id>101</employee_id>
<last_name>Kochhar</last_name>
</employee>

Oracle 10g: XML Fundamentals 2-12


CDATA and Enumerated Attribute Types

• CDATA: For character data values


<!ELEMENT employee (employee_id, last_name)>
<!ATTLIST employee manager_id CDATA #IMPLIED>

<employee manager_id="102"> <!-- XML -->


<employee_id>104</employee_id>
<last_name>Ernst</last_name>
</employee>
• Enumerated: For a choice from a list of values
<!ELEMENT employee (employee_id, last_name)>
<!ATTLIST employee gender (male|female) #IMPLIED>
<employee gender="male"> <!-- XML -->
<employee_id>104</employee_id>
<last_name>Ernst</last_name>
</employee>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
CDATA and Enumerated Attribute Types
U s
The CDATA Attribute Type

A I
The CDATA type indicates that the attribute value can be set to any character data. Most
O
attributes use the CDATA type. The example in the slide declares manager_id as an

l &
attribute of the employee element. The manager_id attribute may have any character
data as its value. The sample XML code, in the slide, under the manager_id attribute

n a
declaration shows an example of using the attribute.

te
The Enumerated Attribute Type r
I n
The Enumerated type provides a choice from a list of allowable values for the attribute. The
choices of values in the list:

l e
• Are enclosed in brackets
c
• Are separated by the vertical bar (|) character (spaces are optional)

r a
• Can be case-sensitive strings (without quotes) or numeric values

O
For example, the employee element is given a gender attribute with male or female
as its possible values. In the slide, the XML code under the gender attribute declaration
shows an example of using the attribute.

Oracle 10g: XML Fundamentals 2-13


NOTATION Declaration and Attribute Type

• Declaring a NOTATION:
<!NOTATION notation_name SYSTEM "text">
• The NOTATION attribute type represents a name of
a NOTATION declared in the DTD:
<?xml version="1.0"?>
<!DOCTYPE photos [
<!ELEMENT photos (image+)>
<!ELEMENT image EMPTY>
<!NOTATION gif SYSTEM "image/gif">
<!NOTATION jpeg SYSTEM "image/jpeg">
<!ATTLIST image
source CDATA #REQUIRED
type NOTATION (gif | jpeg) #REQUIRED>
]>
<photos>
<image source="myphoto.gif" type="gif"/>
<image source="mypet.jpg" type="jpeg"/>
</photos>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
NOTATION Attribute Type and NOTATION Declarations
U s
This defines a name for a notation that can be used as:
A I
The syntax for the NOTATION declaration is shown in the first code example in the slide.

• An attribute value for a NOTATION attribute type


O
(covered in subsequent pages)
l &
• A name after an NDATA keyword in an unparsed external ENTITY declaration

n a
The second code example in the slide shows an XML document using an internal DTD that
declares:

te r
• The <photos> element as containing one or more <image> elements

I n
• That each <image> element can have two attributes:

c l e
- A source containing a character data such as a file name
- A type, declared as a NOTATION attribute type, whose value must be a choice

r a
of the notation names, such as gif and jpeg, as listed in the content model
• A notation name for gif and jpeg in their NOTATION declarations
O
Note: The DTD example also illustrates how to declare more than one attribute for an
element, for example, the source and type attributes for the image element. Also,
NOTATION declarations are not commonly used.

Oracle 10g: XML Fundamentals 2-14


Specifying Default Attribute Values

• A quoted default attribute value:


– Can be specified in the DTD after the attribute type:
<!ELEMENT employee (employee_id, last_name)>
<!ATTLIST employee department_id (10|60|90) '90'>

– Is not specified when using the #IMPLIED or


#REQUIRED keywords
– Is required in the DTD if using the #FIXED keyword
<!ELEMENT employee (employee_id, last_name)>
<!ATTLIST employee manager_id CDATA #IMPLIED>
<!ATTLIST employee min_salary CDATA #FIXED '4000'>

• An attribute value is mandatory in the XML


document when using the #REQUIRED keyword.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Specifying Default Attribute Values
U s
attribute type enclosed in quotes.
A I
The attribute declaration in a DTD enables you to specify default attribute values after the

O
The first DTD example in the slide specifies a default value of 90 for the department_id

employee element, the default is assumed.


l &
attribute. If the XML document does not specify a department_id attribute for an

n
The second DTD example demonstrates: a
te r
• The manager_id attribute declared as an #IMPLIED value. The attribute
declaration in the DTD does not require a default value, and the XML document may
I n
or may not supply a value. A default is not applied if the attribute is excluded from the

l e
employee element.

c
• The min_salary attribute as a #FIXED attribute, in which case a quoted default

r a
value is mandatory in the declaration. When the min_salary attribute is used, it
must have the same value as declared in the DTD. A #FIXED attribute value is
O constant and cannot be changed in the XML document.
If an attribute declaration uses the #REQUIRED keyword, it forces the XML document to
use the attribute and specify a value in its element.

Oracle 10g: XML Fundamentals 2-15


Entities in XML

• Entity types predefined by XML standards:


– Built-in entities
– Character entities
• Entity types that can be declared in the DTD:
– General entities
– Parameter entities
• Entity references for:
– Built-in, character, and general entities can be made
in an XML document or the DTD using:
&entity-name;
– Parameter entities can be made in the DTD using:
%entity-name;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Entities in XML
U s
include:
A I
In XML, as per the World Wide Web Consortium (W3C) standard, predefine entities

O
• The built-in entities representing these special characters:
- The less than sign (<), represented by &lt;

l &
- The greater than sign (>), represented by &gt;
- The ampersand (&), represented by &amp;

n a
- The single quotation mark or apostrophe ('), represented by &apos;

te r
- The double quotation mark ("), represented by &quot;
• The character entities representing any Unicode character specified in the XML

I n
recommendation, which is based on Unicode 3.0. Character entities are formed using
an ampersand (&) followed by a hash (#), then a Unicode character number, and

l e
terminated by a semicolon (;). For example, &#169 denotes the copyright symbol
c
(©). The character number can be a decimal or a hexadecimal Unicode value.

r a
Hexadecimal values are prefixed by an x. For example, &#xA9 represents the

O copyright symbol (©).


An entity reference to a parameter entity is done in a DTD. However, references to built-in,
character, and general entities can be done in the XML document and a DTD, for example,
<Company>&quot;Oracle Corporation&quot;</Company> instead of
<Company>"Oracle Corporation"</Company>
Oracle 10g: XML Fundamentals 2-16
General Entity Declarations

• Internal entity declaration (parsed)


<!ENTITY entity-name "replacement text">

<!ENTITY company "Oracle Corporation">


<!ENTITY Emperor "Alexander &quot;The Great&quot;">
<!ENTITY president "<employee>
<last_name>King</last_name>
</employee>">
• External entity declarations:
– Parsed (text stored in external location)
<!ENTITY entity-name SYSTEM "file.ext | URL">
– Unparsed (requires a notation declaration)
<!ENTITY entity SYSTEM "file.ext" NDATA notation>
<!NOTATION notation SYSTEM "text">
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
General Entity Declarations
U s
General entities:

A
• Must be declared in a DTD before you use it in the XML documentI
• May be used in the DTD as well
O
• Are used to create reusable sections of replacement text that can represent entire

• Can be declared:
l &
paragraphs, strings, or even entire documents

n a
- Internally (direct), with replacement text held within the DTD declaration

te r
- Externally, with replacement text stored outside in the DTD in a file or a Web
address (via URL). External entities are used to include large quantities of data

I n
and are declared with the SYSTEM keyword before a file name or a URL.
To reference a general entity, prefix the name with an ampersand (&) and terminate it with a
l e
semicolon (;). An XML Parser replaces an entity reference with its replacement text. For
example:
c
r a <organization>
&company; is a software company
O
Expands to:
</organization>

<organization>
Oracle corporation is a software company
</organization>
Oracle 10g: XML Fundamentals 2-17
General Entity Declarations (continued)
Well-Formed Parsed Entities
The replacement text of parsed internal or external entities must consist of well-formed
XML content. These entities can be used as replacement text inside XML elements or
attributes, and other DTD declarations. For example, in the slide, the entity declarations for
company, Emperor, and president are all (well-formed) parsed internal entities.
However, the following examples are not well-formed and therefore invalid:
<!ENTITY starttag "<emp>"> <!-- must contain end tag -->
<!ENTITY endtag "</emp>"> <!-- must contain start tag -->
<!ENTITY ref "change to &ref;"> <!-- recursive not allowed -->
Note: The last example in the notes is recursive. You cannot have a recursive entity.
Parsed External Entities
Examples of parsed external entities can be another file containing, or a URL referencing,
data that conforms to well-formed XML data. For example:
<?xml version="1.0"?>
<!DOCTYPE employees [
<!ENTITY employeeData SYSTEM "employee.xml">
]>
<employees>
&employeeData;
</employees>
The employee.xml document can contain:
<employee>
n l y
<last_name>King</last_name>
</employee>
e O
Unparsed External Entities
U s
such as:
A I
There is often a requirement to include data that is not well-formed in an XML document,

O
• HTML text that has tags that are not paired, do not overlap, and must not be
interpreted as XML elements

l &
• Image data to be processed by the XML application
a
• Text data containing special XML characters that must not be interpreted
n
te r
Using an unparsed external entity is one way to include data that will be processed and not
validated by an XML Parser. To convert a parsed external entity declaration into an

I n
unparsed external entity declaration, add:
• The NDATA keyword after the file name or URL
l e
• A notation name after the NDATA keyword
c
r a
The notation name must be declared in a <!NOTATION ..> declaration, as shown in the
example in the slide.
O
Note: External entities can make the DTD more manageable by reducing the size of the
entity declarations if the replacement text is very extensive (because there are no size
limits).

Oracle 10g: XML Fundamentals 2-18


Parameter Entities

• Declared as:
<!ENTITY % entity-name "replacement text">
– Requires a space after the percent (%) symbol
– Must be declared before referenced in the DTD
– Must be defined in an external DTD
– Replacement text can be in external location using:
<!ENTITY % entity-name SYSTEM "file.dtd | URL ">
• Examples:
<!ENTITY % employee_elements "last_name, salary">
<!ENTITY % employee_elements SYSTEM "empelm.txt">
• Referenced in the DTD using:
%entity-name;
<!ELEMENT employee (%employee_elements;)>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Parameter Entities
U s
A I
Declaring a parameter entity requires a percent (%) sign and a space, after the ENTITY
keyword and before the entity name. Referencing a parameter entity requires that you use

O
the percent (%) sign followed by the entity name (no space required) terminated with a

l &
semicolon (;). A parameter entity must be declared:
• In an external DTD, and therefore cannot be declared in an internal DTD
• Before they are referenced in the DTD
n a
Using Parameter Entities

te r
If the content model of multiple elements are identical, then use a parameter entity to
I n
represent the structure of the content model, thereby avoiding repetitive typing. Changing

l e
the content model can be done in one place. For example, consider the following elements:

c
<!ELEMENT employee (id, firstname, lastname)>

r a <!ELEMENT manager (id, firstname, lastname)>

O
Instead of declaring them individually, you can declare and a parameter entity and reference
it to achieve the same result, as shown in the following example,
<!ENTITY % personcontent "(id, firstname, lastname)">
<!ELEMENT employee %personcontent;>
<!ELEMENT manager %personcontent;>

Oracle 10g: XML Fundamentals 2-19


Complete DTD: Example

File: employees.dtd
<!ELEMENT employees (employee+)>
<!ELEMENT employee (employee_id, last_name)>
<!ATTLIST employee manager_id CDATA #IMPLIED
department_id (10|60|90) '90'>
<!ELEMENT employee_id (#PCDATA )>
<!ELEMENT last_name (#PCDATA )>
<?xml version="1.0"?>
<!DOCTYPE employees SYSTEM "employees.dtd" [
<!ENTITY title "Mr">
]>
<employees>
<employee manager_id="100" department_id="10">
<employee_id>100</employee_id>
<last_name>&title; king</last_name>
</employee>
</employees>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Complete DTD: Example
U s
A I
This slide shows a complete example of an XML document and associated DTD that
summarizes some of the features of DTD declarations covered in this lesson. In particular,
the example illustrates:
O
l &
• Combining an external DTD and an internal DTD, as highlighted in the slide, where
the ENTITY declaration is added to the internal DTD subset
a
• Declaring of elements, such as employees, employee, employee_id, and
n
last_name

te r
• Specifying a cardinality symbol (+) for employee elements

models I n
• Using the (employee_id, last_name) sequence, and #PCDATA content

l e
• Declaring multiple attributes, such as manager_id and department_id for the
c
r a
employee element
• Using default attribute values for the department_id

O
Oracle 10g: XML Fundamentals 2-20
Validating XML Against a DTD

The oraxml command-line utility or XML Parser:


• Requires xmlparserv2.jar in the CLASSPATH
• Uses –dtd option for full validation with a DTD:
java oracle.xml.parser.v2.oraxml –dtd emp.xml
• Produces the following message when the XML
document is valid:
The input XML file is parsed without errors
using DTD validation mode.

• Can be invoked, in this course, as an External Tool


in Oracle JDeveloper 10g
– Right-click the XML document
– Select OraXML-dtd from the menu
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Validating XML Against a DTD
U s
A I
The oraxml utility is a command-line interface to the Oracle XML Parser supplied with
the Oracle XML Developer’s Kit (XDK). The oraxml command-line utility can be used to

O
validate an XML document against a DTD using the following syntax:

l &
java oracle.xml.parser.v2.oraxml –dtd emp.xml
The –dtd option specifies that the supplied XML document (emp.xml) must be validated
a
against the DTD specified in the <!DOCTYPE> declaration contained in the XML file.
n
te r
To run the oraxml command-line utility, ensure that the xmlparserv2.jar is added to
the Java CLASSPATH, for example,

I n
set CLASSPATH=E:\JDeveloper\lib\xmlparserv2.jar

c l e
java oracle.xml.parser.v2.oraxml –dtd emp.xml
In this course, Oracle JDeveloper has been configured as an External Tool enabling the

r a
execution of the oraxml utility with any XML document in a project. To invoke the
oraxml as an External Tool command:
O
1. Right-click the XML document in the Navigator or source code XML Editor.
2. Select OraXML-dtd from the menu.
Note: Using the External Tool option eliminates the need to start a command window.

Oracle 10g: XML Fundamentals 2-21


Summary

In this lesson, you should have learned how to:


• Use an internal and an external DTD
• Read and write DTD declarations for:
– Elements
– Attributes
– Entities
– Notations
• Validate XML documents with a DTD using:
– The oraxml command-line utility
– Oracle JDeveloper configured to invoke the oraxml
command-line utility

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
A document type definition (DTD) establishes the grammar for a valid structure of an XML
document. This is similar in concept to how a database schema establishes the structure of a

O
relational database. When an XML document follows the rules declared in the DTD, the

l &
XML document is said to be “valid.” The DTD declares the following structural items:
• Elements and their content models, such as parsed character data (#PCDATA) for
a
non-markup text, element names, sequences, or choices. The content model and
n
te r
elements that can be given a cardinality to specify the number of occurrences
permitted using the following suffixes:

I n
- The + for a mandatory (one or many) occurrence
- The * for an optional (zero or many) occurrence

l e
- The ? for an optional (zero or one) occurrence
c
r a
Note: The absence of a suffix means that there is one and only one occurrence.
• Attributes representing additional properties of an element. Attributes can have valid
O values, and you can specify whether attributes are optional or mandatory as well.
• Entities that can be used to substitute their name with replacement text, which can be
defined internally in the DTD or obtained from external sources such as a file or URL
Validation can be performed using the Oracle XML Parser oraxml command-line utility.

Oracle 10g: XML Fundamentals 2-22


Practice 2: Overview

This practice covers the following topics:


• Associating a DTD with an XML document
• Validating an XML document by using an external
DTD
• Adding internal DTD declarations to extend the
XML document structure and content

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Practice 2: Overview
U s
A
using an external DTD to validate an XML document. Tasks include: I
In this practice, you are provided with a DTD for employees to test your understanding of

O
• Associating the external DTD to an existing XML document
• Validating the XML document
• Correcting validation errors
l &
a
• Extending the DTD by using internal DTD declarations
n
te r
Note: The practice uses the oraxml command-line utility configured as an external tool in
JDeveloper to validate the XML document. Although Internet Explorer does not implement

I n
strict DTD validation, it is used so that you can view the resulting XML document tree

c l e
particularly to see the resulting document after the entities are replaced.

r a
O
Oracle 10g: XML Fundamentals 2-23
Practice 2
The goal of this practice is to create a valid XML document based on DTD declarations.
You also create internal DTD declarations.
1. Modify the employees.xml file by adding a new employee and validate the
document by using a supplied DTD.
a. Add the following new employee as the last <employee> element in the
employees.xml file, just before the </employees> end tag:
<employee>
<emp_id>007</emp_id>
<last_name>Bond</last_name>
<first_name>James</first_name>
</employee>
Hint: Copy the text from E:\labs\lab\lab_02_01_a.xml to save time.
Check the syntax of the employees.xml document and save the changes.
b. Add the DTD file E:\lab\labs\employees.dtd to your project and
examine the DTD declarations.
c. Associate the employees.dtd file with employees.xml by inserting an
appropriate document type declaration using a <!DOCTYPE …> entry. Check
the XML syntax, correct syntax errors, and save the changes to the file.
d. Validate employees.xml using the Tools > OraXML-dtd menu, and
check for errors in the Message Log window.
e. Using information in the Message Log window, make corrections to the
employees.xml document, and save your changes. Validate the
employees.xml using Tools > OraXML-dtd until the errors are fixed.
n
2. Associate an external DTD with departments.xml, validate, and correct the l y
document using an internal DTD declaration.
a. Add the E:\labs\lab\departments.dtd file into the
e O
use the DTD.
U s
XMLLabsProject, and add a DOCTYPE reference in departments.xml to

A I
b. Validate the departments.xml document using Tools > OraXML-dtd.
Explain any errors reported and correct them, and validate again to confirm that
the changes you have made are valid.
O
l &
Hint: The num attribute is used as a sequence number.
c. Modify the DOCTYPE declaration in departments.xml to include an internal
a
DTD declaration redefining the num attribute to use the #IMPLIED default
n
OraXML-dtd.
te r
setting. Save the changes and validate departments.xml using Tools >

I n
d. In the internal DTD, add an external entity declaration called deptData that
references an external file called E:\labs\lab\newdepts.txt. Add

l e
newdepts.txt file to your project to view its contents, and observe that the
c
second <department> element (for department 40) does not have a num

r a
attribute.

O e. Reference the deptData entity before the end tag of the document root
element. Save the changes to departments.xml, and validate the document
using Tools > OraXML-dtd.
f. View the document in Internet Explorer to see the results of the entity reference
being replaced by the contents of the newdepts.txt file.
Oracle 10g: XML Fundamentals 2-24
Modularizing XML with Namespaces

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe XML Namespaces
• Explain the need for XML Namespaces
• Use XML Namespaces in an XML document
• Use XML Namespaces with prefixes
• Manage the scope of XML Namespace
declarations

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
XML Namespaces represent a group or collection of names. XML Namespaces are the
solution to the problem of ambiguity and name collisions. This lesson introduces how to:
• Declare an XML Namespace with or without prefixes
O
• Use the XML Namespaces in an XML document

l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 3-2
What Is an XML Namespace?

An XML Namespace:
• Is identified by a case-sensitive Internationalized
Resource Identifier (IRI) reference (URL or URN)
• Provides universally unique names for a collection
of names (elements and attributes)

<employee> <departments>
employee_id <name>
<name> department_id
<salary> <location_id>

http://hr.com/employees urn:hr:departments
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
What Is an XML Namespace?
U s
An XML Namespace:

A I
• Is identified by Internationalized Resource Identifier (IRI), which is a case-sensitive
string of characters identifying a resource
O
and attribute names
l &
• Provides a universally unique name for a collection of XML names made of element

a
The IRI is a string of characters that can be formatted as:
n
te r
• An Uniform Resource Indicator (URI) or Uniform Resource Locator (URL), such as a
Web address http://hr.com/employees.

I n
Note: The URL, or Web address, represents a unique string and is not checked to be a
valid or existing Web address.

l e
• An Uniform Resource Name (URN), such as urn:hr:departments. A URN starts
c
with the letters urn, followed by a colon (:), a Namespace Identifier (NID) (hr), a

r a
colon (:), and a Namespace Specific String (NSS) (departments).

O
The example in the slide shows two collections of XML element and attribute names, each
identified by a unique XML Namespaces IRI. If the XML Namespace was not used, then the
<name> element for an employee will be indistinguishable from the <name> element of
the department. Applying the XML Namespace qualifies each <name> element removing
the ambiguity, particularly if the documents are merged.
Oracle 10g: XML Fundamentals 3-3
Why Use XML Namespaces?

Using an XML Namespace resolves name collisions or


ambiguities in an XML document.
<?xml version="1.0"?> <?xml version="1.0"?>
<department> <department>
<name> <name>
Executive Executive
</name> </name> Which name?
</department> <employee>
<?xml version="1.0"?> <name>
<first_name>Steven</f
<employee>
<name> <last_name>King</last
</name>
<first_name>Steven</first_name>
<last_name>King</last_name><salary>2000</salary>
</name> </employee>
<salary>2000</salary> </department>
</employee>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Why Use XML Namespaces?
U s
attributes. XML Namespaces:
A I
XML Namespaces are designed to provide universally unique names for elements and

O
• Resolve name ambiguity and collision problems that can occur when XML document
fragments are combined, or multiple elements have similar type and attribute names in
the same XML document
l &
a
• Allow code modules to be invoked for specific elements and attributes

n
te r
If two companies are interchanging XML messages, they must come to a common
agreement on the meaning of the element and attribute names in the messages. This can be
achieved by two means:

I n
• Defining the meaning, format, and domain of every element and attribute needed

c l e
• Recognizing element and attribute names without ambiguity
The first can be accomplished by using an XML Schema definition. The second is solved by

r a
using XML Namespaces to qualify element names.
The examples in the slide illustrate the combining of a <department> element with one
O
of its <employee> elements. Each document is different and defines a <name> element.
Each <name> element has a different content model and must be interpreted by an
application in a different way. The problem does not arise when the elements exist in
separate documents.
Oracle 10g: XML Fundamentals 3-4
Declaring XML Namespaces

Declare an XML Namespace:


• With the xmlns attribute in an element start tag:
– Assigned an IRI (URL, URI or URN) string value
– Provided with an optional namespace prefix
• With a namespace prefix after xmlns: to form
qualified element names:
<dept:department
xmlns:dept="urn:hr:department-ns">
...
</dept:department>
• Without a prefix to form a “default namespace”:
<department xmlns="http://www.hr.com/departments">
...
</department>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring XML Namespaces in an XML Document
U s
An XML Namespace is declared:

A I
• In the start tag of an XML element by using the xmlns attribute, which has:

O
- A value, representing the unique XML Namespace string (or IRI)

l &
- An optional prefix, providing an abbreviation for the XML Namespace string
• With a namespace prefix to explicitly qualify elements and attributes names. The
a
namespace prefix is declared after xmlns: and is used with an XML element to
n
te r
create a qualified name. An element name without a prefix is called the local name.
A prefix can also be used to qualify an XML attribute name.

I n
• Without a prefix to form a default namespace, which implicitly qualifies the element
name and its children that are not explicitly qualified by a prefix

c l e
Note: Attributes specified without a prefix are not associated with an XML Namespace.

r a
The examples in the slide show two XML Namespace declarations:
1. The urn:hr:department-ns string, which is assigned the dept prefix. The
Oprefix is used to qualify the department element name in the start and end tags.
2. The http://www.hr.com/departments string, which is a default namespace
Note: An XML Namespace string does not have to reference an actual document or page.

Oracle 10g: XML Fundamentals 3-5


XML Namespace Prefixes

A namespace prefix:
• May contain any XML character except a colon
• Can be declared multiple times as attributes of a
single element, each with different names whose
values can be the same or a different string
• Can be overridden in a child element by setting
the value to a different string. For example:
<?xml version="1.0"?>
<emp:employee xmlns:emp="urn:hr:employee-ns">
<emp:last_name>King</emp:last_name>
<emp:address xmlns:emp="urn:hr:address-ns">
500 Oracle Parkway
</emp:address>
</emp:employee>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Namespace Prefixes
U s
A I
An XML Namespace prefix qualifies a local element and attribute name by a particular
XML Namespace. The example in the slide qualifies the last_name element by using the

O
emp prefix representing the urn:hr:employee-ns XML namespace. The address

l &
element also uses the emp prefix (which qualified by a different namespace) that is
urn:hr:address-ns, overriding the parent element definition for the XML namespace.
a
The following example shows two different prefixes (A and B) being used with the same
n
XML namespace:

te r
<A:department xmlns:A="http://www.a.org/">

I n
<A:employees>
<B:name xmlns:B="http://www.b.org/">

c l e<B:first_name>Steven</B:first_name>
<B:last_name>King</B:last_name>

r a </B:name>

O
</A:employees>
</A:department>
Note: It is best to avoid using the same prefix on elements having a parent-child
relationship. It is best to avoid using the same prefix for different namespace declarations
because it can be confusing to read and create problems when processing the document.
Oracle 10g: XML Fundamentals 3-6
Example of XML Namespace Declarations

<?xml version="1.0"?>
<department xmlns="urn:hr:department-ns"
xmlns:emp="urn:hr:employee-ns">
<name>Executive</name>
<emp:employee>
<emp:name>
<emp:first_name>Steven</emp:first_name>
<emp:last_name>King</emp:last_name>
</emp:name>
</emp:employee>
<emp:employee>
<emp:name>
<emp:first_name>Neena</emp:first_name>
<emp:last_name>Kochhar</emp:last_name>
</emp:name>
</emp:employee>
</department>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example of XML Namespace Declarations
U s
A I
The slide shows an example of a <department> element containing two <employee>
elements. The <department> element shows an example of declaring two XML

O
Namespaces: a default and one with the emp prefix. The <name> element is used for:

l &
• The department name containing the Executives text
• The employee name containing the <first_name> and <last_name> child
elements
n a
te r
Without using XML Namespaces in the document, the <name> element will be ambiguous
to a processor and can possibly be treated as the same type, even though the department and

I n
employee names are semantically and structurally different.

l e
Using the XML Namespaces removes the ambiguity for each <name> element, which

c
allows them to be processed differently by an XML application. In the example in the slide:

r a
• The unqualified <department> and <name> elements are implicitly qualified by
the default namespace, urn:hr:department-ns, declared in the start tag of the
O <department> element
• All <employee> elements and their children, including the <emp:name> element,
are explicitly qualified with the emp prefix, which is associated to the
urn:hr:employee-ns XML Namespace.
Oracle 10g: XML Fundamentals 3-7
Scope of XML Namespace Declarations

<?xml version="1.0"?>
<root-level xmlns="urn:demo:default-ns"
xmlns:one="urn:hr:one-ns"
xmlns:two="urn:hr:two-ns">
<level-one id="1">A</level-one>
<one:level-one id="2">
<one:level-two>B</one:level-two>
<two:level-two>C</two:level-two>
</one:level-one>
<one:level-one xmlns:one="urn:one:override-ns">
<level-two xmlns="">D</level-two>
<level-two>E</level-two>
<level-two xmlns:two="urn:two:override-ns">F
</level-two>
</one:level-one>
</root-level>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Scope of XML Namespace Declarations
U s
A I
The scope of a default or prefixed XML Namespace declaration extends from the beginning
of the start tag in which it appears to the end of the corresponding end tag, unless it is

O
overridden in a child (descendant) element by an inner declaration.

l &
Note: In the case of an empty element, the scope of the XML Namespace is the element
itself. The default namespace declaration applies to all nonprefixed element names within its

n a
scope. In the slide, the default namespace applies to:

te r
• The <level-one id="1"> element
• The <level-two> element containing the texts E and F, because the element

I n
containing the text F does not use a prefix

l e
The attribute value for an XML Namespace declaration may be the empty string. An XML

c
Namespace with an empty string has the effect of removing any association of the default

r a
namespace or prefix with any XML Namespace name, for example, the <level-two>
element containing the text D in the slide. In this case, additional declarations may be made
O
to redeclare the default namespace or prefix again.
Note: Elements using a prefix, without its XML namespace declaration in scope, is an error.

Oracle 10g: XML Fundamentals 3-8


Invoking the ShowXmlNS Tool

Right
click

Results

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Invoking the ShowXmlNS Tool
U s
A I
In this course, the Java source code and class has been provided in your project for use in the
lesson practices to examine the effects of applying XML Namespaces to elements in an

O
XML document. The Java class has been configured as an External Tool in JDeveloper that
can be invoked by:

l &
• Right-clicking an XML document in the Navigator, or in the XML Editor
• Selecting ShowXmlNS from the menu
n a
te r
The tool displays the effects of using XML Namespace declarations in an XML document
by showing the expanded name as a pseudo attribute for each element in the XML

I n
document. The printed results can be seen in the JDeveloper Message Log window.

l e
Note: The ShowXmlNS tool is written in Java using the DOM API available in the Oracle

c
XML Parser (xmlparserv2.jar). The source code is included in your course project.

r a
To run the tool from the command line, execute the following command:

O
set CLASSPATH=E:\JDeveloper\lib\xmlparserv2.jar;E:\labs\classes
java ShowXmlNS filename.xml

Oracle 10g: XML Fundamentals 3-9


Summary

In this lesson, you should have learned how to:


• Declare an XML Namespace
• Declare a default XML Namespace
• Use an XML Namespace with or without a prefix
• Qualify element and attribute names with an XML
Namespace
• Manage the scope of XML Namespace
declarations

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
An XML Namespace is a string identifier used to qualify a collection of element and
attribute names. If an element has a namespace prefix, it has two parts:
• The local name, that is, the element name itself
O
prefix used
l &
• The qualified name, which includes the local name and the the XML Namespace

n a
When the element is combined with the XML Namespace string associated with its prefix, it

te r
is called the expanded name forming the universal name of the element.
An XML Namespace is declared using the xmlns attribute in the start tag of an element.

I n
The xmlns attribute, which may or may not be followed by a colon and prefix name, has a

l e
case-sensitive value representing a XML Namespace string or International Resource

c
Identifier (IRI), that is, a URL, URI, or URN that is not checked as a valid Web address. A

r a
default namespace is declared and applied when the prefix is not used; otherwise, elements

O
must be qualified by their appropriate prefixes.
The scope of a namespace declaration includes the element in which it is declared and its
descendants, unless overridden by another namespace declaration in a child element. The
namespace string value may be an empty string, which effectively cancels the namespace.

Oracle 10g: XML Fundamentals 3-10


Practice 3: Overview

This practice covers the following topics:


• Modifying an XML document to contain XML
Namespace declarations and prefixes
• Using the ShowXmlNS tool to examine the effects
of using XML Namespaces in an XML document

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Practice 3: Overview
U s
Namespaces.
A I
In this practice, you test your understanding of writing an XML document with XML

O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 3-11
Practice 3
The goal of this practice is to add XML Namespaces to an existing XML document and then
use the ShowXmlNS tool to examine the effects of using XML Namespaces.
Note: In this course, the source code for the ShowXmlNS Java class is provided in the
JDeveloper project. Oracle JDeveloper has been configured to have an External Tool
command called ShowXmlNS that can be invoked using the following steps:
i. Right-click the XML document in the Navigator or the XML Editor.
ii. Select ShowXmlNS from the menu.
The ShowXmlNS displays the expanded XML Namespace in the start tag of each element in
the Message Log window.
1. In the XMLLabsProject, edit employees.xml, and add a default XML
Namespace.
a. In the employees root element, add a default XML Namespace with the URN
string value urn:hr:employees and save the change to the XML document.
b. Run the ShowXmlNS tool and explain the results.
2. In the XMLLabsProject, edit departments.xml, and add an XML Namespace
by using a namespace prefix.
a. In the <departments> root element, add an XML Namespace using the dept
prefix, and URL value of http://www.hr.com/departments. Save the changes and
predict the namespace applied to each element in the document. Run
ShowXmlNS to confirm your results.

l y
b. Apply the dept namespace prefix to the start and end tags of <department>
elements in the departments.xml document, and save the changes.
n
c. Run the ShowXmlNS tool and explain the results.
e O
Note: Do not edit the file identified by the &deptData; entity reference.

U s
3. Add the file E:\labs\lab\hr.xml to your XMLLabsProject and examine the
effects of using XML Namespaces without using the ShowXmlNS tool until you have

a. The <hr> element A I


answered the following question: What is the expanded namespace for the following:

b. The <department> element O


c. The <department_name> element
d. The <location_id> element
l &
n
e. The <employees> element a
te r
f. The <employee> element containing the data for Alexander Hunold
g. The <last_name> element containing the text Hunold

I n
h. The <employee> element containing the data for Bruce Ernst

c l e
Run the ShowXmlNS tool to verify your answers.

r a
O
Oracle 10g: XML Fundamentals 3-12
Validating XML by Using XML Schema

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe XML Schema
• Create an XML Schema document
• Reference an XML Schema in an XML document
• Create an XML Schema document by using:
– Built-in data types
– Simple types
– Complex types with sequences and choices
• Validate XML documents with XML Schema by
using:
– The oraxml command-line utility
– Oracle JDeveloper 10g

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
In this lesson, you learn about XML Schemas:
• Validating an XML document against XML Schema
A I
O
• The syntax for writing an XML Schema Document (XSD) using the elements defined in
the XML Schema namespace
References
l &
URL: http://www.w3.org/TR/xmlschema-0/
n a
r
Beginning XML, 2nd Edition, David Hunter et al. Wrox Publications

te
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 4-2
What Is an XML Schema?

XML Schema
• Is an XML language that defines and validates
the structure of XML documents
• Is stored in an XML Validates
XSD
Schema Document (XSD)
• Defines components, such as:
– Simple types definitions
– Complex type definitions
– Element declarations References
– Attribute declarations Instance
• Supports XML Namespaces, and built-in, simple,
and complex data types
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
What Is an XML Schema?
U s
A I
The W3C XML Schema Definition Language is an XML language (or vocabulary) used in an
XML Schema Document (XSD), for describing and constraining the content of XML

O
documents. The XSD is used to validate the structure of an XML document.

l &
An XML document, whose structure is based on the definitions in an XML Schema, is called an
instance document of that XML Schema. The slide shows an XML Schema Document stored
a
separately from the XML instance document that it describes and validates.
n
te r
The introduction of the XML Schema allowed XML technology to represent data types in a
standard format. The data types give a precise way of specifying the type of content that can be

I n
held in elements and attributes of an XML document. Using a document type definition (DTD)
provided no mechanism for specifying data types in a way that a database user may require. The
l e
XML Schema definition file builds upon DTD functionality while providing XML Namespace
c
a
and data type support.
r
O
Oracle 10g: XML Fundamentals 4-3
The Benefits of XML Schemas

XML Schemas:
• Unify both document and data modeling
• Validate XML documents
• Are created using XML
• Support the Namespace Recommendation
• Allow validation of text elements content based on
built-in or user-defined data types
• Allow modeling of object inheritance and type
substitution
• Allow easy creation of complex and reusable
content models

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The Benefits of XML Schemas
U s
A I
You can use XML Schema to specify the structure of XML documents and validate the XML
documents. Although most XML documents are well-formed, they may not be “valid.” A valid

O
document is well-formed and conforms to specific rules defined by either a DTD or an XML
Schema. The benefits of using an XML Schema for validation are the following:

l &
• They are easily created using XML, as defined by the W3C XML Schema language.

n a
• They support the W3C Namespace Recommendation.
• They can be used to validate content of text elements based on built-in and user-defined
data types.
te r
• They allow the creation of complex data type models that can be reused.

I n
• They support object inheritance and substitution in types.

l e
In the Web publishing world, a single page that displays local weather, stock quotes, horoscopes,

c
and specific news channels based on user preferences can involve dozens of queries made to

r a
underlying databases and application servers. These queries are made via SQL, the standard

O
object-relational query language, or via some programmatic interface that ultimately calls SQL.
Because both SQL and programming languages, such as Java, are strongly typed, they return
information that possesses type, structure, constraints, relationships, and so on. The structural
and data typing aspects of XML Schema can help exploit generation of viewable documents
from databases.

Oracle 10g: XML Fundamentals 4-4


An Example XML Schema Document

• The simple XML Schema uses:


– A required XML Namespace string, with an xs
prefix, http://www.w3.org/2001/XMLSchema
– The <schema> element as its document root
– The <element> element to declare an element
<?xml version="1.0"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="departments" type="xs:string"/>
</xs:schema>
• A valid XML instance document:
<?xml version="1.0"?>
<!-- The element cannot contain child elements -->
<departments>
Finance
</departments>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
An Example XML Schema Document
U s
A I
The example in the slide shows a simple XML Schema document that declares a single element
called departments. The XML Schema Document (XSD) uses the required XML Namespace

O
value http://www.w3.org/2001/XMLSchema, which is assigned the xsd namespace
prefix. The xsd prefix is used to qualify the schema, element, and string names to ensure

l &
that the XSD document structure conforms with the W3C XML Schema language

a
recommendation, that is, the XSD itself is a valid document.
n
te r
The XML Schema language elements used in the example are:
• The <xs:schema> element is the root element for the XSD, and contains the definitions

I n
for the structure of the XML instance document.
• The <xs:element> element declares a root element name, departments, for the

l e
XML instance document, an example of which is shown below the XSD code.
c
• The <xs:string> value is set as the data type for the contents of the departments

r a
element in the XML instance document. In this case, the data can be any string but not

Omarkup, that is, no child elements are permitted.


Although the example is a very simple XML Schema document, the resulting XML instance
document structure that can be created is not very useful.
Note: Using a namespace prefix, such as xs or xsd, is recommended but not required.

Oracle 10g: XML Fundamentals 4-5


Validating an XML Document with an XML
Schema Document

In the XML instance document, use the


http://www.w3.org/2001/XMLSchema-instance
XML namespace and reference the XML Schema using:
• The noNamespaceSchemaLocation attribute, or
• The schemaLocation attribute
noNamespaceSchemaLocation="file.xsd"
SD
schemaLocation="namespace file.xsd" X

validates
<?xml version="1.0"?>
<departments xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="departments.xsd">
Finance
</departments>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Validating an XML Document with an XML Schema Document
U s
A I
To validate an XML instance document using an XML Schema, the XML instance document
declares the http://www.w3.org/2001/XMLSchema-instance XML Namespace in

O
its root element to enable either of the following attributes to be used:
• The noNamespaceSchemaLocation attribute, whose value is a file name or URL

l &
string identifying the location of the XML Schema document

a
• The schemaLocation attribute, whose value is a namespace/file location pair

n
te r
identifying the location of an XML Schema using a specific XML Namespace string, a
space, and a file location (file name or URL) of the XML Schema document

I n
These attributes are a hint to the XML Parser to validate the XML document using the XML
Schema document identified by their value.

l e
Note: The http://www.w3.org/2001/XMLSchema-instance namespace must be
c
r a
given a namespace prefix, such as xsi. The prefix allows the schemaLocation or the
noNamespaceSchemaLocation attributes to be recognized by XML processor.

O
The code example uses the noNamespaceSchemaLocation attribute, which means the
XML document does not need to declare any XML Namespace for its elements. For example,
the departments element is not required to be qualified by an XML Namespace. However, it
is recommended to use the schemaLocation attribute.

Oracle 10g: XML Fundamentals 4-6


Referencing an XML Schema with the
schemaLocation Attribute

• The XML Schema defines the targetNamespace value.


<?xml version="1.0"?> <!-- departments.xsd -->
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.hr.com/departments">
<xs:element name="departments" type="xs:string"/>
</xs:schema>
• The XML document references the targetNamespace
in the schemaLocation and the default namespace.
<?xml version="1.0"?> <!-- XML document -->
<departments xmlns="http://www.hr.com/departments"
xmlns:xsi=
"http://www.w3.org/2001/XMLschema-instance"
xsi:schemaLocation=
"http://www.hr.com/departments departments.xsd">
Finance
</departments>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Referencing an XML Schema with the schemaLocation Attribute
U s
A I
It is recommended to use the schemaLocation attribute rather than the
noNamespaceSchemaLocation attribute. Using the schemaLocation forces a specified

O
XML Namespace to be used in an XML instance document. This helps to eliminate ambiguity
when referencing elements from multiple namespaces in the XML Schema and instance
documents.
l &
a
The XML Schema document in the example, departments.xsd, uses a
n
instance document.
te r
targetNamespace attribute to define the XML Namespace that must be used in the XML

I n
The XML instance document references the XML Schema for validation by using the
schemaLocation attribute to specify these two parts in its value:
l e
• The targetNamespace string as defined in the XML Schema document
c
r a
• The file name, or URL location, of the XML Schema document
Note: The targetNamespace attribute value is also declared as the default namespace in an
O
xmlns attribute of the <departments> element in the XML instance document.
It is recommended that you declare the targetNamespace in an xmlns attribute with a
namespace prefix in the XML Schema, enabling the XML Schema to unambiguously refer to,
reuse, or extend types and elements declared in the same XML Schema document.
Oracle 10g: XML Fundamentals 4-7
Components of an XML Schema

<schema> Partial component hierarchy


<element>

<attribute> <restriction>

<simpleType> <list>

<complexType> <union>

<group>
<group> <sequence>
<choice>

<all>
<attributeGroup>
<attributeGroup>
<attribute>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Components of an XML Schema
U s
more declarations for:
A I
The root of an XML Schema document is the <schema> component, which can contain one or

O
• An <element> for XML elements, which can contain <attribute>’s, or be structured
as <simpleType> or a <complexType>

l &
• An <attribute> representing a named attribute XML elements

a
• A <simpleType>, which is an atomic built-in data type, or structured as a <list> or

n
te r
<union> of other components, such as <enumeration> components
• A <complexType>, which defines a complex structure that may be composed of other

I n
components, such as a <sequence> or <choice> or <group>. For example, a
<complexType> is needed to declare a structure with child elements, and can define

l e
type structures used for deriving other types, or used as a user-defined type.

c
• A <group>, which names a structure composed of a <sequence>, <choice>, or an

r a
<all> component
• An <attributeGroup> defining a list of attributes
O
Note: An XML Schema contains more component types than discussed in this course, which
covers <element>, <attribute>, <simpleType>, <complexType>, and
<sequence> components. The <attribute> item is duplicated for clarity in the slide.

Oracle 10g: XML Fundamentals 4-8


Example of XML Schema Components

<?xml version="1.0"?> 1
<xsd:schema 2
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="region"> 3
<xsd:complexType> 4
<xsd:sequence>
5
<xsd:element name="region_id"
type="xsd:int"/> 6
<xsd:element name="region_name"
type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element> <?xml version="1.0"?>
</xsd:schema> <region xmlns:xsi="http://...">
<region_id>1</region_id>
<region_name>Europe</region_name>
XML document </region>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example of XML Schema Components
U s
The example for XML Schema contains the following components:
1. The XML declaration
A I
O
2. The <schema> root element with the namespace declaration
xmlns:xsd="http://www.w3.org/2001/XMLSchema" to indicate that the

l &
elements used in the XML Schema document, specified in the W3C XML Schema

a
Language recommendation, define the structure of an XML instance document. The
n
te r
namespace prefix, such as xsd, is optional but recommended. When the prefix is declared,
XML Schema elements must use the prefix–for example, <xsd:schema>.

I n
3. The <xsd:element> declaration within the <schema> element, which specifies a root
element name for the XML instance document–for example, region

l e
4. The <xsd:complexType> definition within <xsd:element>, which is needed to

c
indicate that the <region> element contains a sequence of child elements named

r a
<region_id> and <region_name>
5. The <xsd:sequence>,which defines the order of occurrence of the two element
O
declarations it contains, and forms the content model for the region element
6. The two <xsd:element> declarations for child elements region_id and
region_name, based on the built-in int and string data type, respectively

Oracle 10g: XML Fundamentals 4-9


The <schema> Declaration

• Is the root element in an XML Schema document


• Contains:
– Namespace information
– Defaults
– Version
<schema targetNamespace="URI"
attributeFormDefault="qualified"|"unqualified"
elementFormDefault="qualified"|"unqualified"
version="version number">
• Example:
<?xml version="1.0"?>
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLschema">
...
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The <schema> Declaration
U s
A I
The <schema> element is the root element in an XML Schema. It contains namespace
information, element or attribute defaults, and any version for the vocabulary. For example:

O
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace ="http://www.oracle.com/namespace"

l &
xmlns:target="http://www.oracle.com/namespace"

n a
attributeFormDefault="qualified"
elementFormDefault="qualified"
version="1.0">

te r
The XML Schema Namespace is http://www.w3.org/2001/XMLSchema. The following

I n
are valid XML Schema Namespace declarations:

c l e
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

r a<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
The namespace prefix has no significance and can be anything that you choose. The prefixes in
O
the preceding examples are most commonly used. An XML Schema declares vocabularies;
therefore, the optional targetNamespace attribute helps to uniquely identify a vocabulary,
and requires a matching namespace declaration to be used with references to declarations within
the same XML Schema.

Oracle 10g: XML Fundamentals 4-10


The <schema> Declaration (continued)
Declaring a Target Namespace
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace ="http://www.oracle.com/namespace"
xmlns:target="http://www.oracle.com/namespace">
Or
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oracle.com/namespace"
xmlns:target="http://www.oracle.com/namespace">
Note: Declaring the targetNamespace value as a default namespace, or using a namespace
prefix as xmlns:target="http://www.oracle.com/namespace", in the root
element allows the XML Schema document to reference vocabulary names declared in the same
XML Schema document. This is necessary when declaring names that are designed to be
referenced by other declarations to be extended or used to derive types for other components.
Declaring Defaults
You can modify the default values of declarations appearing within the XML Schema by setting
the attributeFormDefault and elementFormDefault attributes to the value
qualified or unqualified (the default). These attributes control the qualification of
elements and attributes, with a namespace, in the instance document.
An element or attribute is qualified if it has an associated namespace–for example,
<emp:employee xmlns:emp="http://www.hr.com/employee">
<first_name>Steven</first_name>
<last_name>King</last_name>
</emp:employee>
n l y
In this example,
• The <employee> element is qualified by a namespace
e O
associated namespace
U s
• The <first_name> and <last_name> elements are unqualified, that is, they have no

A
<employee xmlns="http://www.hr.com/employee">
I
In the following example, all elements are implicitly qualified by the default namespace:

<first_name>Steven</first_name>
O
<last_name>King</last_name>
</employee>
l &
n a
The last example can be explicitly expressed as shown here:

te r
<emp:employee xmlns:emp="http://www.hr.com/employee">
<emp:first_name>Steven</emp:first_name>

I n
<emp:last_name>King</emp:last_name>
</emp:employee>

c l e
r a
O
Oracle 10g: XML Fundamentals 4-11
Global and Local Declarations

• Global declarations: <schema ...


– Appear as direct children xmlns:t="http://...">
of the <schema> element <!– Global -->
– Can be reused within the <element name="A"/>
XML Schema document
<complexType name="B">
• Local declarations: <!-- Local -->
– Are valid in the context <sequence>
they are defined <element ref="t:A"/>
– Are not children of <element name="C"/>
the <schema> element </sequence>
– Can reference global </complexType>
type declarations by using
</schema>
a namespace prefix

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Global and Local Declarations
U s
In the XML Schema document, a component declaration is:

A I
• Global, if it is declared as a direct child of the <schema> element, such as the
<element> and <complexType> components in the slide
O
• Local, if it is declared within a component other than the <schema> element, that is, it is

l &
not a direct child of the <schema> element
In the slide, the global declarations are:
n a
te r
• The element A, which can appear as a root element in an XML instance document
• The complex type B, whose structure contains other local type declarations
The local types are:
I n
• The element B, whose type is derived from the reference to global element A
l e
• The element C, a simple local component
c
r a
To enable a local element, such as element A, to reference a global declaration within the same
XML Schema document, it is necessary to declare an XML Namespace (preferably with a
O
namespace prefix such as t) with the same value as the targetNamespace attribute in the
start tag of the <schema> element–for example,
<schema targetNamespace="http://www.hr.com/departments"
xmlns:t="http://www.hr.com/departments"...>

Oracle 10g: XML Fundamentals 4-12


Global and Local Declarations (continued)
This example shows how to reference global type declarations within the content model:
<?xml version="1.0" encoding="windows-1252"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:trg="http://www.hr.com/departments"
targetNamespace="http://www.hr.com/departments"
elementFormDefault="qualified">
<xsd:element name="department_id" type="xsd:int"/>
<xsd:element name="department_name" type="xsd:string"/>
<xsd:complexType name="departmentType">
<xsd:sequence>
<xsd:element ref="trg:department_id"/>
<xsd:element ref="trg:department_name"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="departments">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="department" type="trg:departmentType"
maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

l y
The preceding XML Schema reuses global type declarations in the ref and type attribute

n
values, which reference the names of the global component. It is recommended that an XML

O
Namespace prefix, such as trg (with a namespace value set in the targetNamespace), is
used to ensure that global type name references are unique within the document. In the example,
e
the global type names are:

U s
• The department_id and department_id, which are referenced in ref attributes

A I
of the element declarations in the complexType called departmentType
• The departmentType referenced in type attribute of the department element that

O
is a child (local) type in the departments global element

l &
Note: All schema elements are declared using the xsd prefix.
An XML instance document that conforms to the preceding XML schema is:
a
<?xml version='1.0' encoding='windows-1252'?>
n
xsi:schemaLocation=
te r
<departments xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

I n
"http://www.hr.com/departments code_04_13n.xsd"
xmlns="http://www.hr.com/departments">
<department>

c l e
<department_id>10</department_id>

r a
<department_name>Administration</department_name>
</department>

O
</departments>

Oracle 10g: XML Fundamentals 4-13


Declaring an Element

Declare a simple <element> with:


• A name attribute to specify the tag name
• A type attribute to specify the content allowed
<xsd:element name="first_name" type="xsd:string"/>
<first_name>Steven</first_name> <!-- XML -->
Full syntax:
<element
name="name-of-element"
type="global-type | built-in-type"
ref="global-element-name"
form="qualified | unqualified"
minOccurs="non-negative number"
maxOccurs="non-negative number | unbounded"
default="default-value"
fixed="fixed-value">

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring an Element
U s
attributes of <element> are:
A I
The XML Schema language uses the <element> component to declare an XML element. The

O
• The name attribute for specifying the tag name for the element
• The type attribute to specify the content type, or type of data contained in the element

l &
• The ref attribute for referencing global type names in the schema document

a
• The form attribute that can be used to override the elementFormDefault attribute

n
te r
value used in the <schema> element
• The minOccurs attribute that specifies the minimum number of times the element must

optional.
I n
appear in the XML instance document. A value of zero indicates that the element is

l e
• The maxOccurs attribute that indicates the maximum number of times the element can

c
appear in the XML instance document. A value of unbounded means that there is no

r a
limit to the number of element occurrences.
• The default attribute that specifies a default value for the element if it does not appear
Oin the XML instance document. The default is not applied to an element with a value.
• The fixed attribute indicates that the content of the element must be equal to this value.
Note: The example specifies that the first_name element contains the string data. The
string type is a built-in data type in the XML Schema language.
Oracle 10g: XML Fundamentals 4-14
Built-in XML Schema Data Types

The XML Schema Language provides built-in data


types, such as:
• The string type
• The int type
• The decimal type
• Many others (boolean, float, and so on)
Examples:
<xsd:element name="employee_id" type="xsd:int"/>
<employee_id>100</employee_id> <!-- XML -->

<xsd:element name="salary" type="xsd:decimal"/>


<salary>1000.50</salary> <!-- XML -->

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Built-in XML Schema Data Types
U s
SimpleType A I
The built-in data types that can be specified in the type attribute are listed in this table:
Example or Explanation
string O
l & “this is a string”
boolean
a true, false
float
double
t e rn single-precision floating point
double-precision 64-bit floating point
decimal
e In 123.45
integer
c l -12345; 0; 12345

r a
non-positive-integer 12345; 0

int
O
negative-integer -12345
123456789
short 12345
Oracle 10g: XML Fundamentals 4-15
Built-in XML Schema Data Types (continued)

SimpleType Example or Explanation


byte 123
non-negative-integer 0; 123456
unsigned-long 123456789012345
unsigned-int 1234567801
unsigned-short 12345
unsigned-byte 123
positive-integer 123456
date 2000-02-16
time 15:55:00.000
timeinstant 2000-12-31T05:55:00.000 (5:55 am, Coordinated Universal
Time)
timeduration P5Y1M4D10H20M1.2S (5 years; 1 month; 4 days; 20 minutes;

recurringinstant
1.2 seconds)

n l y
-02-16T5:55:00 (February 16th every year at 5:55 am.
Coordinated Universal Time)

e O
long
binary
1234567890123
bit pattern
U s
uri-reference standard URL
A I
ID*
O
XML 1.0 Compatibility
IDREF*
l &
XML 1.0 Compatibility

n a
ENTITY*

NOTATION*
te r
XML 1.0 Compatibility

XML 1.0 Compatibility


language I n en-US (see xml:lang in XML 1.0)
IDREFS*
c le XML 1.0 Compatibility

r
ENTITIES* a XML 1.0 Compatibility
O
NMTOKEN* XML 1.0 Compatibility
NMTOKENS* XML 1.0 Compatibility

Oracle 10g: XML Fundamentals 4-16


Declaring a <simpleType> Component

The <simpleType>:
• Is a derived type extending built-in or other types
• Provides three primary derived types:
– A <restriction>
– A <list>
– A <union>
• Has facets (properties), such as maxInclusive
<xsd:simpleType name="empid">
<xsd:restriction base="xsd:positiveInteger">
<!– for positiveInteger the minimum is 1 -->
<xsd:maxInclusive value="1000"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:element name="employee_id" type="empid"/>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring a <simpleType> Component
U s
A I
The <simpleType> declaration includes atomic or built-in types provided by the XML
Schema Recommendation, such as integer that requires character data are numbers in a
document instance. A <simpleType> declaration can be:
O
• For a derived type that extends a built-in or other simpleType declaration

l &
• For an element that contains data, and may not contain attributes or child elements
• Refined by using facets or properties
n a
In the example in the slide:

te r
• A <simpleType> called empid is declared as a <restriction> type

I n
• The <restriction> uses the base attribute to identify the built-in type from which the
<simpleType> is derived

l e
• The base type is positiveInteger, representing non-negative values
c
• The maxInclusive facet sets a maximum value of 1000 for this data type

r a
• The <element> for employee_id references the empid <simpleType> as its data

Otype, restricting employee_id elements to contain positive integers less than or equal to
1000.
Note: A valid XML code snippet is: <employee_id>999</employee_id>.

Oracle 10g: XML Fundamentals 4-17


Declaring a <simpleType> Component (continued)
The following table lists the facets, or properties that can be used in simpleType
declarations:

Facet Description

enumeration An allowable value in an enumerated list

fractionDigits The number of digits to the right of a decimal point in a


numeric type
length The number of items in a list type, or characters in a string type

maxExclusive A maximum value excluding the value listed

maxInclusive A maximum value including the value listed

maxLength Maximum number of items in a list type, or characters in a


string type
minExclusive A minimum value excluding the value listed

minInclusive A minimum value including the value listed

minLength Minimum number of items in a list type, or characters in a


string type
n l y
pattern
O
Restricts string type based on a regular expression

e
totalDigits
s
The total number of digits in a numeric value

U
whiteSpace
I
Controls how whitespace is treated within a type. Values are

A
preserve, replace, or collapse

O
For example: To restrict the job_id element value by using the <enumeration> facet:
<xsd:element name="job_id">
l &
<xsd:simpleType>

n a
<xsd:restriction base="xsd:string">

te r
<xsd:enumeration value="AC_MGR"/>
<xsd:enumeration value="AD_PRES"/>

I n
<xsd:enumeration value="FI_MGR"/>
</xsd:restriction>

c l e
</xsd:simpleType>
</xsd:element>

r a
The XML element can contain only one of the values specified in the enumeration list. For

O
example:
...
<job_id>AC_MGR</job_id> <!-- is valid -->
<job_id>XX_MGR</job_id> <!-- is not valid -->
...

Oracle 10g: XML Fundamentals 4-18


Using <list> and <union> SimpleTypes

• Declaring a <list>:
<xsd:element name="email">
<xsd:simpleType>
<xsd:list itemType="xsd:string"/>
</xsd:simpleType>
</xsd:element>
<email>SKING sking@hr.com</email>
• Declaring a <union>:
<xsd:simpleType name="mgrTypes">…</xsd:simpleType>
<xsd:simpleType name="repTypes">…</xsd:simpleType>
...
<xsd:element name="job_id">
<xsd:simpleType>
<xsd:union memberTypes="mgrTypes repTypes">
</xsd:simpleType>
</xsd:element>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using <list> and <union> SimpleTypes
U s
A I
The first example in the slide shows a declaration of a simpleType providing a <list> of
strings for the <email> element, which is shown in an XML snippet that uses a space-separated

O
list of e-mail strings. In the <union> example, if the mgrTypes is declared as:
<xsd:simpleType name="mgrTypes">

l &
<xsd:restriction base="xsd:string">

n a
<xsd:enumeration value="AC_MGR"/>
<xsd:enumeration value="FI_MGR"/>

te
</xsd:simpleType> r
</xsd:restriction>

I n
If repTypes is declared as:
<xsd:simpleType name="repTypes">

c l e
<xsd:restriction base="xsd:string">
<xsd:enumeration value="AC_REP"/>

r a <xsd:enumeration value="HR_REP"/>

O
</xsd:restriction>
</xsd:simpleType>
The following are valid XML snippets for the <job_id> element:
<job_id>AC_MGR</job_id>
<job_id>HR_REP</job_id>

Oracle 10g: XML Fundamentals 4-19


Declaring <complexType> Components

The <complexType> declaration:


<xsd:complexType name="..." mixed="true | false">
...
</xsd:complexType>
• Must be identified by a name attribute if it is
global; otherwise, it is an anonymous complex
type
• Provides a content model that can contain:
– Simple content
– A <sequence> declaration
– A <choice> declaration
– A reference to a global <group>
– An <all> declaration
• Can allow mixed or empty content
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring <complexType> Components
U s
A I
The <complexType> declaration is a powerful construct that enables you to create simple to
complex structures. A <complexType> that is declared globally, in the XML Schema

O
document, must be identified its name attribute. A locally declared <complexType> is called
an anonymous complex type, where the name attribute is not required. Setting the mixed

l &
attribute to true allows both text and element content to be included in the content for the
element.
n a
te r
The <complexType> declaration specifies different content models that enable the content to
be mixed, empty, or contain element hierarchies. A content model can contain:

I n
• Simple content, for data without child elements
• A <sequence> declaration, to specify an ordered sequence of child elements

l e
• A <choice> declaration, for providing a choice of child elements
c
• A reference to a global <group>, for reusing a group of elements to define the complex

r a
type structure

O
• An <all> declaration, to allow all elements in the content model to be used in any order
Note: Examples of the <sequence>, <choice>, and empty content models are discussed in
the subsequent pages.

Oracle 10g: XML Fundamentals 4-20


Declaring a <sequence>

• Defines an ordered sequence of elements


• Must be contained within a <complexType>
<xsd:element name="department">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="department_id"
type="xsd:int"/>
<xsd:element name="department_name"
type="xsd:string"/>
<xsd:element name="manager_id"
type="xsd:int" minOccurs="0"/>
<xsd:element name="location_id"
type="xsd:int" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring a <sequence>
U s
A I
The <sequence> is used within a <complexType> to declare an ordered list of elements.
The department element, in the slide, may contain the element sequence of the

O
<department_id> followed by the <department_name>, optionally followed by the
<manager_id> that can be optionally followed by the <location_id>.

l &
Note: The minOccurs attribute is zero for manager_id and location_id. Either of

n a
these elements may be omitted. However, if both appear, they must be entered in the sequence
shown above. For example, the following XML element is valid:
<department>

te r
<department_id>10</department_id>

I n
<department_name>Administration</department_name>

e
</department>

c l
However, the following is invalid because <location_id> is before <manager_id>:

r a<department>
<department_id>20</department_id>

O <department_name>Marketing</department_name>
<location_id>1800</location_id> <!-- Error -->
<manager_id>201</manager_id>
</department>

Oracle 10g: XML Fundamentals 4-21


Declaring a <choice>

• Defines a choice of alternative elements


• Must also be contained within a <complexType>
<xsd:complexType name="employeeType">
<xsd:choice>
<xsd:element name="full_time"
type="xsd:string"/>
<xsd:element name="part_time"
type="xsd:string"/>
</xsd:choice>
</xsd:complexType>
<xsd:element name="employee">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="full_name"
type="xsd:string"/>
<xsd:element name="contract"
type="employeeType"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring a <choice>
U s
A I
A <choice> allows for one of a selection of components to be included in the XML instance
document. A <choice> is declared within a <complexType>. Suppose that the Human

O
Resources department wants to identify employees as full-time or part-time staff. The example in
the slide declares an element for the type of employee, called employeeType, which can

l &
contain either a <full_time> or <part_time> element, but not both at the same time. The

a
following example is a snippet of a valid text in an XML document:
n
<employee ...>

te r
<full_name>Steven King</full_name>
<contract><full_time>Permanent</full_time></contract>

I n
</employee>

l e
The following example is invalid:

c
<employee ...>

r a <full_name>Steven King</full_name>
<contract><!-- Error can't contain both children -->

O <full_time>Permanent</full_time>
<part_time>Six Months</part_time>
</contract>
</employee>

Oracle 10g: XML Fundamentals 4-22


Declaring an Empty Element

• Using a <complexType> declaration without any


elements or a content model
• Typically contains attributes
<xsd:element name="departments">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="department"
maxOccurs="unbounded"/>
<xsd:complexType>
<xsd:attribute name="department_id"
type="xsd:int"/>
<xsd:attribute name="department_name"
type="xsd:string"/>
<xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring an Empty Element
U s
A I
An empty element does not allow text between the start and end tags. Empty elements are mostly
useful for elements with only attributes, that is, they do not have text content.

O
To declare an empty element without attributes in the XML Schema, use:
<xsd:element name="marker">
<xsd:complexType/>
l &
</xsd:element>

n a
te r
The valid XML syntax for marker is: <marker></marker> or <marker/>. The slide
declares departments containing one or more department elements, each with a

I n
department_id and department_name attribute.
Note: Text content is not allowed within each department element.

c l e
A valid XML instance document, using the XML Schema in the slide, can contain:

r a
<departments>
<department department_id="10"

O department_name="Administration"></department>
<department department_id="20" department_name="Marketing"/>
</departments>
Note: The second <department> element does not use the end tag format.

Oracle 10g: XML Fundamentals 4-23


Using Element Wildcards

Element wildcard declarations:


• Allow including elements without much control
• Provide a way to include elements from:
– Within the XML Schema and its namespace
– Another namespace
• Are declared using <any>:
<xsd:complexType name="commentType">
<xsd:sequence>
<xsd:element name="author"/>
<xsd:any namespace="##any"
processContents="lax"
minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="comments" type="commentType"/>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using Element Wildcards
U s
A I
You may want to use a form of element wildcard, which declares an element that does not
control its content when including any elements declared in the XML Schema’s or another

O
namespace. Declare an element wildcard by using <any>, with the following key attributes:
• The namespace attribute with a value of:

l &
- ##any allows elements from all namespaces

n a
- ##other allows elements from namespaces other than targetNamespace
- ##targetNamespace allows elements from the targetNamespace

te r
- ##local allows well-formed elements not qualified by a namespace
- A space-separated list of namespace URIs allows elements from the specified

I
namespaces n
c l e
• The processContents attribute with a value of:
- skip indicates to the processor to skip wildcard elements in an instance document

r a
- lax attempts the validation of the content elements if their declaring XML can be
accessed. However, errors are not flagged.
O - strict (the default) validates the content if the declaring XML Schema can be
accessed, and errors will be flagged
For example: Use an element wildcard to create elements that you want to contain HTML/XHTML
tags as part of formatting instructions for the data within the element.

Oracle 10g: XML Fundamentals 4-24


Declaring Attributes

Declare an <attribute>:
• Identified by the name attribute
• With the type attribute restricted to built-in or
user-defined simple types
<xsd:attribute name="department_id"
type="xsd:string"/>
Full syntax:
<attribute
name="name-of-attribute"
type="global-type | built-in-type"
ref="global-attribute-declaration"
form="qualified | unqualified"
used="optional | prohibited | required"
default="default-value"
fixed="fixed-value">

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring Attributes
U s
A I
Attributes declared by using an <attribute> component are identified by a name and a
type that is based on a built-in or user-defined <simpleType>. An attribute can be declared
in three ways:
O
• As a local type contained within another component, such as an <element> or an
<attributeGroup>
l &
a
• As a global type that can be referenced, extended, and reused in a local type or as part of an
n
<attributeGroup>

te r
• As a reference to an existing global type

I n
In the slide, the department_id is a global declaration if it appears as a direct child of the
<schema> component, otherwise it is a local type if nested within an element other than

l e
<schema>. Other attributes of the <attribute> component are:
c
ref, derives the type from an existing global attribute declaration
a



O r
form, indicates the attribute must be qualified by namespace prefix or not (the default)
used, indicates that the attribute is optional (the default), required, or
prohibited (not allowed)
• default, defines a default value for the attribute when it is optional and not specified
• fixed, defines a constant value for the attribute

Oracle 10g: XML Fundamentals 4-25


Attribute Declarations: Example

1. Based on a <simpleType>:
<xsd:attribute name="department_id">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxInclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
2. With a default value:
<xsd:attribute name="department_id"
type="xsd:int" default="10"/>

3. Referencing a global type:


<xsd:attribute ref="department_id"/>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Attribute Declarations: Example
U s
A I
The first example declares the department_id attribute using a <simpleType>
declaration. The <simpleType> uses a <restriction> to constrain the data type values to
being positive integer values less than or equal to 100.
O
l &
The second example declares the department_id as a simple integer type with a default
value of 10. The default value is assumed if the attribute is not included in the XML document.

n a
The third example declares an attribute referencing the department_id attribute type

te r
declared in the first example. The attribute reference example assumes that the
department_id is uniquely declared in the default namespace of the same XML Schema
document.
I n
c l e
Each of the above examples can be declared globally, or nested (locally) as part of:
• An element declaration

r a
• A <complexType> declaration. An example of this is shown in the section titled
“Declaring an Empty Element,” which contains attribute declarations
O
• An <attributeGroup> declaration, as discussed in the section titled “Declaring and
Referencing an <attributeGroup>”

Oracle 10g: XML Fundamentals 4-26


Declaring and Referencing an
<attributeGroup>

Declare an <attributeGroup>:
• Identified by the name attribute
• Containing one or more <attribute>s, or
references to <attributeGroup>s
<xsd:attributeGroup name="departmentGroup">
<xsd:attribute name="name" type="xsd:string"/>
<xsd:attribute name="id" type="xsd:int"/>
</xsd:attributeGroup>
Reference in a <complexType> or
<attributeGroup>:
<xsd:element name="department">
<xsd:complexType>
<xsd:attributeGroup ref="departmentGroup"/>
</xsd:complexType>
</xsd:element>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring and Referencing an <attributeGroup>
U s
A I
The <attributeGroup> is a collection of attribute declarations. Although an
<attributeGroup> can be declared locally, they are more useful when declared globally so
that the group can be reused in different components.
O
An <attributeGroup>:

l &
• Has a name that can be referenced by another <attributeGroup> declaration
• Can contain <attribute> declarations
n a
te r
• Can contain another <attributeGroup> declaration. However, recursive and indirect
circular references are not valid. The following examples are not permitted:

I n
<attributeGroup name="group1">
<attributeGroup ref="group1"/>

Or: l e
</attributeGroup>

c
r a<attributeGroup name="groupA">
<attributeGroup ref="groupB"/>
O </attributeGroup>
<attributeGroup name="groupB">
<attributeGroup ref="groupA"/>
</attributeGroup>

Oracle 10g: XML Fundamentals 4-27


Documenting the XML Schema

Document the XML Schema by using:


• XML comments
• Attributes from other namespaces
• An <annotation> declaration:
– Provides an <appinfo> element
– Contains a <documentation> element
– Can be included within all other component types
<xsd:annotation>
<xsd:appinfo source="file:///e:/labs/anno.xml"/>
<xsd:documentation>
A <b>big</b> comment about this Schema
</xsd:documentation>
</xsd:annotation>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Documenting the XML Schema
U s
A I
The slide lists different ways to document your XML Schema. Although XML comments are
valuable for reading the XML Schema document, most processors will not report the XML
comments.
O
l &
You can include references to attributes from namespaces other than the target namespace of the
XML Schema document. These attributes are ignored by the Schema processor and can be used
a
to pass information to other applications, and act as comments to the human reader of the
n
document.

te r
The best form of comment is to use the <annotation> declarations, which can be nested

I n
inside most other XML Schema component as a form of documentation. As shown in the slide,
an annotation can contain any element from any namespace. For example, the <b> and </b>
l e
elements represent bold text in the HTML/XHTML namespace. The <appinfo> element is
c
r a
optional and can include a source attribute to identify an external file for application processing
or documentation. Different XML Schema processors may ignore or treat the <appinfo>

O
contents differently.
Note: When creating an XML Schema document in JDeveloper, it automatically adds a sample
<annotation> element as a child of the <schema> component.

Oracle 10g: XML Fundamentals 4-28


Creating an XML Schema Document in
JDeveloper

3 4
1

6
Drag and drop

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating an XML Schema Document in JDeveloper
U s
1. Select a project node and click File > New….
A I
The slide shows a screen image of the following steps to create an XML Schema document:

2. Expand the General category and select the XML node.


3. Double-click XML Schema. O
l
4. Enter the XML Schema file name and click OK.&
a
5. The XML Schema document is created and opened in the XML Schema Editor, which
n
provides two editing tabs:

te r
a. A Design tab to graphically edit the XML Schema

I n
b. A Source tab to textually edit the document by using an XML editor that is aware of
the XML Schema recommendation elements and attributes. Initially, in the Design

l e
tab, view the <schema> element with a default targetNamespace attribute, and

c
a single child element called exampleElement is created.

r a
6. Add XML Schema components visually in the Design tab:

O - Right-click an item and select a component from a context-sensitive content menu, or


- Drag and drop Schema Components from the Component Palette

Oracle 10g: XML Fundamentals 4-29


Using the JDeveloper XML Schema Editor

2
1

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the JDeveloper XML Schema Editor
U s
A I
As shown in the slide, XML Schema Editor can be used visually by using the Design tab view.
Alterations made to the Design tab alters the source code by adding, modifying, or removing the

O
associated XML elements into the document, which can be viewed in the Source tab. While
editing in the Design tab:
1. Components can be:
l &
a
- Moved by using drag-and-drop techniques
n
te r
- Added into other components by right-clicking a component, and selecting an object
from the context-sensitive menu

I n
- Clicked to change their name in place, or by using the Property Inspector
2. The Component Palette provides XML components that can be dragged and dropped into

l e
place the Design window

c
3. The Property Inspector displays properties that can be altered to set component

r a
properties, such as minOccurs, maxOccurs, and type attribute values

O
4. The Structure pane displays the hierarchical structure of the document, and indicates
validation errors. The Structure pane can be used to navigate between components, and
add, modify, and delete components.
Click the Source tab to use the text-based XML Editor to view or make changes.

Oracle 10g: XML Fundamentals 4-30


Using the JDeveloper XML Schema-Aware
XML Editor

To use the XML Schema-aware Editor features:


1. Register an XML Schema with JDeveloper
2. Associate an XML document with an XML Schema
3. Use the XML Schema-aware code-insight, and
validate the XML menu features

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the JDeveloper XML Schema-Aware XML Editor
U s
A I
The slide lists the steps needed to enable you to use the JDeveloper XML Schema-aware features
of XML Editor. The following steps are discussed in the subsequent pages:

O
1. In JDeveloper, register the XML Schema document, which can be located in a file on disk
or from a URL on the Web.

l &
2. Create an XML document and associate the XML instance document with the XML

a
Schema in the start tag of the root element by using the schemaLocation attribute

n
te r
defined in the http://www.w3.org/XMLSchema-instance namespace.
3. The code-insight automatically becomes aware of the registered XML Schema, and you

I n
can start using it to rapidly create an XML instance document.
Note: JDeveloper has a list of preregistered XML Schemas, such as the XML Schema

l e
Recommendation that enables you to rapidly and visually create your own XML Schema
documents.
c
r a
O
Oracle 10g: XML Fundamentals 4-31
Registering an XML Schema with
JDeveloper

4
5

2 3 6

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Registering an XML Schema with JDeveloper
U s
A I
An XML Schema can be registered or imported into JDeveloper enabling the XML Editor to
become aware of the XML Schema. The steps to register an XML Schema are the following:

O
1. Select Tools > Preferences from the menu to display the Preferences window.
2. Click the XML Schema node.

l &
3. Click Add to display a dialog for entering the XML Schema location.

a
4. In the Add Schema dialog box, enter the file name or a URL for the XML Schema
n
te r
document, and the file extension to which it is applied (for example, xml).
5. Click OK to add the new XML Schema to the User Schemas for XML Editing list.

I n
6. Click OK to close the Preferences window.
The new XML Schema is now registered. You can select Tools > Configure Palette to add the

l e
XML elements defined in the registered XML Schema to the JDeveloper Component Palette.
c
This enables you to create elements by using the drag-and drop-techniques.

r a
To use the XML Schema-aware editing feature after the XML Schema is registered:

O
1. Create an XML document
2. Enter the root element of the document to associate with the XML Schema using
http://www.w3.org/Schema-instance namespace and setting the
schemaLocation attribute value to the XML Schema document

Oracle 10g: XML Fundamentals 4-32


Using the XML Schema-Aware XML Editor

• Code-insight is invoked when a less than (<)


character, space, or colon (:) is typed.
• Drag and drop from Component Palette.

2
3

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the XML Schema-Aware XML Editor
U s
A I
After the XML Schema is registered with JDeveloper, XML Editor becomes aware of its
vocabulary. Then, the JDeveloper code-insight feature can provide you with context-sensitive

O
selection of elements, attributes, and namespace prefixes. The numbers in the slide represent the
following:

l &
1. Create the root element, set the xmlns:xsi attribute, assign the XML Schema namespace

a
and document name to the xsi:schemaLocation attribute, and define a default (or

n
te r
prefixed) namespace for the document elements.
2. Enter a less than (<) character and wait a second after which JDeveloper code-insight will

I n
display the elements appropriate to that context. In the slide, the child element of the
<department> element includes the department_id, department_name,

l e
location_id, manager_id, and elements from the xsi: namespace (if the

c
departments XML Schema permits).

r a
3. Alternatively, perform a drag-and-drop operation with an element from the Component

O Palette, if it has been configured using the Tools > Configure Palette menu.
Note: Entering a less than (<) character causes elements to be displayed; typing a space after the
start tag causes a list of attributes to be displayed for the element; and typing a colon (:) after a
namespace prefix displays elements in the namespace (if accessible).

Oracle 10g: XML Fundamentals 4-33


Validating an XML Document with its XML
Schema in JDeveloper

To validate an XML document against an XML Schema:


• On the XML document, right-click one of the
following:
1. Navigator
2. XML
Editor 2

Select Validate XML from the menu


n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Validating XML Schema with JDeveloper
U s
can be validated against the XML Schema.
A I
After an XML Schema document is registered with JDeveloper, any XML instance document

O
The slide shows two ways to validate the XML document in JDeveloper:

from the menu.


l &
1. Right-click the XML document name in the Navigator pane, and select Validate XML

n a
2. Right-click the Source tab of XML Editor, and select Validate XML from the menu.

te r
Note: The Validate XML menu item is unavailable when the XML document is not associated

I n
with a registered XML Schema. However, if you do not want to register the XML Schema with
JDeveloper, the oraxml command-line utility can be used to validate an XML document

l e
against an XML Schema.

c
r a
O
Oracle 10g: XML Fundamentals 4-34
Validating an XML Document with its XML
Schema by Using oraxml

The oraxml Java command-line utility:


• Does not require registering the XML Schema
• Validates an XML instance document against an
XML Schema specified in the schemaLocation or
noNamespaceSchemaLocation attribute values
• Requires:
– The xmlparserv2.jar in the CLASSPATH
– The –schema option
– The XML document file name
java oracle.xml.parser.v2.oraxml -schema test.xml

The input XML file is parsed without errors using


schema validation mode.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Validating XML Against a Schema
U s
A I
The oraxml utility, a command-line interface for the Oracle XML Parser (in
xmlparserv2.jar), can be used to validate an XML document against an XML Schema

O
document. Invoke the oraxml utility by using the following command:

l &
java oracle.xml.parser.v2.oraxml –schema test.xml

n a
te r
Note: The java executable located in the Java Runtime Environment (JRE) binary directory
must be in the PATH. The xmlparserv2.jar file located in the JDeveloper library directory

I n
must be in the CLASSPATH.
The –schema option indicates that the test.xml file must be validated against the XML

l e
Schema specified in the root element of the XML document. For example, if the XML Schema is
c
contained in a file called test.xsd, then the XML instance document contains the following:

r a<test

O xmlns:xsi="http://www.w3.org/2001/XMLschema-instance"
xsi:schemaLocation="http://www.demo.com/test test.xsd"
xmlns="http://www.demo.com/test">
Sample data
</test>

Oracle 10g: XML Fundamentals 4-35


Applications for XML Schema

• E-commerce
• Web publications and syndication
• Enterprise Application Integration (EAI)
• Process control and data acquisition

XSD
XML Schema validates
the XML information exchanged.
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Applications for XML Schema
U s
A I
E-commerce: In both business-to-business and business-to-consumer e-commerce, data is
largely dynamic. XML Schema maps robustly to server-driven data models such as SQL:1999,

O
which provides user-defined types, inheritance, references between types, collections of types,
among others. Libraries of schemas define business transactions within markets and between

l &
parties. XML Schema validates a business document, and provides access to its information set.

a
Web Publications and Syndication: The key to syndication on the Web is in highly
n
te r
customizable distribution between publishing and syndication services. Collections of XML
documents with complex relations (such as cross-references and kind-of relations) among them

I n
will be the norm. Protocols, such as ICE and SOAP, that are built on XML, can take advantage
of the complex structural aspects of XML Schema.

l e
Enterprise Application Integration (EAI): The essence of an EAI hub-and-spoke architecture

c
is in the dynamic data exchange between loosely coupled applications. DTDs cannot fully

r a
describe today’s exchange data models. XML Schema capability for metadata interchange

O
simplifies EAI, and is an important optimization technology.
Process Control and Data Acquisition: In multivendor, distributed systems such as those in
plant automation, security, devices, and traffic routing, XML Schema can aid outgoing and
incoming message validity. Controllers can determine which parts of messages they
understand,when to ignore information, and when to raise errors.
Oracle 10g: XML Fundamentals 4-36
XML Schema Versus DTD

• XML Schema:
– Is more powerful and flexible than a DTD
– Provides better namespace support than a DTD
– Is written in XML syntax
– Is extensible
– Provides data type support
• DTD:
– Provides ENTITY functionality that is not supported
by XML Schema
– Can be embedded in an XML document
– Is written in SGML

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Schema Versus DTD
U s
A I
An XML Schema defines a set of new names called a vocabulary, and the structure and data
types for elements, types, attributes, and attribute groups. A DTD defines a vocabulary of names

O
for elements and attributes containing either a text string, or a combination of text strings and
child elements.

l &
Applications that process the same XML documents may want to represent their data elements
a
differently. Using XML Namespaces help applications to distinguish between different
n
te r
definitions of the same element name used in different contexts in a single document. XML
Schema seamlessly supports namespaces to distinguish definitions. A DTD does not directly

I n
support namespaces or provide support for “typing” of data. Because a DTD declares names
associated with textual contents, it poses problems when you try to model dynamic content that

l e
comes from strongly typed systems such as databases. XML Schema is ideal for database
c
systems because it provides for data type integrity and the maintenance of bound conditions.

r a
A DTD is written using a syntax that is different from an XML document. Consequently, parsers,

O
tools, and programs dealing with a DTD must implement the specific rules that govern the DTD.
An XML Schema allows models to be written using the XML syntax, which allows the same
programs that read the data to also read the definition of the data.

Oracle 10g: XML Fundamentals 4-37


Converting a DTD to an XML Schema

• XML document:
<employee>
<employee_id>120</employee_id>
<last_name>Weiss</last_name>
</employee>
• DTD:
<!ELEMENT employee (employee_id, last_name)>
<!ELEMENT employee_id (#PCDATA)>
<!ELEMENT last_name (#PCDATA)>
• XML Schema:
<xsd:complexType name="employeeType">
<xsd:sequence>
<xsd:element name="employee_id" type="xsd:int"/>
<xsd:element name="last_name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="employee" type="employeeType"/>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Converting a DTD to an XML Schema
U s
A I
In the example, the XML code in the first example conforms to both the DTD and XML Schema
shown. A validating parser using the DTD can only discern that the elements are strings. By

O
using the XML Schema, a validating parser can discern that employee_id is an integer and
last_name is a string.

l &
The slide presents a simple example that is easily converted by manually typing the XML
a
Schema, provided that you understand the structure represented by the DTD. There are several
n
te r
ways to automate the conversion of a DTD to an XML Schema:
• Locating existing tools on the Web

I n
• Writing your own application with an API that provides the capabilities to convert a DTD
to an XML Schema, such as in the Oracle XML Developer’s Kit (XDK).

l e
Note: The XDK provides API calls to enable the development of an application that converts a
c
r a
DTD to an XML Schema. For an example of this, see the demonstration file called
DTD2Schema.java, which is provided with an Oracle 10g installation in the

O
ORACLE_HOME/xdk/demo/java/schema directory.
Oracle XML SQL Utility (XSU) can generate an XML Schema document from a database table
definition. These tools are discussed in the lesson titled “Using the Oracle 10g XML Developer’s
Kit.”

Oracle 10g: XML Fundamentals 4-38


Summary

In this lesson, you should have learned how to:


• Describe an XML Schema
• Create an XML Schema document with:
– Element declarations
– Attribute declarations
– Custom simpleType and complexType declarations
– Annotations
• Use the XML Schema built-in data types
• Associate an XML Schema with an XML instance
document
• Validate XML documents with an XML Schema,
using JDeveloper and oraxml command-line tool.
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
an XML document using an XML Schema.
A I
In this lesson, you learned about XML Schema creation. You have also learned about validating

An XML Schema can express complex structures using:


O
l &
• The element declarations with data type support
• The attribute declarations with data type support
a
• The simpleType and complexType declarations
n
te r
• The group and attributeGroup declarations
Comparatively, a DTD expresses relatively simple structures with the following typical

I
shortcomings including:
n
• Lack of support for complex structural schemas
l e
• No support for XML namespaces
c
r a
• No provision for data types
• Content models that specify part-of relations, but only specify kind-of relations implicitly

Oor informally
An advantage that XML Schema offers is extensibility: An XML Schema can be refined and
extended by authors adding their own elements, attributes, and constraints. This extensibility
enables XML Schemas to create open content models.

Oracle 10g: XML Fundamentals 4-39


Practice 4: Overview

This practice covers the following topics:


• Writing an XML Schema document
• Creating a simple XML Schema document
manually, and a valid XML instance document
• Modifying the XML Schema document with the
XML Schema editor in JDeveloper
• Registering the XML Schema in JDeveloper
• Modifying and validating the XML document
against the updated and registered XML Schema

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Practice 4: Overview
U s
A I
In this practice, you develop a simple XML Schema documents that are used to validate XML
instance documents. You use JDeveloper to create the XML Schema document and manually

O
add XML Schema components to define the XML Schema structure. The JDeveloper XML
Schema Editor is used to modify the XML Schema document, which is registered in JDeveloper,

l &
and used to validate the XML document instance.

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 4-40
Practice 4
The goal of the practice is to create an XML Schema for the regions.xml and
employees.xml documents. You manually type XML Schema components for the
regions.xml file, and use the visual XML Schema editor in JDeveloper to build the XML
Schema document for employees.xml. The XML Schema documents created are used to
validate their respective XML documents, by first using the oraxml command-line utility via
the Tools > OraXML-schema menu option, and then by registering the XML Schema in
JDeveloper and using the built-in XML Schema-aware features of JDeveloper.
1. Create an XML Schema for the regions.xml document.
a. Add the file E:\labs\lab\regions.xsd to your project. You will notice that it
contains a skeleton XML Schema with the <schema> element.
b. Edit regions.xsd to add the W3C XML Schema namespace to the <schema>
start tag of the root element by using the xsd namespace prefix. Ensure that the
<schema> element start and end tags are qualified with the namespace prefix.
c. Inside the <xsd:schema> element, create a child element named regions, but
do not add the type attribute.
d. Inside the regions element declaration, create an anonymous <complexType>
containing a <sequence> that encloses one element named region with its
maxOccurs attribute set to unbounded.
e. Inside the region element declaration, add an anonymous <complexType> also
containing a <sequence> with two child element declarations: the first one named
region_id with the type attribute value of xsd:int, and the second named
region_name with the type attribute value of xsd:string.

n l y
f. Check the syntax and validate the XML Schema document. Save the XML Schema
document when there are no syntax or validation errors.
O
g. Click the Design tab to view the XML Schema in the visual display mode, and
e
U s
expand the nodes to show the complete XML Schema structure.
2. Associate the regions.xml document with the regions.xsd XML Schema and
validate the XML instance document.

A I
a. Edit regions.xml, and add the XML Namespace prefix xsi set to the URL value

O
http://www.w3.org/2001/XMLSchema-instance. Set the
xsi:noNamespaceSchemaLocation attribute to the region.xsd XML

l &
Schema. Check the XML syntax, correct errors (if any), and save the changes to the
XML document.
n a
te r
b. Validate the region.xml XML document using the oraxml utility configured as
the Tools > OraXML-schema menu option. Explain the validation errors in the

I n
XML document.
c. Correct all the validation errors, ensure that the XML syntax is correct, save the

l e
changes, and validate the XML document again by using the Tools > OraXML-

c
schema.

r a
O
Oracle 10g: XML Fundamentals 4-41
Practice 4 (continued)
3. Using the JDeveloper XML Schema Editor, create an XML Schema for the
employees.xml document.
a. Create a new XML Schema by right-clicking the XMLLabProject node and
clicking New…. Expand the General category and select the XML node, and double-
click the XML Schema item. In the Create XML Schema file dialog box, enter the
File Name: employees.xsd, and click Ok.
Note: JDeveloper creates the XML Schema and displays it in the XML Editor Design
tab window, with a default <schema> and <exampleElement> element.
b. In the <schema> element, replace the URL in the targetNamespace attribute
with the value http://www.hr.com/employees. Be sure to press the
[ENTER] key. Click exampleElement and change its name to employees.
Save the changes.
Note: Remember to press the [ENTER] key after entering text values.
c. In the Structure pane, expand the employees node, its annotation child node, and the
documentation node. Click the A – A Sample Element node, and in the Property
Inspector pane (on the right) click and replace the Data property field value
containing “A Sample Element”with “The employees element.”
d. Create the employee child element in a sequence by right-clicking the employees
element and selecting Insert inside element – employees > sequence. Then, right-
click the sequence object and select Insert inside sequence – element. Change the
new element name to employee.
e. Select the employee element and change the maxOccurs property in the
Property Inspector pane to the unbounded value.
n l y
f. Create four child elements of the employee by using the Component Palette, locate,

e O
and drag the sequence object and drop it on the employee element in the Design
tab. Drag four element objects and drop them on the employee sequence object.
s
Change the name of the four elements starting from the top to employee_id,
U
XML Schema document.
A I
first_name, last_name, and salary, respectively. Save the changes to the

O
g. Right-click the employee_id element and click Set Type, and enter the xsd:int
value in the blank field (this can also be done using the type property in the
&
Property Inspector). Set the type of the first_name and last_name elements to
l
n
the XML Schema document. a
xsd:string, and the salary element to xsd:decimal. Save the changes to

te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 4-42
Practice 4 (continued)
4. Register the employees.xsd XML Schema in JDeveloper, and then associate and
validate the employees.xml document with its XML Schema by using JDeveloper’s
built-in Validate XML menu option.
a. To register the employees.xsd with JDeveloper, select Tools > Preferences and
click the XML Schemas node.
b. Click Add… to display the Add Schema window. In the Add a Schema from the
file system or a URL: field, enter the URL
file:/E:/labs/lab/employees.xsd, or browse for the file
E:\labs\lab\employees.xsd. In the Extension field, enter the value xml.
Click Ok to close the Add Schema window, and confirm that the XSD file has been
added to the User Schemas for XML Editing list. Click Ok to close the Preferences
window.
c. Right-click employees.xml. Can the Validate XML menu be invoked? Why not?
d. Edit employees.xml in the XML Editor and associate it with the
employees.xsd schema document by using the xsi:schemaLocation
attribute in the root element. Modify the default namespace to have the same value as
the targetNamespace defined in the XML Schema document. Ensure that the
employees.xml document has well-formed syntax, and save the changes.
e. Right-click employees.xml, and click Validate XML. What is the result?
f. Confirm the validation results by clicking the Tools > OraXML-schema command-
line tool for XML Schema validation.
If you have time…
5. Create a new employee by using the XML-Schema-aware Editor.
n l y
O
a. Edit employees.xml and add a blank line after the last <employee> element,
just before the </employees> end tag. Type the less than (<) character and wait
e
for code-insight to display the available choices.

U s
b. Double-click the employee option, and enter the greater than (>) character to close

A I
the start tag of the element. If you have enabled the Tools > Preferences > Code
Editor > XML > End Tag Completion option, the </employee> end tag is

O
automatically added; otherwise, enter the </employee> end tag.
c. Create a blank line between the new <employee> element start and end tags. In the

l &
blank line enter the less than (<) character and wait for code-insight to display your

a
choices. What are the choices available?
n
te r
d. From the code-insight choices offered, select employee_id and enclose the value
108 between the start and end tags. Repeat the process and insert the

I n
<first_name> element containing the text Nancy, the <last_name> element
with text Greenberg, and <salary> element with 12000.

l e
e. Right-click in the XML Editor and select Auto Indent XML to tidy the document

c
contents. Right-click and select Validate XML, and save the changes to the

r a
document.

O
Oracle 10g: XML Fundamentals 4-43
n l y
e O
U s
A I
O
l &
na
te r
I n
c le
ra
O
Navigating XML Documents by Using
XPath

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c l e
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe XML Path Language (XPath)
• Construct a location path
• Use XPath expressions and functions
• Test XPath expressions

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
In this lesson, you learn about the basic XML Path Language (XPath) syntax, abbreviated
expressions, and functions. You use an application called TestXPath, which is provided

O
in this course, to test XPath expressions on XML documents in JDeveloper.

l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 5-2
What Is XML Path Language?

XML Path Language (XPath):


• Is primarily used to address the nodes of an XML
document modeled as a tree of nodes
• Is named after its use of a path notation for
navigating through the hierarchical structure of an
XML document
• Uses a compact, non-XML syntax to form
expressions for use in Uniform Resource Identifier
(URI) and XML attribute values
• Fully supports XML Namespaces
• Is designed to be used by XML applications, such
as XSLT and XPointer

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
What Is XPath?
U s
A I
XML Path Language (XPath) is primarily used for addressing parts (nodes) of an XML
document. XPath models an XML document as a tree of nodes, and expresses a navigation

O
path through the hierarchical structure of an XML document. XPath:

document
l &
• Is named after the path notation it uses for navigating through the structure of an XML

a
• Uses a compact, non-XML syntax to form expressions that are used within URI and
n
XML attribute values

te r
• Facilitates the manipulation of string, number, and Boolean values

I n
• Operates on the abstract, logical structure of an XML document called the document
data model, rather than its surface syntax

c l e
In addition to its use for addressing parts of an XML document, XPath fully supports XML

r a
Namespaces and provides a natural expression language subset for pattern matching, which
is extensively used in the W3C XSLT Recommendation, and XPointer.
O
Note: XSLT is XML Stylesheet Language Transformation, the language used to transform
an XML document into another XML document. XPointer is the XML Pointer Language,
used as a fragment identifier for any URI reference that locates a resource with a MIME type
of text/xml or application/xml.
Oracle 10g: XML Fundamentals 5-3
The XPath Model

Document root 1

<departments> 2

<department> num="1" 4

<department_id>

10
3 5
<department_name>
Administration

<department> num="2"

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XPath Model
U s
different types of nodes, as seen by XPath, in an XML document:
A I
XPath models an XML document as a tree of nodes. The graphic in the slide depicts the

O
1. Document root, which is a virtual document root that is the parent of the entire XML
document containing the XML declaration, the root element and its children,

l &
comments, and processing instructions at the beginning and the end of the document
2. Root element (for example, the <departments> element)

n a
3. Element nodes (for example, the <department>, <department_id>, and

te r
<department_name> elements. The root element is also an element node.
4. Attribute nodes (for example, the num="1" node)

I n
5. Text nodes (for example, the nodes containing the text 10 and Administration)
Note: In the XPath model, the document root is not the same as the root element node.
l e
XPath can also address comment nodes, processing instruction nodes, and namespace nodes,
c
r a
which have not been shown in the diagram. XPath defines a way to compute a string value
for each type of node, some of which have names. Because XPath fully supports the XML

O
Namespaces Recommendation, the node name is modeled as a pair known as the expanded
name, which consists of a local part, and a namespace URL, which may be null.
XPath allows various kinds of expressions to be nested with full generality. XPath is a
strongly typed language such that the operands of various expressions, operators, and
functions must conform to designated types. XPath is a case-sensitive expression language.
Oracle 10g: XML Fundamentals 5-4
XPath Expressions

An XPath expression:
• Is the primary construct in XPath
• Is evaluated to yield an object, whose type can be:
– A node set
– A Boolean
– A number
– A string
• Is evaluated within a context, which includes:
– A node called the context node
– The context position and the context size
– A function library among others
• Known as a location path, is commonly used
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XPath Expressions
U s
A I
The XPath language provides several kinds of expressions, which may be constructed from
keywords, symbols, and operands. Generally, an operand forms another kind of expression.

O
An XPath expression is evaluated to yield an object of the following basic types:

• A Boolean: A true or false result


l &
• A node-set: An unordered collection of nodes excluding duplicates

• A number: A floating-point number


n a
te r
• A string: A sequence of Universal Coded Character Set (UCS) characters
XPath expressions are evaluated in a context, which consists of:

I n
• A node, called the context node
• A pair of non-zero positive integers known as the context position and the context size

l e
• A set of variable bindings
c
• A function library

r a
• A set of namespace declarations in scope for the expression

O
The most important and commonly used type of expression is called a location path, which
is discussed on the next page.
Note: Typically, XPath is used by an XSLT Processor, where the context node changes as
the processor navigates through the XML document nodes. An XSLT Processor is guided by
template instructions that contain XPath expressions used to match nodes in the tree.
Oracle 10g: XML Fundamentals 5-5
The Location Path Expression

The location path expression is one of the following:


/departments/department/department_id
• An absolute location path
• A relative location path:
– Is made up of one or more location steps that
specify navigation directions to nodes in an XML
document
– Is relative to the starting point called the context
node
<?xml version="1.0"?>
<departments>
<department num="1">
<department_id>10</department_id>
<department_name>Administration</department_name>
</department>
</departments>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The Location Path Expression
U s
A I
The location path is one of the most important XPath expressions that gives an application
navigation directions in an XML document to locate a set of nodes. A location path is one
of the following:
O
• An absolute location path, starting with a slash (/) character followed by a relative
location path
l &
• A relative location path, made up of a sequence of one or more location steps

n a
separated by a slash (/) character. Location steps are composed from left to right

te r
selecting or navigating to a set of nodes, relative to the context node
The location path expression shown in the slide is an absolute path that uses the document

I n
root as the context node. An absolute location path always starts with a slash (/) character,
followed by a relative location path comprised of the following location steps:
l e
1. Go to the <departments> root element relative to document root.
c
2. Then, go to the first child <department> element of the <departments> node.

r a
3. Finally, go to the <department_id> child element of the <department> node.

O
If the example XML document included more than one <department> element and child
<department_id> elements, then the XPath expression will match more than one, or a
set of <department_id> nodes. The result is the entire element from the start to the end
tags, and the data between them. In the result for the example as highlighted in slide, is:
<department_id>10</department_id>

Oracle 10g: XML Fundamentals 5-6


Results of Location Path Expressions

A location path evaluates to a result that is:


• Empty <?xml version="1.0"?>
<departments>
• A single node <department num="1">
...
• A set of nodes </department>
Examples: </departments>
• The absolute root location path
/
• Child element location steps (examples show
location paths relative to the document root)
Relative: departments Absolute: /departments
Relative: departments/department
Absolute: /departments/department

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Results of Location Path Expressions
U s
• Empty
A I
Evaluation of location path expression produces a result that is one of the following:

• A single node
O
• A set of nodes (more than one node)

l &
The slide shows a skeleton XML document of departments and various location path

n a
expressions and their resulting nodes. The relative location paths in the examples assume

te r
that the context node is the document root:
• The first example is an absolute location path expression selecting the document root,

I n
resulting in the entire document matching the expression.

c l e
• The second example shows a relative and absolute location path selecting the root
element node as its result.

r a
• The third example provides a relative and absolute location path selecting the set of
department child elements of the root element.
O
In the second example, departments is called a location step. In the last example,
departments is the first location step, followed by a slash, and then the department
location step, forming a compound XPath expression.

Oracle 10g: XML Fundamentals 5-7


Location Steps in XPath Expressions

Each location step:


• Forms the address of a specific node, or set of
nodes, to be selected
• Comprises three parts:
– An axis
– A node test
– Zero or more predicates
axis::node-test[predicates]
• Has an unabbreviated and abbreviated form
• Acts like a filter for a selected node or node-set
• Is separated by a forward slash (/) character to
form a compound location path expression
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Location Steps in XPath Expressions
U s
A I
As identified, a location path is an important XPath expression that comprises one or more
location steps relative to the context node. Each location step is separated by a slash (/)
character to form a compound location path that:
O
• Specifies the address or location of a node or set of nodes (node-set)
&
• Evaluates to a result that is empty, a single node, or set of nodes
l
n a
For example: department/department_name addresses all the
department_name child elements of the department element that is a child of the

te r
context node. Each location step consists of and is defined by three parts:
• An axis, specifying the relationship between the selected nodes and the context node

I n
• A node test, specifying the node type of the selected nodes
• Zero or more predicates, or conditions that use arbitrary expressions to filter the set of
l e
selected nodes
c
r a
The axis produces a list of nodes that is then filtered using the node test (which is limited to
filtering based on node type and node name). The predicates are then applied, if present, to

O
further reduce the node-set.
The location step can be specified in unabbreviated or abbreviated format. The
unabbreviated form is seldom used because it is quite verbose using the full axis names
followed by a double colon and then the node test. The axes names are discussed in the
section titled “XPath Axes.”
Oracle 10g: XML Fundamentals 5-8
XPath Axes

ancestor

parent/ancestor

preceding-sibling

self Context node

child/descendant

descendant

attribute
namespace

following-sibling

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XPath Axes
U s
• child for the children of the context node
A I
Document tree node axis names (in lowercase) relative to a context node in the diagram are:

• descendant for descendants of the context node


O
parent for the parent of the context node. The document root does not have a parent.
&



a l
ancestor for ancestors of the context node
following-sibling for all the following siblings of the context node

r n
preceding-sibling for all the preceding siblings of the context node

te
• following for all nodes appearing after the context node in document order
preceding for all nodes that are before the context node in document order


I n
attribute for the attributes of the context node (empty for non-element nodes)


c e
namespace for namespace nodes of the context node (empty for non-element nodes)
l
self axis for the context node itself

r a
descendant-or-self for the context node and its descendants
ancestor-or-self axis for the context node and its ancestors (and the root node)
O

Note: The following-sibling and preceding-sibling axes are empty for


attribute or namespace context nodes. The descendant, preceding, and following
excludes attribute or namespace nodes, following excludes descendants, and
preceding excludes ancestors.
Oracle 10g: XML Fundamentals 5-9
XPath Node Test Types

An XPath node test type can be:


• A node-name, such as:
– The element name
– The attribute name, if prefixed with an @ symbol
– A qualified name, with namespace prefix
• An asterisk (*)
• The text() type
• The processing-instruction() type
• The comment() type
• The node() type
• Separated by the vertical bar (|) character to form
multiple matches
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XPath Node Test Types
U s
A I
The node type specified as the node test for a location step can be:
• A node-name representing either a qualified or an unqualified element name. If it is

O
prefixed with an @ symbol, then the node-name represents an attribute name.

• The text() type to select text nodes


l &
• An asterisk (*) to match all element or attribute node names

a
• The processing-instruction() type for processing instruction nodes
n
te r
• The comment() type for obtaining the comment nodes
• The node() type to match any of the above nodes

I n
Using the vertical bar (|) character as a separator, node tests can be combined to create a

c l e
rule matching multiple node types. For example, using /text()|comment() matches
either the text or comment nodes of the root element.

r a
Note: If nodes in the XML document declares an XML namespace with a prefix, the node

O
name must be qualified by the namespace prefix in the XPath expression.

Oracle 10g: XML Fundamentals 5-10


Unabbreviated and Abbreviated
Expressions

Abbreviated Unabbreviated (with axis name)


departments child::departments
employee/salary child::employee/child::salary
* child::*
. self::node()
.. parent::node()
../salary parent::node()/child::salary
@id attribute::id
department/@num child::department/attribute::num
text() child::text()
//salary /descendant-or-
self::node()/child::salary

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Unabbreviated and Abbreviated Expressions
U s
A I
Every location path can be expressed using an abbreviated syntax, rather than a verbose
unabbreviated syntax. The following unabbreviated XPath expressions are seen in the slide:

O
child::departments selects the department child elements of the context node.
child::employee/child::salary selects the salary child elements of
&


a l
employee child elements of the context node.
child::* selects all element children of the context node.

r n
self::node() selects the context node.

te
• parent::node() selects the parent node of the context node.

I n
parent::node()/child::salary selects the salary child element from the
parent of the context node.


c l e
attribute::id selects the id attribute of the context node.
child::department/attribute::num selects the num attribute from the

r a
department child elements of the context node.
child::text() selects all text node children of the context node.
O

• /descendant-or-self::node()/child::salary selects all salary
elements of the context node or its descendents.
Note: child::node() selects all the children of the context node, whatever their node
type. Using attribute::* will select all the attributes of the context node.
Oracle 10g: XML Fundamentals 5-11
Unabbreviated and Abbreviated Expressions (continued)
Using abbreviated syntax:
• name selects the name element children of the context node
• / selects the document root which is always the parent of the document element
• text() selects all text node children of the context node
• comment() selects all the comments node children of the context node
• node() select all the child node types of the context node
• @name selects the name attribute of the context node
• @* selects all the attributes of the context node
• . selects the context node
• .. selects the parent of the context node
• ../@lang selects the lang attribute of the parent of the context node
Note: The most important abbreviation allows the child axis, and the double colon (::) to
be omitted from a location step. In effect, child is the default axis.
Other Common XPath Expressions
• /employee matches the employee element at the document root.
• department/department_name matches the department_name element as
a direct child of the department element.
• departments//department_id matches the department_id element as a
descendant of the departments element, at any level.
• .//employee matches the employee element as descendants of the current node.
• department_name | department_id matches either department_name
or department_id elements as children of the context node.
n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 5-12
Abbreviated XPath Expression: Examples

//last_name
Result: <last_name>King</last_name>
<last_name>Kochhar</last_name>
employees/employee/name/first_name/text()
Result: Steven
Neena
employees//salary
Result: <salary>24000</salary>
<salary>18000</salary>
employees/employee/@employee_id
Result: employee_id="100"
employee_id="101"
comment()
Result: <!-- Employee data -->
Note: The document root is the context node.
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Abbreviated XPath Expression: Examples
U s
<?xml version="1.0"?>
<!-- Employee data --> A I
The examples in the slide are applied to the following XML document:

<employees>
O
<employee employee_id="100">
<name>
l &
n a
<first_name>Steven</first_name>
<last_name>King</last_name>
</name>

te r
<salary>24000</salary>

I n
</employee>
<employee employee_id="101">

c l e
<name>
<first_name>Neena</first_name>

r a <last_name>Kochhar</last_name>
</name>

O <salary>18000</salary>
</employee>
</employees>
Note: The context node is the document root, <first_name> and <last_name> are
children of <name>, and the comment is a child of the document root.

Oracle 10g: XML Fundamentals 5-13


XPath Predicates

An XPath predicate:
• Is a Boolean expression in square brackets
evaluated for each node in the node-set
//department[department_name="Administration"]
• With a numeric result is converted to a Boolean
using the position() function
/departments/department[2]
/departments/department[position()=2]

• May be provided with each location step


//department[@num<3]/department_id[.="10"]
• May be combined with logical operators
//department[@num>2 and @num<=4]/department_name

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XPath Predicates
U s
A I
A predicate in an XPath expression is a condition contained in square brackets appearing
after the node test of a location step. The predicate is evaluated as a Boolean expression for

O
each node in a node-set. If the condition is true, then the node is included; otherwise, the
node is excluded from the results. The predicates like query expressions filter the results.

l &
• The first example returns descendant <department> elements that contain a
<department_name> element whose text node is Administration.
a
• The second example specifies a numeric value, which can computed. Numeric results
n
te r
are converted to a Boolean expression by using an equality comparison of the value to
the return value of the position() node-set function. The position() function

I n
determines the proximity position of a member node in a node-set. The proximity
position is a numbered position of the node in the sequence it appears in a node-set.

c l e
Proximity position numbers start at 1.
• The third example shows that each location step can contain a predicate. The example

r a
produces the <department_id> element containing the text string 10 if it is in a
<department> element whose num attribute value is less than 3.

O
Note: The last example uses the and logical operator (in lowercase) to combine predicate
expressions, which can be written as using an implied and operation, for example:
//department[@num>2][@num<=4]/department_name
You can combine predicates with an or logical operator (in lowercase), for example:
//department[department_id="10" or (@num>1 and @num<4)]

Oracle 10g: XML Fundamentals 5-14


XPath Predicates (continued)
Each XPath expression in the slide is applied to the following XML document:
<?xml version='1.0' encoding='windows-1252'?>
<departments>
<department num="1">
<department_id>10</department_id>
<department_name>Administration</department_name>
<manager_id>200</manager_id>
<location_id>1700</location_id>
</department>
<department num="2">
<department_id>20</department_id>
<department_name>Marketing</department_name>
<manager_id>201</manager_id>
<location_id>1800</location_id>
</department>
<department num="3">
<department_id>30</department_id>
<department_name>Purchasing</department_name>
<manager_id>114</manager_id>
<location_id>1700</location_id>
</department>
<department num="4">
<department_id>40</department_id>
<department_name>Human Resources</department_name>
<manager_id>203</manager_id>
<location_id>2400</location_id> n l y
</department>
</departments>
e O
U s
The node-set result for each XPath expressions are shown in the following examples:

<department num="1">
<department_id>10</department_id> A I
• Expression: //department[department_name="Administration"]

O
<department_name>Administration</department_name>

l &
<manager_id>200</manager_id>
<location_id>1700</location_id>
</department>
n a

r
Expression: /departments/department[2]

te
<department num="2">

I n
<department_id>20</department_id>
<department_name>Marketing</department_name>

c l e
<manager_id>201</manager_id>
<location_id>1800</location_id>

• r a </department>
Expression: //department[@num<3]/department_id[.="10"]

• O <department_id>10</department_id>
Expression: //department[@num>2 and @num<=4]/department_name
<department_name>Purchasing</department_name>
<department_name>Human Resources</department_name>

Oracle 10g: XML Fundamentals 5-15


Operators in XPath Expressions

• Comparison operators:
– <=, <, >=, >
– =, !=
• Logical operators:
– not, and, or
• Mathematical operators:
– *
– div, mod
– +, -
• Literal strings are quoted with single or double
quotes.
Note: Operators are listed in the order of precedence.
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Operators in XPath Expressions
U s
Comparison operators include:
• Less than or equal to (<=), or less than (<) A I
The slide lists the operators that can be used in predicates and XPath expressions.

• Greater than or equal to (>=), or greater than (>) O


• Equal to (=), and not equal to (!=)
l &
• A combination of more than one predicate by using a lowercase and, lowercase or, or
both
n a
Mathematical operations include:
te r
• The asterisk (*) for multiplication

I n
• The lowercase div for division
• The lowercase mod for the remainder of a division
l e
• The plus sign (+) for addition
c
• The minus sign (-) for subtraction

r a
Note: When using XPath in XSLT stylesheet documents, the < character must be entered

O
using its entity representation, that is, using &lt;. In addition, literal strings in expressions,
which are usually delimited by single or double quotation marks, must use entity names to
enter quotes, that is, either the &quot; or &apos; as appropriate.
Note: Predicates can be combined as follows: [predicate1][predicate2]. This is
the same as using an and operation, that is: [predicate1 and predicate2].
Oracle 10g: XML Fundamentals 5-16
XPath Functions

XPath functions:
• Are used in predicates or expressions
function-name(arguments,...)
• Have a name followed by parenthesis, and zero or
more arguments. For example:
position()
• May return one of the following four types:
– Boolean
– Number
– Node-set
– String

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XPath Functions
U s
result types:
A I
XPath functions are used in predicate and expression to yield one of the following four

O
• A Boolean function can operate on Boolean expressions to return a true or false
result.

l &
• A number function is used to operate on numbers, and return floating-point values.
a
• A node-set function operates on a set of node selected by a location path expression,
n
te r
and return a result, usually a numeric value.
• A string function operates on Unicode strings values.

I n
The position() function is an example of a node-set function. Functions in each of these

c l e
categories are discussed on the next few pages.

r a
O
Oracle 10g: XML Fundamentals 5-17
Boolean Functions

Function Description
boolean(o) Converts to a Boolean
not(b) Returns true if its argument is false and vice versa
true() Returns true
false() Returns false
Example: <department>'s without a <manager_id>
/departments/department[boolean(not(manager_id))]
Partial Results:
<department num="12">
<department_id>120</department_id>
<department_name>Treasury</department_name>
<location_id>1700</location_id>
</department>
...
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Boolean Functions
U s
A I
Boolean functions manipulate expressions to return either a true or false value. The
boolean() function converts its argument to a Boolean value and returns a result, where:

O
• Non-zero numbers are converted to a true, and a 0 value returns a false.
• A node-set is false if empty; otherwise, it is true.

l &
• Zero length strings return false; otherwise, a true value is returned. For example:
- boolean('false') returns true.

n
- boolean() returns false. a
te r
The not() function returns the reverse of its Boolean argument. That is, it returns true

I n
when its argument is false, and false if its argument is true. For example:
not(@salary>10000) returns true, if the salary is less than 10000.

l e
The true() function always returns true.
c
r a
The false() function always returns false.
The example in the slide locates <department> elements that do not contain any
O
<manager_id> child elements. Although the boolean() function is not required in the
example, it shows that XPath functions may be nested within the predicate expression.
Note: The example in the slide uses the data from the rows of the DEPARTMENTS table in
the XML format as seen in the partial results.

Oracle 10g: XML Fundamentals 5-18


Number Functions

Function Description
number(o) Converts the argument to a number
sum(ns) Returns the sum for each node in a node-set
ceiling(n) Returns the smallest integer that is greater than
a given number
floor(n) Returns the largest integer which is less than a
given number
round(n) Returns the closest integer to a number

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Number Functions
U s
following:
A I
The number functions can be used to manipulate numeric data. The number functions are the

O
• The number() function converts its argument to a number—for example,

l &
number('6.75') returns the numeric value 6.75.
If the argument is a Boolean expression, then a true is converted to a value of 1, and
a
false returns a 0 value. If the argument is not convertible to a number, then this
n
te r
function returns NaN (not a number).
• The sum() function accepts a node set as an argument and returns the result of the

I n
sum of the nodes. Each node is first converted to a string value and then to a number
before being summed up.
l e
• The ceiling() function returns the smallest integer that is greater than its
c
r a
argument—for example, ceiling(2.35) returns a value of 3.
• The floor() function returns the largest integer that is less than its argument—for

Oexample, floor(2.35) returns a value of 2.


• The round() function returns the number rounded to its nearest integer—for
example, round(2.35) returns the value 2, and round(2.65) returns the value 3.

Oracle 10g: XML Fundamentals 5-19


Node-Set Functions

Function Description
last() Returns the context size
position() Returns the context position
id(o) Returns elements by their unique ID
count(ns) Returns the number of nodes in a node-set
local-name(ns) Returns the local node name (unqualified)
Examples:
//department[position()=1]
Results: <department num="1">
<department_id>10</department_id>
...
</department>
//department[last()]/department_name
Results: <department_name>Payroll</department_name>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Node-Set Functions
U s
A I
The node-set functions that manipulate and return information about a set of nodes include:
• The last() function that returns the number of nodes in the context node-set
• The position() function that returns the context position. For example,
O
//employee[position()=2] returns the second employee descendant node.

l &
• The id() function that accepts a string containing one or more space-separated ID
values as the argument. It returns a node-set containing all nodes in the document
a
having those ID values, which are declared as an ID attribute type in the DTD, that is,
n
te r
the attribute is not named but is declared as a unique ID attribute type.
• The count() function is similar to last(). It gives a count of the number of nodes

I n
in its node-set argument. For example, count(//employee) gives you the number
of employee elements in the document.

l e
• The local-name() function returns the local name, without a namespace prefix, of

c
the first node in the node-set argument. If no argument is provided, the name of the

r a
context node is returned.
The first example in the slide locates the first department element by its position in the node-
O
set. This is equivalent to //department[1]. The second example locates the last
department in the node-set, which can be written as:
//department[count(//department)]/department_name
Note: Node-set functions not listed in the slide are: namespace-uri() that returns the
namespace URI string of a node, and name() that returns the qualified name of a node.
Oracle 10g: XML Fundamentals 5-20
String Functions

Function Description
string(o) Converts an object to a string
concat(s,s,...) Concatenates its arguments
substring(s,n,n) Returns a substring of a string argument
from a start position to a length
contains(s,s) Accepts two arguments and returns true
if the first argument contains the second
starts-with(s,s) Takes two arguments and returns true if
the first argument starts with the second;
otherwise, it returns false
string-length(s) Returns the length of a string

Example:
//department[starts-with(department_name,'A')]

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
String Functions
U s
The string() function converts any type of data to a string.

A I
The concat() function returns the concatenation of its arguments. For example,

O
concat('This is ','cool') returns the string 'This is cool'.
The substring() function takes three arguments: the string to evaluate, a start position,

l &
and a length. If the length is omitted then the return string contains all the characters from

n a
the start position to the end of the evaluated string. For example:
substring('employee',1,3) returns the string 'emp'.

te r
substring('Administration',6) returns 'istration'.
The contains() function searches for the presence of the second argument within the

I n
first. If it is present, it returns true; otherwise, it returns false. For example:
contains('Steve King','ing') is true
e

c l
contains('Neena Kocchar','charm') is false

r a
The starts-with() function returns true if the first argument starts with the second;
otherwise, it returns false. For example: starts-with ('Administration',

O
'Adm') returns true
The string-length() function returns the length of its argument as an integer value.
For example: string-length('King') returns a value of 4.
The example in the slide returns <department> elements with <department_name>
child nodes that start with an uppercase A.
Oracle 10g: XML Fundamentals 5-21
XSLT and XPath

XSLT:
• Transforms XML into plain text, HTML, or XML
• Specifies transformation rules in elements with
attributes that use XPath expressions
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//department_name">
<html>
<body>
<p><xsl:value-of select="."/></p>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="*/text()"/>
</xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XSLT and XPath
U s
A I
An XML Stylesheet Language (XSL) document is an XML document with elements that
define transformation rules. The slide shows sample XSL document elements, such as:
• The <xsl:template> element with a match attribute containing an XPath
O
expression defining the set of nodes to which the template rule applies.

l &
• The <xsl:value-of> element with the select attribute containing an XPath
expression. The <xsl:value-of> element outputs the text value of the specified
a
node, relative to the context node matching its template XPath expression.
n
te r
The <xsl:template> element informs the XSLT Processor how to locate specific
element nodes in the input document, and provides the rules to create the output data as the

I n
contents specified between the start and end tags of the <xsl:template> element. In the
example, you search for department_name elements, and use the current node (.) to

l e
output the value of the department_name.

c
Note: The XSLT Specification states that XSLT processors must provide a default template

r a
rule causing text nodes to be output, if no matching template rules exist. Suppress the output
of unprocessed text nodes by including, at the end of the XSLT stylesheet, a template rule
O
matching all text nodes that does not output data. For example, as shown in the slide, use:
<xsl:template match="*/text()"/>
Note: The example in the slide provides a context for where XPath expressions can be used.
XSLT is covered in detail in the lesson titled “Transforming XML by Using XSL
Transformation.”
Oracle 10g: XML Fundamentals 5-22
Testing XPath Expressions

To view the results of XPath expressions, use:


• An XSL stylesheet to transform an XML document
that can be viewed in an XML-enabled browser

• The TestXPath tool provided for this course, via


the Tools > TestXPath menu

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Testing of XPath Expressions
U s
A I
The slide shows the output of applying the stylesheet on the previous page to the following
XML document. It retrieves the value of the <department_name> element.
<?xml version = "1.0"?>
<?xml-stylesheet type="text/xsl" O
l &
href="code_05_22_s.xsl"?>
<departments>

n a
r
<department num="1">

te
<department_id>10</department_id>
<department_name>Administration</department_name>

I n
<manager_id>200</manager_id>

c l e
<location_id>1700</location_id>
</department>

r a <department num="2">
<department_id>20</department_id>

O <department_name>Marketing</department_name>
<manager_id>201</manager_id>
<location_id>1800</location_id>
</department>
</departments>
Oracle 10g: XML Fundamentals 5-23
Using the TestXPath Tool

2
5

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the TestXPath Tool
U s
A I
The TestXPath tool is provided in this course for testing XPath expressions on XML
documents. TestXPath is a Java application that uses the Oracle XML Parser DOM API

O
to apply XPath expressions to an XML document and display the resulting node-set. To start
TestXPath as configured in JDeveloper, and test XPath expressions:

l &
1. Right-click the XML document in Navigator, or XML Editor
2. Select TestXPath from the menu. Alternatively, click Tools > TestXPath.

n a
3. Enter an XPath expression in the TestXPath input dialog box.

te r
4. Click Test to view the output results in the TestXPath tab in the Log window.
Note: Expressions tested in TestXPath use the document root as the context node.

I n
5. After viewing the output results in the Log window, test XPath expressions by
choosing an entry from the history in the pop-up list, edit an existing entry, or enter a

l e
new XPath expression. Click Exit to terminate the application.
c
Note: If the XML document declares a default namespace, then TestXPath requires

r a
elements in the XPath expression to be qualified with the def:prefix. Changes to the XML

O
document must be saved before you run the TestXPath tool. At the command line, use:
set CLASSPATH=E:\JDeveloper\lib\xmlparserv2.jar;E:\labs\classes
java TestXPath filename.xml
Note: The code for TestXPath was obtained from a sample provided by Steve Muench
(Oracle Corporation) from his book titled Building Oracle XML Applications (O’Reilly).
Oracle 10g: XML Fundamentals 5-24
Summary

In this lesson, you should have learned how to:


• Describe XPath and its document model
• Construct a location path with location steps
• Use axes, node-tests, and predicates in XPath
expressions
• Use XPath functions in predicates
• Test XPath expressions by using XSLT or
TestXPath

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
or set of nodes (node-set) in an XML document.
A I
In this lesson, you learnt the XPath syntax used to form an expression that addresses a node

O
The XPath document model comprises an XML document tree beginning at the virtual

• The XML header


l &
document root that contains everything in an XML document including:

• The root element node and its children


n a
• Comments
• Processing instructions
te r
I n
You can construct XPath expressions to navigate to any node in the XML document tree.
The most important and common XPath expression is called a location path. The location
l e
path is made up of one or more location steps separated by a forward slash (/) character.
c
Each location step, which can be expressed in an abbreviated or unabbreviated format, has

r a
three parts:

O
• The axis that defines the direction of navigation relative to a context node
• The node-test that defines the set of nodes of interest
• Zero or more predicates, which filter the set of nodes processed
XPath is meaningful in processing contexts such as XSLT and XPointer. The TestXPath
tool is provided to test and learn about XPath expressions in the lesson practices.
Oracle 10g: XML Fundamentals 5-25
Practice 5: Overview

This practice covers the following topics:


• Testing XPath expressions by using TestXPath
• Specifying XPath expressions in XSLT stylesheet
<xsl:template> elements to output region
information in HTML format

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Practice 5: Overview
U s
A I
In this practice, you test your understanding of writing XPath expressions by using the
TestXPath tool, and specifying appropriate XPath expressions in XSLT stylesheet

O
<xsl:template> elements to output region data in HTML format.

l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 5-26
Practice 5
The goal of this practice is to gain experience in writing XPath expressions by testing them
using the TestXPath tool, and writing the XPath expressions in the XSLT stylesheet
<xsl:template> elements for outputting employee data in HTML format.
1. In the XMLLabsProject, edit the root element in employees.xml to remove all
the xmlns, and xsi:schemaLocation attributes. Save the changes to your
document.
2. Right-click employees.xml and select TestXPath path tool to write XPath
expressions for the following scenarios:
Note: There may be more than one way to write the XPath expression.
a. Locate all employee elements.
b. Locate the first employee element.
c. Locate the last employee element.
d. Locate the last two employee elements.
e. Find all the last name elements.
f. Obtain the text for the first name of employees.
g. Locate employee elements containing a salary less than 5000.
h. List the salary elements greater than 5000.
i. Find employees with a first or last name beginning with the letter A.
j. Obtain the comment for the root element.
3. Test the effects of changing an XPath expression in the match attribute of an
<xsl:template> element in an XSL stylesheet document.
a. In the XMLLabsProject, add the E:\labs\lab\regions.xsl file.
n l y
Examine the contents and note the first <xsl:template> element for the root
O
element /regions outputs HTML tags for a document with a HTML table.
e
The <xsl:apply-templates/> element invokes the second

U s
<xsl:template> matching region elements and outputs their

A I
<region_id> and <region_name> element values as a table row.
b. Right-click the regions.xml document, and select Internet Explorer to

O
display the document in the browser, showing the document tree.
Note: Do not close the browser window because it is refreshed in the subsequent
steps.
l &
a
c. Edit regions.xml to include a declaration to use the regions.xsl
n
te r
stylesheet by inserting the following line just above the start tag of the
<regions> root element:

I n
<?xml-stylesheet type="text/xsl" href="regions.xsl"?>
Save the changes to regions.xml.

l e
d. Refresh the browser window to see the results of the XSL transformation.
c
e. Edit the regions.xsl stylesheet and modify the XPath expression in the

r a
match attribute, of the second <xsl:template> element, to include a

O predicate to address the last two region elements. Save the changes to the XSL
stylesheet, and refresh the browser to confirm the results.

Oracle 10g: XML Fundamentals 5-27


Practice 5 (continued)
f. Modify the XPath expression in the match attribute, of the second
<xsl:template> element, to use a predicate that returns the first two
region elements. Save the changes to the XSL stylesheet, and refresh the
browser to confirm the results. Did you encounter any problems? If so, what
happened? Close the browser when you have finished.
If you have time:
4. Test XPath expressions with the departments.xml document that declares and
uses a namespace prefix called dept for some of its elements.
a. First, edit departments.xml and place the entity reference &deptData; in
a comment and replace it with all the <department> element data in the
external file it references, that is, all the data in
E:\labs\lab\newdepts.txt. Save the changes to department.xml
and start TestXPath.
b. Locate department elements in the http://www.hr.com/departments
namespace. Which department elements do not match the expression and why
not?
Hint: Use the namespace prefix to qualify element names.
c. Locate department elements without a namespace.
d. Find all department nodes whether qualified by a namespace or not.
Hint: Use the node() function to locate any node, and local-node()
function to compare the node name with the string 'department'.
e. Locate all department elements without a <manager_id> element.
n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 5-28
Transforming XML by Using XSL
Transformations

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe XSL and XSL Transformations (XSLT)
• Transform an XML document by using XSLT
• Use key XSLT elements
• Create, apply, and call templates
• Sort and filter an XML document
• Use parameters with templates
• Use the oraxsl command-line utility

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
syntax for transforming XML documents.
A I
In this lesson, you learn about Extensible Stylesheet Language (XSL), and its rules and

References:
O
• http://www.topxml.com/xsl/XSLTRef.asp
l &
• Beginning XML, second edition, Hunter et al, Wrox Publications

n
• XSLT, Doug Tidwell, O’Reilly Press a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 6-2
What Is XSL?

Extensible Stylesheet Language (XSL) is made up of


two parts:
• XSL Transformations (XSLT)
• XSL Formatting Objects (XSL-FO)

XSL

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
What Is XSL?
U s
A I
XML documents have structure and, unlike HTML, do not provide formatting or display
instructions. Extensible Stylesheet Language (XSL) adds the capability of transforming an

O
XML document into another document containing XML with a different structure, or an
HTML document with formatting tags.
XSL has the following two parts:
l &
n a
• XSL Transformations (XSLT) is an XML application that processes rules contained in

document.
te r
an XSLT stylesheet. The rules in an XSLT stylesheet can be applied to any XML

I n
• The XSL Formatting Objects (XSL-FO) is an XML application used for describing the
precise layout of text on a page. XSLT is used to generate XSL-FO elements that are
l e
output to another XML document. Additional processing is needed to create the final
c
r a
output form such as a portable document format (PDF) document.
This lesson focuses on XSLT.
O
The graphic in the slide depicts an XML document and an XSLT stylesheet document being
processed by an XSL processor. The XSL processor is an XML application that applies the
transformation rules to the XML document as specified in the XSL document and produces
a new document as the result.
Oracle 10g: XML Fundamentals 6-3
XSL Transformations

XSL
Input XML processor Output XML
document document

XSL
stylesheet

<?xml version="1.0"?>
<xsl:stylesheet ...> Output
<xsl:template match="XPath"/> data
Matching <!-- output information -->
</xsl:template>
rule </xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XSL Transformations
U s
A I
XSL Transformations (XSLT) is an XML application, or XSL Processor, that processes
rules specifying how to transform one XML document into another XML document. The

O
rules are contained in an XSLT document called an XSLT stylesheet, which itself is an
XML document and must be well-formed.

l &
The slide shows that an XSLT stylesheet contains one or more template rules; each template
rule has two parts:
n a
<xsl:template> element
te r
• A match pattern, specified as an XPath expression in an attribute of an

I n
• Template data, appearing between the start and end tags of the <xsl:template>

c l e
element, that contains the output information. The template data typically contains
XML/HTML elements mixed with the XSLT rules.

r a
The XSL processor compares the elements in the input XML document with the template

O
rule pattern in the XSLT stylesheet, and writes the template data for matching rules to the
output tree, typically, another XML document. Essentially, the transformation process
operates on the tree data structure of a source (input) XML document and produces a tree of
nodes as its output.
Note: XSL-FO elements are output elements found inside the <xsl:template> rules.
Oracle 10g: XML Fundamentals 6-4
The XSLT Stylesheet

An XSLT stylesheet is an XML document containing:


• A <xsl:stylesheet> root element declaring:
– The xsl namespace prefix
– The http://www.w3.org/1999/XSL/Transform
mandatory namespace URI
• One or more <xsl:template> elements and other
XSL elements defining transformation rules
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
...
<xsl:template match="/"> ... </xsl:template>
<xsl:template match="..."> ... </xsl:template>
<xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XSLT Stylesheet
U s
A I
An XSLT stylesheet is an XML document that uses elements from the XSLT vocabulary to
describe transformation rules. The document element of every XSLT stylesheet is the

O
<xsl:stylesheet> element, whose content is a set of one or more XSL elements

l &
defining template rules describing the transformation to be performed.
Note: <xsl:transform> is a synonym for <xsl:stylesheet>.

n a
The <xsl:stylesheet> element declares the mandatory namespace attribute

te r
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" used to qualify the
elements in an XSLT stylesheet. If you do not provide this exact namespace prefix and URI,
I n
the XSLT Processor simply ignores the rules in <xsl:template>, <xsl:for-each>,

l e
<xsl:value-of>, and other XSL elements that are qualified with the xsl prefix.

c
Therefore, it does not recognize them as XSLT instructions.

r a
Each stylesheet rule, called a template, contains a match pattern specified as an XPath

O
expression that is compared against the nodes in the source XML document. An XSL
template rule is represented by an <xsl:template> element with a match attribute that
is assigned a "pattern" string containing an XPath expression.

Oracle 10g: XML Fundamentals 6-5


XSLT Stylesheet: Example

<?xml version="1.0"?> 1
<xsl:stylesheet version ="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 2
<xsl:template match="/">
<html> 3
<body>
<table border="1">
<tr><th>Id</th><th>Name</th><th>Salary</th></tr>
<xsl:apply-templates/>
</table> 5
</body> 4
</html>
</xsl:template>
<xsl:template match="employee">
<tr>
<td><xsl:value-of select="employee_id"/></td>
<td><xsl:value-of select="last_name"/></td>
<td><xsl:value-of select="salary"/></td>
</tr> 6
</xsl:template>
</xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XSLT Stylesheet: Example
U s
A I
The XSLT document in the example, called a stylesheet, shows the following components:
1. The standard XML document declaration, because the stylesheet is an XML document

O
2. Mandatory XML Namespace declaration using the xsl namespace prefix, and the
URI http://www.w3.org/1999/XSL/Transform namespace

l &
3. The <xsl:template> rule matching the root of the source XML document

a
4. The template data containing HTML tags to be written to the output document
n
te r
5. The <xsl:apply-templates> element instructing the XSLT Processor to apply
template rules, if any, for child elements of root in the source document. The
<xsl:apply-templates> element is replaced by any output generated for
I n
matching child element template rules.

c l e
6. The <xsl:template> rule for matching <employee> elements in the source
document, with template data containing HTML table row (<tr>...</tr>) tags

r a
enclosing three table data (<td>...</td>) tag pairs. Each table data tag pair
encloses an <xsl:value-of select="..."/> rule that inserts the value of the
Osource document element selected by the XPath expression, which is typically the
name of the source document element.
The XML document that uses this XSLT stylesheet is shown in the page titled “Viewing the
Transformed Document.”
Oracle 10g: XML Fundamentals 6-6
Using an XSLT Stylesheet with an XML
Document

An XML document uses an <?xml-stylesheet...?>


processing instruction:
• After the XML declaration and before the root
element of the XML document.
• Containing two pseudo-attributes:
– The type value is the MIME type for the stylesheet
– The href value is the URL of the source XSLT
stylesheet document
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="emp.xsl"?>
<employees>
...
</employees>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using an XSLT Stylesheet with an XML Document
U s
A I
An XSLT stylesheet is applied to an XML document by adding the xml-stylesheet
processing instruction in the XML document prologue that is before the document root

O
element. The xml-stylesheet processing instruction provides two pseudoattributes:

l &
• The type value is the MIME media type for the type of stylesheet. For XSL
stylesheets, the type value must either be application/xml or text/xml.
a
However, the XSL processor in Internet Explorer does not recognize
n
te r
application/xml as the type value but accepts a value of text/xsl, as shown
in the example in the slide. A MIME media type value of text/css is applicable to

I n
a Cascading Style Sheet (CSS).
• The href value is a URI string referencing the name of the stylesheet document.

c l e
The xml-stylesheet processing instruction is required for a browser to invoke its

r a
XSLT Processor to apply the stylesheet to the XML document tree.
Note: The type pseudoattribute value of text/xsl, which is a fabrication of Microsoft,
O
is not a formally registered MIME type. However, this course uses the text/xsl MIME
type to make it easier to observe the results of XSLT. The processing instruction is not
required by the Oracle command-line XSLT Processor. Therefore, the MIME type used is
irrelevant to the Oracle command-line XSLT Processor.
Oracle 10g: XML Fundamentals 6-7
Viewing the Transformed Document

Perform one of the following:


• Open the XML document in the browser
• View oraxsl command-line processor output
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="emp.xsl"?>
<employees>
<employee>
<employee_id>100</employee_id>
<last_name>King</last_name>
<salary>24000</salary>
</employee>
<employee>
<employee_id>101</employee_id>
<last_name>Kochhar</last_name>
<salary>18000</salary>
</employee>
</employees>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Viewing the Transformed Document
U s
A I
The slide shows the source XML document and the result of applying the XSLT stylesheet
from the section titled “XSLT Stylesheet: Example.” When you open the XML document

O
with Microsoft Internet Explorer, it automatically applies the XSLT stylesheet specified in

l &
the XML document processing instruction and renders the result shown.
Alternatively, you can use the oraxsl command-line interface to apply an XSLT

n a
stylesheet to an XML document. To invoke oraxsl use:

te r
set CLASSPATH=E:\JDeveloper\lib\xmlparserv2.jar
java oracle.xml.parser.v2.oraxsl f.xml f.xsl f.html

I n
The oraxsl parameters in order are:

l e
1. The source XML document (f.xml)

c
2. The XSLT stylesheet document (f.xsl)

r a
3. The output file name (f.html). If omitted, the output appears on the standard output.

O
Note: If the result file contains HTML, then you can view it in a browser. The Oracle 10g
version of the oraxsl utility is configured as an External Tool in JDeveloper because it
supports some XSLT 2.0 features. The oraxsl utility is discussed in the section titled
“Using the oraxsl Utility.”

Oracle 10g: XML Fundamentals 6-8


JDeveloper Support for XSLT

1
5

2
3

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
JDeveloper Support for XSLT
U s
A I
Oracle JDeveloper 10g provides the XML Schema-aware XML Editor, which you can use to
create, check the syntax, and validate an XSL stylesheet document.

O
The slide illustrates the steps to create an XSL stylesheet in JDeveloper:

the menu).
l &
1. Right-click an existing project node and select New… (or select File > New… from

n a
2. In the New Gallery window, click XML under the General node in the Categories:

te r
section, and then double-click XSL stylesheet in the Items: section.
3. When the Create XSL File dialog box is displayed, enter the File Name: field and
click OK.
I n
c le
4. JDeveloper creates a skeleton XSL file containing:
- An XML declaration

r a
- The <xsl:stylesheet> root element with its required XML Namespace
prefix xsl and URI http://www.w3.org/1999/XSL/Transform
O - An empty <xsl:template> element with a rule matching the document root
5. Start editing the XSLT document making use of the code-insight features of the XML
Schema-aware XML Editor. The graphic shows code-insight providing a list of
suitable elements after typing the text <xsl: inside the <xsl:template> element.

Oracle 10g: XML Fundamentals 6-9


Creating Template Rules

The template rule:


• Is created using <xsl:template> elements with:
– A match attribute with an XPath pattern value
– The output template containing formatting
instructions to produce a result tree
<xsl:template match="pattern">
output-template
</xsl:template>
• Is applied when a node in the input XML document
matches the XPath pattern in the rule
<xsl:template match="/">
A simple text string
</xsl:template>
• Match pattern determines its context node
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating Template Rules
U s
A I
Template rules determine what the XSLT Processor will output when an input node matches
the template. Each template rule is defined by the <xsl:template> element. The
<xsl:template> element contains:
O
nodes from the input XML document
l &
• A match attribute that specifies the rule pattern, as an XPath expression, to recognize

a
• The output template between the start and end <xsl:template> tags. The output
n
te r
template contains instructions for formatting the result document tree. The output
template can be empty to suppress the output for a node, or include any, or a

I n
combination, of text, XML, HTML, and XSLT elements with additional instructions
for the XSLT Processor, and XSL-FO elements.
l e
The example in the slide transforms the entire XML input document into a simple text string
c
with the template rule matching the document root, and the output document will contain the
r a
text: A simple text string. The rule in the slide processes the root element and not

O
any other nodes from the input document. To process the child nodes of the document root,
its template rule must include an <xsl:apply-templates/> rule.
The general principle used by an XSLT Processor is that when a template rule matches an
input node, the output template instructions are copied to the resulting output tree.
Note: The matching node becomes the context node for the template rule.
Oracle 10g: XML Fundamentals 6-10
Getting Input Text with <xsl:value-of>

The <xsl:value-of> element:


• Has the select attribute containing an
expression, typically an XPath expression
• Inserts the string (text) value of the expression
• Is used inside an <xsl:template> element
• For example:
<xsl:template match="region">
<xsl:value-of select="."/>
</xsl:template>
<region num="1">
<id>1</id> 1 Europe
<name>Europe</name>
</region> Output document
Input XML document
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Getting Input Text with <xsl:value-of>
U s
A I
Most of the time, you want to insert the content from the input document into the output
results, unlike some of the previous examples that replace the input with a literal string. The

O
<xsl:value-of> element inserts into the output tree a string or text value calculated
from the XPath expression specified in the select attribute. For example, to output:

l &
• Element text: <xsl:value-of select="name"/> produces Europe

a
• Attribute values: <xsl:value-of select="@num"/> produces a 1

n
te r
• Numeric or Boolean expressions:
<xsl:value-of select="@num + 2"/> produces a 3, or
<xsl:value-of select="boolean(id)"/> produces the string true
I n
The <xsl:value-of> element syntax is:

l e
<xsl:value-of select=“expression”

c disable-output-escaping=“yes|no”/>

r a
The example in the slide uses the current node (.) XPath expression in the template

O
matching nodes with the name region from the input XML document. The result written
to the output document contains the concatenated text value of the <region> element and
its children. The disable-output-escaping attribute values are:
• yes that outputs an & character for an &amp; in the input, and > for an &lt;.
• no (the default), that outputs &amp; and &lt; as themselves, if in the input text
Oracle 10g: XML Fundamentals 6-11
Applying Template Rules

• Use <xsl:apply-templates/> to recursively


process children of the context (current) node. 1
<xsl:template match="/">
Document root Document root
</xsl:template>
/
<xsl:template match="/"> Output
A Document root Document
<xsl:apply-templates/> 2
B </xsl:template>
B D <xsl:template match="A"> Document root
C Root element A Root element A
D <xsl:apply-templates/>
C Element B
</xsl:template>
Element B
<xsl:template match="B">
Input XML Element B
document </xsl:template>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Applying Template Rules
U s
A I
As discussed, each rule is called a template because the literal text, elements, and attributes
inside the body of the rule act as a blueprint for constructing a part of the result tree. The

O
XSLT Processor constructs the content of a rule’s template in the result tree whenever it
processes a source node matching the rule’s pattern.

l &
To begin, the XSLT Processor reads the source document from top to bottom, starting at the

n a
document root, working down to the children using a preorder traversal. Templates are

te r
activated in the order in which they match elements encountered during the traversal.
Therefore, a template for a parent node is activated before a template matching its children.

I n
However, to activate templates for child elements, the <xsl:apply-templates/>

c l e
XSLT element must be included in the template of the parent node.
Note: The <xsl:apply-templates/> element is an instruction to the XSLT Processor

r a
to recursively process all the children of the context node. Without this rule, child elements

O
may not be processed unless the default template rule is invoked. Default template rules are
discussed in the section titled “Default Template Rules.”
Note: The data output from child node templates is inserted into the location where the
<xsl:apply-templates/> appears.

Oracle 10g: XML Fundamentals 6-12


Applying Template Rules (continued)
The slide illustrates the same input XML document tree being processed by two different
XSLT stylesheets:
1. In the first example, the resulting output document contains only the literal text,
Document root, contained in the template rule for the document root. In this
example, the <xsl:apply-templates/> element is not used; therefore, no other
nodes from the input document tree are processed. In addition, the template rule for the
document root overrides the built-in default template.
2. In the second example, the output document contains data from each of the templates
in the XSLT stylesheet. All templates are invoked because the <xsl:apply-
templates/> element is used in the templates for templates matching most of the
parent nodes in the tree. However, the child elements of node B, that is C and D, are
not processed without including the </xsl:apply-templates/> in the template
rule for B.
The sequence of events that occur in the second example in the slide is:
1. XSLT Processor reads the input XML document starting with the document root node.
2. It finds the template rule for the document root, with match="/", copies the
template data to the output tree, and writes the literal text "Document root" to the
output tree first.
3. It encounters the <xsl:apply-templates/> element inside the document root
template rule.
4. It fetches the document root’s child element, root element A, from the input XML
document.

n l
5. It finds the matching template rule for node A, with match="A", and copies its y
result.
e O
template data to the output tree, appending the text "Root element A" to the

template rule for node A.


U s
6. XSLT Processor encounters another <xsl:apply-templates/> element in the

A I
7. The first child, element B, of parent node A, is processed by the template rule, with
match="B", appending the text "Element B" to the output results.

O
8. Because there is no more to process in the template rule for B, processing continues

"Element B" to the output results.


l &
with the next child node B of parent element A, appending another line of the text

a
9. Because there are no more direct child elements of node A, the processing continues in
n
te r
the context of the rule for element A, which has no more to process either.
10. Processing returns to the context of the template for the document root, the parent of

I n
node A, which also has no more template data to be processed.
11. The result document tree is copied to the output destination, possibly the browser
l e
display window, or a file containing the result data.
c
r a
O
Oracle 10g: XML Fundamentals 6-13
Controlling Template Activation Order

The <xsl:apply-templates> activates one of the


following:
• Templates matching child nodes by default
• Templates matching its optional select attribute
Example:
<?xml version='1.0' encoding='windows-1252'?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:apply-templates select="//region"/>
</xsl:template>
<xsl:template match="regions">
<h1>Regions</h1><xsl:apply-templates/>
</xsl:template>
<xsl:template match="region">
<p><xsl:value-of select="."/></p>
</xsl:template>
</xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Controlling Template Activation Order
U s
A I
As discussed previously, the default behavior of <xsl:apply-templates> is to
process the child nodes of the context node. Alternatively, you can add a select attribute to

O
the <xsl:apply-templates/> element to control the specific template to be activated
relative to the context node.

l &
The example in the slide makes uses of the select attribute in the <xsl:apply-

n a
templates/> element. The select attribute specifies an expression to activate a

te r
template rule whose expression, in the match attribute, is activated for the same elements.
Note: The select attribute of the <xsl:apply-templates/> is typically the same

I n
as, but does not have to be identical to, the match attribute in the activated template rule.

l e
However, the two expressions must identify the same node-set for the correct template rule

c
to be activated.

r a
The results of the transformation contains a line of text for each region ID and name,

O
excluding the Regions header, because the template matching regions is not activated.
If the select="//region" is absent from the <xsl:apply-templates/> in the
template rule for the document root, then the transformation will include a level one heading
with the title Regions before the lines for each region ID and name pairs.

Oracle 10g: XML Fundamentals 6-14


Template Rules and Priorities

• The rule with the highest priority is applied.


• Or, use the rule that appears last if the priority
equals another.
<?xml version="1.0"?>
<xsl:stylesheet version ="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
Document root
</xsl:template>
<xsl:template match="/" priority="1">
Apply this document Root
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="department">
Department Data <!-- default priority -0.5 -->
</xsl:template>
<xsl:template match="department">
I WIN! <!-- default priority -0.5 -->
</xsl:template>
</xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Multiple Template Rules
U s
A I
An XSLT stylesheet normally has multiple template rules declared. As shown in the slide,
the match pattern for more than one template rule can be applicable to the same node. To

O
deal with this potential conflict, an XSLT Processor assigns a default priority to each

l &
template rule, unless the author of the XSLT stylesheet explicitly specifies a priority
attribute in the start tag of the <xsl:template> declaration. The default priority is:
a
• A -0.5 value, if the match pattern is a simple node-test, such as the element name
n
te r
• A 0 value, if the pattern uses a node name qualified by a namespace prefix, or the
processing-instruction() function, for example, dept:department

example, dept:*I n
• A 0.25 value for patterns using a namespace prefix with a wildcard node-test, for

l e
• A 0.5 value for all other patterns, for example, /departments, which uses an
c
absolute XPath pattern

r a
Note: If more than one template rule has a pattern that matches the same node, then the rule
O
with the highest priority is applied. If multiple patterns share the highest priority, then an
error occurs, or the rule appearing last in their order of appearance is used. For example, the
rule for pattern department containing the text literal “I WIN!” in the slide is selected
because it appears last even though it has the same priority as the previous one.

Oracle 10g: XML Fundamentals 6-15


Default Template Rules

XSLT provides built-in template rules:


• That are applied for nodes without a matching
template rule in the XSLT stylesheet
• For different types of nodes in an XML document,
such as:
– The element and root nodes:
<xsl:template match="*|/">
<xsl:apply-templates/>
</xsl:template>
– The text and attribute nodes:
<xsl:template match="text()|@*">
<xsl:value-of select="."/>
</xsl:template>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Default Template Rules
U s
The simplest form of an XSLT stylesheet is:
<?xml version="1.0"?>
A I
<xsl:stylesheet version ="1.0"
O
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
</xsl:stylesheet>
l &
a
An empty XSLT stylesheet creates an output document that contains the text values for all
n
te r
the nodes in the source document. This occurs because most XSLT processors implement
default template rules called built-in templates. The slide shows the first built-in template

I n
rule matching the document root (/) and all element nodes (*) of the source document tree.
The second template rule matches all the text nodes (text()) and attribute nodes (@*).

l e
The XSLT Processor uses the first built-in template rule to process the document root and all
c
its descendant nodes because of the presence of the <xsl:apply–templates/>

r a
element. When a text (or attribute) node is encountered, the second template invokes the

O
<xsl:value-of> element to output its string value.
The resulting output document contains all the text values from the input document.
Note: Explicit template rules added to the XSLT stylesheet override the default built-in
rules. However, nodes without explicit template rules can match the default template rules,
which often cause unwanted text to appear in the output document.
Oracle 10g: XML Fundamentals 6-16
Effects of Default Template Rules

<?xml version="1.0"?>
<xsl:stylesheet version ="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr><th>Id</th><th>Name</th><th>Salary</th></tr>
<xsl:apply-templates/> <!--employees-->
</table> <xsl:template match="*|/">
</body> <xsl:apply-templates/>
</html> </xsl:template>
</xsl:template>
<xsl:template match="employee">
<tr>
<td><xsl:value-of select="employee_id"/></td>
<td><xsl:value-of select="last_name"/></td>
<td><xsl:value-of select="salary"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Effects of Default Template Rules
U s
A I
To illustrate the effects of default template rules, the example assumes that the document
root contains the employees root element with one or more employee children. The

O
XSLT stylesheet declares template rules matching the document root and employee

l &
nodes, but not the employees element. In this case, the processing steps are the following:
1. The document root template outputs the HTML table header row and invokes the
a
<xsl:apply-templates/> element inside the HTML table after the header row.
n
te r
2. The default template is invoked for the employees root element, which does not
have an explicit template rule, as seen by the dotted arrows. The default template
outputs white space and invokes the <xsl:apply-templates/> element to
I n
process the employee child elements.

c l e
3. Each employee node matches its template rule that outputs the text value for the
employee_id, last_name, and salary in the cells of a HTML table row.

r a
Note: After the source document and stylesheet has been constructed and before it is
processed by an XSLT Processor, the text nodes are stripped if it contains only white space
O
characters. Stripping a text node removes it from the tree. The XSLT stylesheet can specify:
• The <xsl:strip-space elements="tokens"/> element to define a space-
separated list of elements for which the spaces are stripped
• The <xsl:preserve-space elements="tokens"/> element to define a list
of space-separated elements in which the spaces are preserved
Oracle 10g: XML Fundamentals 6-17
Looping with <xsl:for-each>

The <xsl:for-each> element:


• Provides a select attribute containing an
expression to identify a node-set
• Applies its template for each node in the node-set
• Is nested inside an <xsl:template> element
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="departments">
<xsl:for-each select="department">
<p><xsl:value-of select="."/></p>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Looping with <xsl:for-each>
U s
A I
The <xsl:for-each> element iterates through all the nodes in the node-set matching the
expression specified in its select attribute. The template rule is applied once for each

O
node in the node-set. The XSLT stylesheet in the slide can be applied to the following XML:
<?xml version="1.0"?>
<departments>
l &
<department>

n a
<department_id>10</department_id>

te
</department> ...r
<department_name>Administration</department_name>

I n
</departments>

l e
When applying the XSLT stylesheet, the processing steps are:
1. The default template rule matches the document root and executes an <xsl:apply-
c
r a
templates/> causing the departments root element template to be activated.
2. The departments root element template rule is activated with the <xsl:for-
O each> element matching all the department child elements.
3. The <xsl:for-each> element is applied for each department node.
The resulting output document contains one line for each department element, with the
text values of its child elements concatenated, for example:
<p>10 Administration</p> ...
Oracle 10g: XML Fundamentals 6-18
Specifying Output Formats

The <xsl:output> element:


• Specifies the output format of the result tree
• Must be a child of the <xsl:stylesheet>
element
• Has a method attribute value that must be one of:
– xml
– html
– text
– A qualified name, which does not define behavior
<xsl:output method="xml" media-type="text/xml"/>
<xsl:output method="html"
omit-xml-declaration="yes"
media-type="text/html"/>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Specifying Output Formats
U s
A I
You can use XSLT to create the result tree in different output formats, such as:
• XML: Set method to xml, the default, unless the output tree root element is
<html>. The xml output type can be used for XHTML output.
O
• HTML: Set method to html to inform the XSLT Processor to convert empty

<br>.
l &
elements such as <br/> or <br></br> into their unpaired HTML form, that is,

n a
Note: The XSLT stylesheet must use one of the empty element formats for unpaired

te r
HTML tags to ensure that the stylesheet is well-formed.
• Text: Set method to text , to output documents with a text/plain MIME type.

I
10g, for example:n
• Other formats: Other formats, such as WML, can be parsed by Oracle JDeveloper

l e
<xsl:output method="wml"

c media-type="text/x-wap-wml" indent="yes"/>

r a
The <xsl:output> element provides several attributes, such as suppressing the output of

O
the XML declaration by using omit-xml-declaration="yes" .
Note: The XSLT Processor may process the output method specified, but is not required to
do so. Therefore, different XSLT processors may produce different results. If the stylesheet
does not contain an <xsl:output> element, the html method is used if the root element
in the output is <html>, independent of text case. Otherwise, the xml method is used.
Oracle 10g: XML Fundamentals 6-19
Attribute Value Templates

An attribute value template is:


• An XPath expression, enclosed in braces, whose
result is used as an attribute value
• Used to include input document information in the
attribute values of XSLT elements, and the output
<region> 1
<region_id>1</region_id>
<region_name>Europe</region_name>
</region>
<xsl:template match="/"> 2
<regions><xsl:apply-templates/></regions>
</xsl:template>
<xsl:template match="region">
<region id="{region_id}" name="{region_name}"/>
</xsl:template>
<regions><region id="1" name="Europe"/></regions> 3

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Attribute Value Templates
U s
A I
The attribute value template is a powerful technique to include node names (element and
attribute names) or their values in the attribute values of XSLT elements in the stylesheet.

O
Using the attribute value template creates dynamic output results determined by information

l &
from the input document, such as attribute values for elements in the result document, as
shown in the example in the slide.You can use the <xsl:element> element in the
a
template to create output elements based on the element names from the input document, as
n
te r
discussed in the section titled “Creating Elements with Attributes.”
The example in the slide shows three related documents:

I n
1. Part of an input XML document showing one <region> element and its children
2. The XSLT stylesheet with templates to transform the input document converting child
l e
elements of the <region> element into attribute values in the output document. The
c
r a
template rules hard-code the output element names for <regions> and <region>,
but use the attribute value template technique to obtain the text values of the

O <region_id> and <region_name> elements from input document to set the


values for their corresponding attributes id and name in the <region> element of
the output document.
3. The resulting output document containing the results after transformation, with the
element text from the input document formatted as attribute values in the output
Oracle 10g: XML Fundamentals 6-20
Creating Elements with Attributes

• To create an element, use <xsl:element>:


<xsl:element name="region">Japan</xsl:element> 1
<region>Japan</region>
• To create an attribute, use <xsl:attribute>:
– Inside an <xsl:element>:
<xsl:element name="region"> 2
<xsl:attribute name="id">5</xsl:attribute>Japan
</xsl:element>
<region id="5">Japan</region>
– Inside <xsl:attribute-set> element used in the
use-attribute-set attribute of <xsl:element>:
<xsl:attribute-set name="region-info"> 3
<xsl:attribute name="id">5</xsl:attribute>
<xsl:attribute name="name">Japan</xsl:attribute>
</xsl:attribute-set>
<xsl:template match="region[1]">
<xsl:element name="{local-name()}"
use-attribute-sets="region-info">
</xsl:element>
</xsl:template> <region id="5" name="Japan"/>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating Elements with Attributes
U s
A I
If you are creating XML output documents, use the <xsl:element> to dynamically
create new elements. As shown previously and in the slide, you can perform one of the
following:
O
l &
• Explicitly provide element and attribute names
• Define rules such that element and attribute names are constructed from nodes in your
a
input XML document at processing time
n
te r
The slide shows three ways to create an element and the results, with or without attributes:
1. A <region> element without attributes that contains a text value of Japan.

I n
2. A <region> element containing the text Japan, and a single attribute called id

c l e
with a value of 5.
3. A <region> element with an id and name attribute. This example uses an

r a
<xsl:attribute-set> element that declares the id and name attributes and
their values. The template creating the output element, derives the element name from
O the context node using the local-name() XPath function, and generates the
attributes by referencing the region-info attribute in use-attribute-sets.
Note: The attribute set hard-codes its attribute names and values in the example. The design
can be made to be more flexible with the use of <xsl:parameter> elements.
Oracle 10g: XML Fundamentals 6-21
Sorting an XML Document

The <xsl:sort> element can be used:


• To sort nodes in the input document before the
nodes are processed
• Inside the <xsl:apply-templates> or
<xsl:for-each> elements
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/employees">
<xsl:for-each select="employee">
<xsl:sort select="last_name"/>
<p><xsl:value-of select="."/></p>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
• Multiple times to specify additional sort criteria
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Sorting an XML Document
U s
<employees>
<employee num="1">
A I
When the example in the slide is applied to the following XML document:

<employee_id>100</employee_id>
<last_name>King</last_name> O
</employee>
<employee num="2">
l &
a
<employee_id>101</employee_id>
n
</employee>
te r
<last_name>Kochhar</last_name>
<employee num="3">

I n
<employee_id>102</employee_id>
<last_name>De Haan</last_name>

c l e
</employee>
</employees>

r a
The output shows employee data sorted by their last names in the following sequence:
102 De Haan

O 100 King
101 Kochhar
Note: Multiple <xsl:sort> elements can be specified for additional sort criteria. You can
sort the child elements before the template is applied by using the following syntax:
<xsl:apply-templates><xsl:sort ...></xsl:apply-templates>

Oracle 10g: XML Fundamentals 6-22


Conditional Processing with <xsl:if>

• The <xsl:if> is processed when the test


attribute evaluates to true.
• The test attribute is a Boolean expression.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<h2>Departments with a manager</h2>
<xsl:for-each select="//department">
<xsl:if test="manager_id">
<p><xsl:value-of select="."/></p>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Conditional Processing with <xsl:if>
U s
A I
Templates rules can perform conditional processing using the <xsl:if> or the
<xsl:choose> elements. Both of these elements provide a test evaluating an XPath

O
expression as a Boolean result of true or false. The XPath expression is converted to a

l &
true or false value. If the XPath expression evaluates to:
• A numeric result of 0, it is converted to false; otherwise, it is considered true
a
• A string result with a length greater than 0, it is converted to true; otherwise, it is
n
false

te r
• A node with a value, it is considered true; otherwise, an empty or non-existent node
is false
I n
c l e
The example in the slide creates a HTML paragraph for each <department> element
containing a <manager_id> child element with a value. Any <department> element

r a
without a child or empty <manager_id> element are excluded.
Note: There are no <xsl:else> or <xsl:else-if> constructs in XSLT. To emulate
O
an “else” scenario, use the <xsl:choose> element, as discussed in the section titled
“Conditional Processing with <xsl:choose>.”

Oracle 10g: XML Fundamentals 6-23


Conditional Processing with
<xsl:choose>

The <xsl:choose> has one or more <xsl:when>


elements, and optionally one <xsl:otherwise>.
<xsl:template match="/">
<xsl:for-each select="//employee">
<p><xsl:value-of select="last_name"/>,
<xsl:choose>
<xsl:when test="salary &lt; 10000">
<font color="red">
<xsl:value-of select="salary"/>
</font>
</xsl:when>
<xsl:otherwise>
<font color="blue">
<xsl:value-of select="salary"/>
</font>
</xsl:otherwise>
</xsl:choose></p>
</xsl:for-each>
</xsl:template>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Conditional Processing with <xsl:choose>
U s
The <xsl:choose> element may contain:

A I
• One or more <xsl:when> elements, each with a condition in their own test
attribute
O
• An optional <xsl:otherwise> element

l &
The <xsl:when> elements are evaluated in the order of appearance; the first

n a
<xsl:when> with a true condition is instantiated, and the remaining elements are not

te r
processed. If all <xsl:when> conditions yield a false result, then none are processed,
unless an <xsl:otherwise> element is provided. The <xsl:otherwise> element

I n
must appear last and is processed if no <xsl:when> condition returns a true result.

l e
The example in the slide uses a single <xsl:when> element to check the salary value of

c
an employee. If the salary is less than 10000, the salary is displayed in a red colored font;

r a
otherwise, the salary is displayed with a blue colored font. The example emulates an “if-

O
then-else” scenario.
Note: The example uses the &lt; built-in entity reference for the less than operator to
ensure that the XSLT stylesheet is well-formed.

Oracle 10g: XML Fundamentals 6-24


Modes

• Allow the processing of the same input XML


element more than once
• Are applied using the mode attribute in
<xsl:template> and <xsl:apply-templates>
• Are Implemented by:
– Defining the mode in <xsl:template>:
<xsl:template match="department" mode="toc"> ...
<xsl:template match="department" mode="body"> ...
<xsl:template match="department "> ...

– Referencing the mode in <xsl:apply-templates>:


<xsl:apply-templates
select="department" mode="toc"/>

Note: The first template is matched and processed.


n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Modes
U s
achieved by:
A I
Modes provide a way to process the same input XML content more than once. This is

O
• Specifying the mode attribute in the <xsl:template> definitions

<xsl:apply-templates> element
l &
• Referencing the mode value of a template by using the mode attribute of the

n a
The mode attribute value is a string to describe the mode (such as toc for the table of

tree.
te r
contents, and body to represent the body of information) for transformation to the output

I n
After a mode attribute is defined on a template rule, you can specify the mode in one or

l e
more instances of the <xsl:apply-templates>, which ensures that the XSLT

c
Processor applies the template matching the specified mode value.

r a
The example in the slide shows three incomplete template rules with the first two specifying

O
their mode attribute values of toc and body, respectively. When the <xsl:apply-
templates> element example is encountered matching the employee nodes, it targets the
template defined with the mode value toc. In this case, only the first of the template rules is
applied as the node and mode name match the apply template request.

Oracle 10g: XML Fundamentals 6-25


Example of Using Modes

...
<xsl:template match="/departments">
<html>
<body>
<h1>Department Report</h1>
<ol><xsl:apply-templates
select="department" mode="toc"/></ol>
<xsl:apply-templates
select="department" mode="body"/>
</body>
</html>
</xsl:template>
<xsl:template match="department" mode="toc">
<a href="#id_{department_id}">
<li><xsl:value-of select="department_name"/></li>
</a>
</xsl:template>
<xsl:template match="department" mode="body">
<a name="#id_{department_id}">
<h2><xsl:value-of select="department_name"/></h2>
</a>...<xsl:apply-templates mode="body"/>...
</xsl:template>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example of Using Modes
U s
A I
In the slide, you see how to use the <xsl:apply-templates> element to specify a
mode for the template to be applied, and how to specify a mode name in target

O
<xsl:template> elements. The example uses an XML input document of department

l &
data to generate a Web report. The XSLT stylesheet processing steps are the following:
1. The template rule matching the root element /departments generates the HTML
a
document structure with the report header Department Report, and generates an
n
te
using the mode value toc.r
ordered list of department names by requesting the <xsl:apply-templates>

I n
2. The <xsl:template> with mode toc is invoked to generate the HTML list
elements containing the department name as a hypertext link referencing an anchor

l e
named with the literal text #id_ prefixed with the department_id node text.
c
3. Next, the root element template rule processes another <xsl:apply-templates>

r a
element, this time using the mode value of body.

O
4. The template rule with a mode of body generates the body of the report containing
the department headers surrounded by the HTML anchor target whose name is the
same as the hypertext link name created by the template with the toc mode.
5. The template with a body mode applies its child templates with the mode of body.
Note: The hypertext link and anchor values are formed by using an attribute value template.
Oracle 10g: XML Fundamentals 6-26
Example of Using Modes

<ol>
<xsl:apply-templates
select="department"
mode="toc"/></ol>

<xsl:apply-templates
select="department"
mode="body"/>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example of Using Modes (continued)
U s
A I
The slide shows the sample HTML results for the XSLT stylesheet shown in the previous
slide. The stylesheet shows <xsl:apply-templates> elements with their

O
corresponding output. A snippet of the department XML document is:

&
<?xml version='1.0' encoding='windows-1252'?>

<departments>
a l
<?xml-stylesheet type="text/xsl" href="code_06_28_n.xsl"?>

n
<department num="1">
r
te
<department_id>10</department_id>
<department_name>Administration</department_name>

I n
<manager_id>200</manager_id>
<location_id>1700</location_id>

c l e
</department>
<department num="2">

r a <department_id>20</department_id>

O <department_name>Marketing</department_name>
<manager_id>201</manager_id>
<location_id>1800</location_id>
</department>
...
</departments>
Oracle 10g: XML Fundamentals 6-27
Example of Using Modes (continued)
The report on the previous page is generated by using the following XSLT stylesheet:
<?xml version='1.0' encoding='windows-1252'?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/departments">
<html>
<body>
<h1>Department Report</h1>
<ol>
<xsl:apply-templates
select="department[position()&lt;5]"
mode="toc"/>
</ol>
<xsl:apply-templates
select="department[position()&lt;5]"
mode="body"/>
</body>
</html>
</xsl:template>
<xsl:template match="department" mode="toc">
<a href="#id_{department_id}">
<li><xsl:value-of select="department_name"/></li>
</a>
</xsl:template>
n l y
<xsl:template match="department" mode="body">
<a name="#id_{department_id}">
e O
</a>
U s
<h2><xsl:value-of select="department_name"/></h2>

<table border="1">

A I
<tr><xsl:apply-templates mode="body"/></tr>

O
<tr><xsl:apply-templates/></tr>
</table>
</xsl:template>
l &
<xsl:template match="department/*" mode="body">

n a
<th><xsl:value-of select="local-name()"/></th>
</xsl:template>

te r
<xsl:template match="department/*">

I n
<td><xsl:value-of select="."/></td>
</xsl:template>

l e
</xsl:stylesheet>
c
r a
O
Oracle 10g: XML Fundamentals 6-28
Calling Templates by Name

• Create a template specifying the name attribute:


...
<xsl:template name="deptlist">
<!-- instructions to process -->
</xsl:template>
...

• Call template by name:


...
<xsl:template match="/departments">
<html>
<body>
<h1>Department Report</h1>
<ol><xsl:call-template name="deptlist"/></ol>
<xsl:apply-templates mode="body"/>
</body>
...

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Calling Templates by Name
U s
<xsl:call-template> rule. The slide shows:
A I
A template rule with a name attribute can be instantiated by referencing its name in an

O
• Assigning the name attribute value of deptlist to the template rule

l &
Note: A template without a match attribute cannot have a mode attribute.
• Calling the template by using the <xsl:call-template> element with the name
a
attribute value deptlist identifying the desired template rule to be instantiated
n
te r
Note: The called template does not have a match attribute;therefore, its processing
instructions must use XSLT commands that set the context. For example:

I n
<xsl:template name="deptlist">

e
<xsl:for-each select="//department">

c l <a href="#id_{department_id}">

r a <li><xsl:value-of select="department_name"/></li>
</a>

O </xsl:for-each>
</xsl:template>
Using named templates is an effective way for creating a stylesheet that is used with
multiple XML documents. Each XML document applies named templates for default
formatting appearance as per company standards, but produces different content.
Oracle 10g: XML Fundamentals 6-29
Creating and Using Parameters

• Define templates parameters with <xsl:param>:


<xsl:template name="deptlist">
<xsl:param name="loc_id"/>
<xsl:for-each
select="//department[location_id=$loc_id]">
<a href="#id_{department_id}><li><xsl:value-of
select="department_name"/></li></a>
</xsl:for-each>
</xsl:template>
• Pass parameters with <xsl:with-param> in an
<xsl:apply-templates> or <xsl:call-
template>:
<xsl:template match="/departments">
<ol><xsl:call-template name="deptlist">
<xsl:with-param name="loc_id"
select="department[1]/location_id"/>
</xsl:call-template></ol>
</xsl:template>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating Parameters
U s
A I
Defining parameters is similar to creating arguments for methods or procedures in a modular
programming language. The first example in the slide defines the template named

O
deptlist with one parameter called loc_id. The parameter value is used by prefixing

l &
its name with a dollar sign ($) in the template body. The example uses the $loc_id to
filter the department node-set identified by the <xsl:for-each> element to departments
a
with a specified location_id. The second example uses an <xsl:with-param> to
n
te r
specify the parameter name and its value determined by the select attribute when calling
the deptlist template that uses the <xsl:call-template> element.
Guidelines
I n
• The <xsl:param> element must be the first item in a template, and you can define

l e
one or more parameters.
c
• Prefix parameter names with a dollar sign ($) to use the parameter values in the

r a
template.
• Provide default parameter values by using either the template body,(between the start
O and end <xsl:param> tags), or by using the select attribute.
• Provide parameter values with <xsl:with-param> either in the template body, or
by using the select attribute.
Note: The <xsl:param> and <xsl:with-param> elements define their value by
using either the select attribute or their template bodies, but not both at the same time.
Oracle 10g: XML Fundamentals 6-30
Using the oraxsl Utility

The oraxsl command-line utility:


• Transforms XML documents with an XSLT
stylesheet
• Writes the result to a file or the standard output
• Requires:
– The java executable in the PATH
– The xmlparserv2.jar file in the CLASSPATH
• For example:
java oracle.xml.parser.v2.oraxsl
departments.xml departments.xsl result.html

• Is configured as an External Tool in JDeveloper for


this course by using Tools > Oraxsl
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the oraxsl Utility
U s
A I
The oraxsl is a command-line interface used to apply a stylesheet on XML documents. To
use oraxsl, ensure that the following environment variables are set:

O
• The CLASSPATH must contain E:\JDeveloper\lib\xmlparserv2.jar, or

l &
an Oracle 10g ORACLE_HOME\lib\xmlparserv2.jar for XSLT 2.0 support.
• The PATH contains the directory where the java executable is located.

n a
To use the simplest form of invoking the oraxsl utility, enter:

te r
java oracle.xml.parser.v2.oraxsl [opts] source stylesheet [result]
The command-line parameters are:

I n
opts, representing zero or more options


c e
source, representing the file name of the input source XML document
l
stylesheet, representing the file name of the XSLT stylesheet

r a
result, an optional file name for the result data. If omitted, the results are written to
the command window or standard output.
O
Note: In this course, Oracle JDeveloper is configured with the oraxsl utility as an
External Tool, which is invoked by right-clicking an XML document and selecting Oraxsl,
which prompts for the XSLT stylesheet file name and an output file name. If the output file
name is not provided, then the results are written to the JDeveloper Log window.
Oracle 10g: XML Fundamentals 6-31
Using the oraxsl Utility (continued)
The oraxsl utility can process multiple XML documents, and accept the following
command-line options that dictate how it must behave:
• -d directory to specify a directory with files to be transformed. (The default
behavior is to process all files in the directory.) If only a certain subset of the files in
that directory (for example, one file) needs to be processed, then this behavior must be
changed by using -l and by specifying only those files that need to be processed. You
can also change the behavior by using the -x or -i option to select files based on their
extension.
• -debug, which enables debug mode. By default, the debug mode is turned off.
• -e error_log to specify a file into which errors and warnings are written
• -h, which prints the oraxsl invocation syntax and options
• -i source_extension, which specifies the file extensions to include (used in
conjunction with –d)
• -l xml_file_list to specify a list of files to be transformed
• -o result_directory, which defines a location to place result files. This must
be used with the -r option.
• -p param_list to specify a list of parameters
• -r result_extension to specify extensions to be used for result files. If -d or
-l is specified, then the option of –r must be specified. For example, if the extension
is specified as out and an input document is foo, then the result file will be called


foo.out. By default, the results are placed in the current directory.

or -l options are specified. n l


-s stylesheet, which specifies the stylesheet file to use. This must be used if -dy

e O
-t num_of_threads, which controls the number of threads to use for processing

when processing multiple documents.


U s
the transformations. Using multiple threads can provide performance improvements


could help in tracing any problems encountered
A I
-v, which enables a verbose mode that displays some debugging information that


O
-w, which causes warnings to be displayed. By default, warnings are turned off.
-x source_extension, which defines file with extensions to be excluded (used
&

in conjunction with the -d option)

a l
Note: The External Tool configuration of oraxsl does not use any of these options. To

r n
view the JDeveloper External Tool configuration, perform the following steps:

I n te
1. Click Tools > External Tools ….
2. Select Oraxsl from the External Tools: list and click Edit.

c l e
3. View the Arguments: field in the External Program Options tab.
4. Click other tabs as required.

r a
O
Oracle 10g: XML Fundamentals 6-32
Summary

In this lesson, you should have learned how to:


• Create an XSL stylesheet containing XSLT
elements
• Use XSLT to transform an XML document by using
a browser and the oraxsl command-line utility
• Use <xsl:template> to create a template rule
• Use <xsl:apply-templates> for recursion
through child template rules
• Call named templates with <xsl:call-
template> with and without parameters
• Apply sort criteria to nodes in an XML document
by using the <xsl:sort> element
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
XSL Transformations (XSLT) occur when a node in the source matches a template rule
pattern. Then, the content of that rule is written to the result tree. Given a source tree and a

O
stylesheet, the XSLT Processor carries out the transformation described by rules in the


l &
stylesheet. An XSL stylesheet contains XSLT elements, such as:
<xsl:template> to create a template rule, without and with parameters defined by
using an <xsl:param> element
n a


te r
<xsl:apply-templates> for recursion through child template rules
<xsl:call-template> to call named templates

I n
<xsl:value-of> to obtain the value of a node in the XML document
<xsl:for-each> to loop through a node-set
e

c l
<xsl:if>, or <xsl:choose>, <xsl:when>, and <xsl:otherwise> for

r a
conditional processing
Parameter values are supplied to templates by using the <xsl:with-param> element.
O
Sorting is accomplished by including one or more <xsl:sort> elements in a template
rule to sort the input node-set before they are processed. Some Web browsers transform an
XML document by using the information provided in an <?xsl-stylesheet?>
processing instruction. The oraxsl command line accepts an XML document and XSLT
stylesheet as command-line arguments to perform the transformation.
Oracle 10g: XML Fundamentals 6-33
Practice 6: Overview

This practice covers the following topics:


• Writing a simple XSL stylesheet to transform
department data in an XML document
• Modifying an existing XSLT stylesheet to process
an XML document containing employee
information
• Optionally, transforming an XML document by
using oraxsl to work with the <xsl:output>
element
• Optionally, using the oraxsl utility to transform
one XML document into another XML document

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Practice 6: Overview
U s
A I
In this practice, you create or modify existing XSLT documents to transform:
• The departments XML document into a Web page by using the browser XSLT
Processor
O
Processor
l &
• The employees XML document into a Web page by using the browser XSLT

n a
If there is time, you use oraxsl to transform:

te
<xsl:output> element r
• The departments XML document into an HTML page, and work with the

I n
• The departments XML document into another XML document, converting the child

c l e
elements into attributes of the same node.

r a
O
Oracle 10g: XML Fundamentals 6-34
Practice 6
The goal of this practice is to gain some experience in writing XSLT template rules to
transform an XML document into an HTML page, for display in a browser or on the Web,
and another XML document.
1. Transform the departments.xml document into a Web page.
a. In the XMLLabsProject, create a new XSL stylesheet called
departments.xsl.
b. In the skeleton document root template rule of departments.xsl, create a
level one HTML header, by using a <h1> tag, containing the text
Departments, followed by the <xsl:apply-templates/> element.
c. Create a template rule for the department element to create the following
HTML structure:
<h2>department_name</h2>
<ul>
<li>Id: department_id</li>
<li>Manager: manager_id</li>
<li>Location: location_name</li>
</ul>
Note: The manager_id information must only appear if it exists as an element
and is not empty. The location_name is derived by mapping a
location_id value of 1700 to Seattle, and 2400 to London; otherwise,
output the value unchanged.
Hint: Use <xsl:if> to test the manager_id, and <xsl:choose> to test
the location_id.
n l y
e O
d. Check the XML syntax and perform a Validate XML operation on the
departments.xsl document. Correct any errors and save the stylesheet.

U s
e. Open departments.xml in the XML Editor, and remove the dept
namespace prefix and declaration from the root element, and remove the dept

A I
prefix from the start and end tags of the first two <department> elements.
f. In departments.xml, add the xml-stylesheet processing instruction to
O
associate with the departments.xsl stylesheet created. Save the changes.

&
g. Observe the transformation to departments.xml in the browser by using
l
Internet Explorer.
n a
Tools > Internet Explorer, or by right-clicking the document and selecting

te r
Note: Correct any errors until you obtain the desired transformation.
2. Transform the employees.xml document into a Web page by making the requested

I n
modifications to the skeleton employees.xsl stylesheet provided.

c l e
a. In the XMLLabsProject, add or open the file called
E:\labs\lab\employees.xsl.

r a
b. Attach the employees.xsl stylesheet to the employees.xml document,
and display employees.xml in the browser. What do you observe?
O c. Modify employees.xsl to enable the employee elements to be transformed
and its child data to be displayed in an HTML table format under the Employee
Information heading. Save the changes and display the results in the
browser. What is the order of employee elements?
Oracle 10g: XML Fundamentals 6-35
Practice 6 (continued)
d. Modify employees.xsl to sort the employee elements by their last name.
Save the changes and display the result in the browser.
e. Examine the last template rule for the salary elements in the
employees.xsl file. Notice that this template rule formats the style of the
salary value in bold or italics based on a condition. Alter the employee
element template rule to apply the salary template rule, instead of outputting
the value of the salary, in the last cell of each row of the HTML table. Save
the changes and view the results in the browser.
f. Modify the salary template rule to accept a parameter called minsal, and using
the select attribute, assign it with a default value of 4500. Modify the
condition to reference the minsal parameter. Save the change and display the
results in the browser.
g. Modify the employee template rule to pass a parameter value of 8000 to the
salary template rule when it is applied. Use the parameter template body to
supply the parameter value. Save changes and display the results in the browser.
If you have time…
3. Transform the departments.xml file into a HTML file using the oraxsl utility.
a. Right-click departments.xml and select Oraxsl from the menu. At the
prompt, enter the XSL stylesheet name departments.xsl, a space, and the
output file name departments.html.
b. In JDeveloper, open the departments.html file, generated by oraxsl, in
your XMLLabsProject.
c. In the HTML editor window, click the Preview tab. What do you observe? n l y
O
d. Click the Source tab for the HTML file to view the HTML tags, and notice the
e
for this kind of file?
U s
first line of the HTML document. Why is the first line present and is it relevant

A I
e. Delete the departments.html file from the disk by selecting the file name in
the Navigator and clicking File > Erase from Disk. Click Yes to confirm the
deletion request.
O
f. Modify the departments.xsl to include the <xsl:output> element by

l &
using html as the value for the method attribute, and add the attribute to

a
suppress the output of the XML declaration from the results. Save the changes.
n
te r
g. Run the oraxsl utility on departments.xml, and at the prompt, enter the
file name departments.xsl, a space, and file name departments.html.

I n
Open departments.html in the XMLLabsProject and examine the
Source tab to check that the XML declaration is no longer present.

l e
h. Run oraxsl on the employees.xml file, and at the prompt enter
c
employees.xsl, a space, and employees.html. Open the

r a
employees.html file in JDeveloper. Click the Source tab, right-click in the

O editor, and select Auto Indent to tidy the contents. Does the first line contain the
XML declaration? Explain your observation.

Oracle 10g: XML Fundamentals 6-36


Practice 6 (continued)
If you have time (continued)…
4. Using oraxsl, transform the departments.xml into an XML file called
departments_new.xml, where the children of the <department> element are
converted to attribute names by using their text part as the attribute values.
a. In the XMLLabsProject, create a new XSL stylesheet with the name
departments_new.xsl.
b. In departments_new.xsl, add to the document root template
<xsl:element> element to create a new output element called
DEPARTMENTS. Inside the template body of the <xsl:element> include the
<xsl:apply-templates/> element.
c. In departments_new.xsl, add another template rule for the department
input element. In the template body, use the <xsl:element> element to
create a new output element with the same name as the context node, that is,
department. Save the changes.
Hint: Use the local-name() XPath function inside braces (using the attribute
template value technique) to determine the current element name.
d. Run oraxsl on the departments.xml file, and at the prompt enter
departments_new.xsl, and click Ok. You can view the generated XML
document element in the Oraxsl tab Log window in JDeveloper. What do you
observe?
e. Edit departments_new.xsl, modify the <xsl:template> for the
department rule, and use an <xsl:for-each> element inside the
<xsl:element> template body to process all the children of the n l y
O
department node. For each child element, create an attribute by using the
e
U s
<xsl:attribute> element with the attribute name set to the name of the
child node, and attribute value to the child text value. Save the changes.

A I
Hint: Use the local-name() XPath function enclosed in braces to derive the
node name of child elements, and use <xsl:value-of> to obtain the node
text as the value.
O
f. Run oraxsl on the departments.xml file, and at the prompt, enter

l &
departments_new.xsl, and click Ok. You can view the generated XML

a
document element in the Oraxsl tab Log window in JDeveloper. What do you
n
observe?

te r
g. Run oraxsl on the departments.xml file again, and at the prompt, enter

I n
departments_new.xsl, a space, and departments_new.xml, and click
Ok. Open the departments_new.xml output document in your

l e
XMLLabsProject, and check the XML syntax. Is the document well-formed?
c
Optionally, right-click the file in the XML Editor, and select Auto Indent XML
r ato tidy the contents.

O
Oracle 10g: XML Fundamentals 6-37
n l y
e O
U s
A I
O
l &
na
te r
I n
c le
ra
O
XSQL Pages Publishing Framework

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to:


• Describe the XSQL Pages Publishing Framework
• Create an XSQL Page by using JDeveloper
• Use the <xsql:query> element to obtain dynamic
XML content by using a SQL statement
• Transform an XSQL Page with an XSL stylesheet
• Test the XSQL Page with the Embedded OC4J
Server in JDeveloper

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
In this lesson, you learn about the different methods available to dynamically generate
Extensible Markup Language (XML) content by using XSQL Pages containing a SQL query

O
that obtains the data from relational tables in the database.

l &
You use JDeveloper to create, and edit the XSQL Pages, and write <xsql:query>
elements containing SQL statements. The XSQL Pages are tested by using the Embedded

n a
Oracle Application Server Containers for J2EE (OC4J) Server in JDeveloper.

te r
Note: The Embedded OC4J Server is the same Java 2, Enterprise Edition (J2EE)-compatible
server available in the Oracle Application Server product suite.
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 7-2
Web Application Architecture

Typical Web applications:


• Use a browser as a client
• Have an application server in the middle tier
• Use a database server to manage dynamic data
• Use HTTP as the communication protocol

HTTP request
SQL
XML/HTML

HTTP response

Client Application server Database

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Web Application Architecture
U s
slide. The architecture comprises:
A I
The typical Web applications are based on the logical three-tier architecture illustrated in the

O
1. A browsers for the client to issue HTTP requests for information

l &
2. An application server to process the HTTP requests from browser clients and return an
HTTP response containing XML, HTML, and other forms of data
a
3. A database that stores dynamic data that is subject to change over time. Applications in
n
stored procedures.
te r
the middle-tier query and manipulate the data by using SQL operations, or calls to

I n
Web applications, which are written in a variety of languages, can be XML-based, where the

c l e
exchange of information with the client or other applications is in the form of XML data.
Oracle XSQL Pages Publishing Framework runs on top of the middle-tier in a Web

r a
application architecture by using J2EE technology to process data in the XML format.

O
Oracle 10g: XML Fundamentals 7-3
XSQL Pages Publishing Framework

The XSQL architecture is an extensible platform for


easily publishing XML on the Web.

Application server

Servlet engine
XSQL
XSQLServlet command
XSQL XSQL Page processor line
Browser
Page XML Parser XML SQL
Utility
XSLT SQL
Response processor JDBC
document
XSL stylesheet
l y
Database
n
Copyright © 2004, Oracle. All rights reserved.

e O
XSQL Pages Publishing Framework
U s
Oracle XSQL Pages Publishing Framework is:

A I
• An extensible platform for easily publishing XML information in any output format

O
• A software architecture that uses an XSQL page to simplify combining the power of
SQL, XML, and XSLT to publish dynamic Web content based on the data obtained
from database tables
l &
called an XSQL Page to:
n a
Using the XSQL Pages Publishing Framework, you can create and use declarative templates

te r
• Assemble dynamic XML “datagrams” containing parameterized SQL queries
• Transform the XML “datagrams” to produce a result in XML, HTML, or text-based

I n
format by using an associated XSLT transformation

l e
Because assembling and transforming information for publishing is done declaratively, no
programming is required. However, the XSQL Pages Publishing Framework is extensible by
c
r a
using Java to integrate custom information sources, and perform custom server-side
processing.

O
As shown in the slide, the XSQL Pages Publishing Framework resides in a J2EE server
whose components include the XSQLServlet with an XSQL Page processor, which uses an
XML Parser, XML SQL Utility (XSU), and JDBC to process SQL, and an XSLT Processor
for applying transformations.
Note: XSQL Page processor provides a command-line and programmatic interface.
Oracle 10g: XML Fundamentals 7-4
Applications and Benefits of XSQL Pages

XSQL Pages:
• Provides easier publishing of database data
• Is declarative and does not require programming
• Uses a browser to display XML data that can be
transformed by using XSL stylesheets into XML,
HTML, text, and other formats
• Is built on functionality provided by Oracle XML
components

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Applications and Benefits of XSQL Pages
U s
A I
Using the XSQL Pages Publishing Framework, the assembly of information to be published
is cleanly separated from presentation. This simple architectural structure has profound
productivity benefits. An XSQL Page template can:
O
l
• Return an XML “datagram” to the requestor&
• Assemble an XML “datagram” by using the result of one or more SQL queries

a
• Optionally, transform the “datagram” into XML, HTML, text, or any other format
n
te r
During the transformation process, you can use stylesheets that conform to the W3C XSLT
1.0 standard to produce documents in a variety of formats, such as:

I n
• HTML, for browser display

c l e
• Wireless Markup Language (WML), for wireless devices
• Scalable Vector Graphics (SVG) for data-driven charts, graphs, and diagrams

r a
• XML stylesheet Formatting Objects (XSL-FO), for rendering into Adobe PDF
• Text documents, such as e-mails, SQL scripts, Java, and other program structures
O
• Arbitrary XML-based document formats
XSQL Pages functionality automates the use of several Oracle XML components, such as
XSQLServlet, XML Parser, XSLT Processor, and XML SQL Utility (XSU).

Oracle 10g: XML Fundamentals 7-5


Structure of a Simple XSQL Page

An XSQL Page:
• Is an XML document with a .xsql extension
• Is a template containing XML and XSQL elements
• Has a root element with the following attributes:
– xmlns:xsql with a URN urn:oracle-xsql
– connection with a database connection name
<?xml version="1.0"?> 1
<xsql:query xmlns:xsql="urn:oracle-xsql" 2
connection="hr">
SELECT *
FROM departments 3
WHERE department_id = 10
</xsql:query>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Structure of a Simple XSQL Page
U s
1. An XML declaration
A I
An XSQL Page is a well-formed XML document with a .xsql extension containing:

2. The root element with a namespace declaration for the xsql prefix and value of
O
urn:oracle-xsql, and a connection attribute with a database identifier name

semicolon terminator
l &
3. The SQL statement to be executed for the <xsql:query> action, without the

n a
Note: The root element can be anything. The example uses an <xsql:query>.

te r
Note: The XSQL document may contain a mix of XSQL and XML elements of your choice,
forming a template for generating an XML result containing data from a SQL query. The

I n
example in the slide generates the following XML result:
<?xml version='1.0'?>

le
<ROWSET>

c <ROW num="1">

r a <DEPARTMENT_ID>10</DEPARTMENT_ID>
<DEPARTMENT_NAME>Administration</DEPARTMENT_NAME>
O <MANAGER_ID>200</MANAGER_ID>
<LOCATION_ID>1700</LOCATION_ID>
</ROW>
</ROWSET>
Note: Output XML element names are derived from defaults, and queried column names.
Oracle 10g: XML Fundamentals 7-6
Creating an XSQL Page in JDeveloper

5
4

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating an XSQL Page in JDeveloper
U s
In JDeveloper, the steps to create an XSQL Page are the following:

A I
1. Select the project node and click File > New …, or right-click and select New….
2. In the General category, click XML.
3. In the Items, double-click XSQL Page. O
&
4. JDeveloper creates a skeleton XSQL Page in a file called untitledn.xsql, where
l
n a
n is a number. You can rename the file by using File > Rename….
Note: JDeveloper creates the document with a root element called <page>, which has

te r
an xsql namespace declaration. The root element name may also be changed.
5. You can edit the file contents, element names, and change the page structure by typing

I n
the information in yourself. You can also use the Component Palette to add XSQL
elements, such as an <xsql:query> or others to build your XSQL Page template.
l e
Component Palette items can be added to the XSQL document by first placing the
c
r a
cursor in the desired position of the XSQL file, and then clicking the required XSQL
element in the Component Palette.

O
Note: The connection attribute is not declared in the root element. You can manually
add the connection attribute, or allow JDeveloper to prompt you and add it when
creating the first XSQL element by using the Component Palette. The connection
attribute value must be the name of a Database Connection created in JDeveloper that is
present in a file called XSQLConfig.xml in the XSQL application CLASSPATH.
Oracle 10g: XML Fundamentals 7-7
Creating Database Connections

XSQL Page database connections are created with the


JDeveloper Database Connection Wizard.

1 2

3
4

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating Database Connections
U s
A I
Using the JDeveloper Database Connection Wizard, you can create named connections for
use with your XSQL page elements. JDeveloper provides many ways to create a database
connection. Some of these ways are:
O
• Click File > New…, expand General and click the Connections category, and then

l &
double-click the Database Connection item.

n
select New Database Connection…. a
• In the Navigator, click the Connections tab, then right-click the Database node, and

te r
• When you add your first XSQL element from the Component Palette, the XSQL
element wizard will provide a step requesting the name of a database connection to be

I n
used. You can select an existing name from the list, or click a New… button to launch

c l e
the Database Connection Wizard shown in the slide.
The benefit of the last approach is that JDeveloper will automatically add the connection

r a
attribute, with its value set to the name of the selected or newly created connection, to the
root element of the XSQL Page.
O
If you create the database connection before adding XSQL elements to the page and
manually type in the XSQL elements yourself without using the Component Palette, then
you must manually add the connection attribute and its value to the root element of the
XSQL Page. The database names are typically stored in a file called XSQLConfig.xml,
which must be located in the CLASSPATH application.
Oracle 10g: XML Fundamentals 7-8
Creating an <xsql:query> Action
Element

Create an <xsql:query> action element by typing the


element or clicking Query in the Component Palette,
and specifying:
1. Properties to set element attribute values
2. A database connection (if adding the first element)
3. The query text
<?xml version='1.0' encoding='windows-1252'?>
<page xmlns:xsql="urn:oracle-xsql"
connection="hr"> 2
<xsql:query max-rows="-1" null-indicator="no"
tag-case="lower"> 1
SELECT *
FROM regions 3
</xsql:query>
</page>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating an <xsql:query> Action Element
U s
A I
The simplest form of an <xsql:query> element contains a SELECT statement, and no
attributes specified in the start tag. Creating an <xsql:query> element is as simple as
typing it in, or clicking the JDeveloper Query component in the Component Palette, which
O
prompts for element details by using the following dialog sequence:

l &
1. The properties window is displayed to set values for attributes added to the
<xsql:query> start tag. Set the values as appropriate, and click Next. The example
a
in the slide shows the default property values that are applied (see explanation below).
n
te r
2. The database connection window appears only if the Query component is the first
XSQL element to be added to the file, that is, if the connection attribute is not
defined in the document root element. You can select the database connection name
I n
from a list, or create a new if none exist, and click Next.

c l e
3. Finally, enter the SQL SELECT statement for the component, and click Finish.
Using the Component Palette to add the <xsql:query> element, as shown in the slide,

r a
sets the following default attributes:
• The max_rows attribute with a value of –1 (the default) that indicates the query
Ofetches all the rows, or if set to a number, the specified number of rows.
• The null-indicator attribute with the value no suppresses output of NULL
valued columns. If set to yes, an empty element with attribute null="TRUE"
appears.
• The tag-case attribute causes XML element names to appear in lowercase.
Oracle 10g: XML Fundamentals 7-9
Viewing an XSQL Page

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Viewing an XSQL Page
U s
Page:
A I
In JDeveloper, use the following steps to view the XML generated by a query in an XSQL

1. Right-click the file for XSQL Page in the Navigator or Editor.


2. Select Run from the menu.
O
JDeveloper then automatically:
l &
1. Starts the Embedded OC4J container (a J2EE Server)
a
2. Deploys the XSQL Page as a Web application to the OC4J container
n
te r
3. Runs the browser with a URL requesting the XSQL Page, which is processed by the
built-in XSQLServlet and XSQL Page processor

I n
Note: The resulting XML output is displayed in the Web browser, as shown in the slide.
By default, the XML element names that are generated have default values. The example in
l e
the slide, in addition to the <page> root element, shows default XML element names for
c
the regions query in the section titled “Creating an <xsql:query> Action Element”:

r a
• The <rowset> element containing the set of rows returned by the query
• The <row> element for each row with a num attribute value as a sequence number
O
• The <region_id> and <region_name> elements, which are derived from the
database column names. Column aliases in the query are used for element names, and
are required for column expressions.
Note: Using various <xsql:query> attributes, you can customize the generated XML
output results.
Oracle 10g: XML Fundamentals 7-10
Customizing the <xsql:query> Output

• The rowset-element attribute changes the tag


name for the default <ROWSET> element.
• The row-element attribute changes the tag name
for the default <ROW> elements.
• A column alias renames the tag name of a column.
<?xml version="1.0"?>
<page xmlns:xsql="urn:oracle-xsql"
connection="hr" >
<xsql:query tag-case="lower"
rowset-element="departments"
row-element="department">
SELECT department_id id, department_name
FROM departments
</xsql:query>
</page>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Customizing the <xsql:query> Output
U s
A I
The <xsql:query> element supports several attributes, which declaratively set XML-
generation options supported the XSQL Page processor. The results of each
<xsql:query> element can be customized by adding the following optional attributes in
the start tag: O

l &
rowset-element sets the element name for the query result set. If set to the empty
string, then the document root element is suppressed. The default name is <ROWSET>.

n a
row-element sets the element name for each row. The default name is <ROW>.


te r
max-rows specifies the maximum number of rows to fetch.
skip-rows sets the number of rows to skip before returning the query results. The


I n
default is not to skip any rows.
id-attribute sets the name of an ID sequence number attribute for each <ROW>


c l e
element. The default name is num.
id-attribute-column specifies a column name used to supply the value for the

r a
ID attribute. The default is to use the row count value.
tag-case sets the case for element names of the query columns. Values can be
O

upper or lower causing column element names to be in uppercase or lowercase,
respectively. The default uses the case of the column name, or column aliases.
Note: The null-indicator attribute was covered in the section titled “Creating an
<xsql:query> Action Element.”
Oracle 10g: XML Fundamentals 7-11
Using Parameters in XSQL Pages

Parameters, which allow query results to be changed:


• Are passed to the XSQL Page in the HTTP request
http://host:80/xsqlapp/dept.xsql?loc_id=1700
• Can be specified as:
– A bind parameter using the ? placeholder character
<xsql:query bind-params="loc_id">
SELECT * FROM departments
WHERE location_id=nvl(?,location_id)
</xsql:query>
– A lexical parameter using {@param-name} syntax
<xsql:query loc_id="null">
SELECT * FROM departments
WHERE location_id=nvl({@loc_id},location_id)
</xsql:query>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using Parameters in XSQL Pages
U s
A I
An XSQL Page can accept a HTTP request with parameters, whose values which can be
used in the queries of the XSQL Page to produce different results. An XSQL Page can use:

O
• Bind parameters as question mark (?) character placeholders in the SQL statement,
anywhere that a SQL bind variable is permitted. The parameter values are bound to the

l &
placeholder by specifying the bind-params attribute on the action element. The

a
bind-params attribute is a space-delimited list of parameter names, whose order of
n
te r
appearance indicates the position of the bind variable to which its value is assigned in
the statement. If the same parameter value is required by more than one occurrence of

I n
a question mark, you must repeat the parameter name in the appropriate position of
bind-params attribute list.

l e
• Lexical parameters that are referenced using the {@param-name} syntax. Lexical
c
parameter values can be used to substitute the text in attribute values and sections of
r a
the SQL statement, such as the conditions, columns, or the table name.

ONote: The SQL statement must be valid after lexical substitution takes place.
The example in the slide uses loc_id as a parameter name-value pair in the HTTP request.
The parameter value is used in the WHERE clause of each query. The first query uses a
bind-params. The second query uses the loc_id lexical parameter with a default value.
Oracle 10g: XML Fundamentals 7-12
Supplying Parameters to XSQL Pages

<page xmlns:xsql="urn:oracle-xsql"
connection="hr">
<xsql:query loc_id="1700"><!-- default -->
SELECT * FROM departments
WHERE location_id={@loc_id}
</xsql:query>
</page>

Uses
request
parameter

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Supplying Parameters to XSQL Pages
U s
• The URL request (as shown in the slide)
A I
Parameters are sent to an XSQL Page as name-value pairs in one of the following:

• The HTTP request header posted to the Web server


O
l &
Typically HTML <FORM> fields are provided to obtained parameter values from user input.
Each field name in the HTML form is used as the parameter name, and the field content
provides its value.
n a
te r
If an HTTP request does not supply the required parameter name-value pair, then a default
value can be used from a parameter defined in the XSQL Page using a page-private value, a

I n
HTTP cookie value, or a HTTP session value. A default value can also be specified in an

c l
ancestor elements. e
attribute value in the start tag of the <xsl:query>, as shown in the slide, or one of its

r a
The example in the slide shows a simple case of using a parameter value supplied in the

O
HTTP request. The HTTP request uses the loc_id parameter with a value of 1800, which
is used in the XSQL Page to generate the results shown. Because of the precedence rules, the
HTTP request parameter value is used over the default value 1700 declared in the loc_id
attribute of the <xsql:query> element. If the parameter name-value pair was not
supplied with the HTTP request, then the default attribute value of 1700 is used in the query.
Oracle 10g: XML Fundamentals 7-13
Parameters and Order of Precedence

Browser Application server

http://host/page.xsql?p=4
Cookie: p=2

Servlet engine
XSQLServlet
<page xmlns:xsql="urn:oracle-xsql" ...>
<xsql:set-page-param name="p" value="1"/>
<xsql:set-cookie name="p" value="2"/>
<xsql:set-session-param name="p" value="3"/>
<xsql:query p="5">SELECT * FROM table
WHERE column={@p}</xsql:query>
</page>
Session state
p=3

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Parameters and Order of Precedence
U s
Page by defining a parameter as:
A I
The slide shows that parameter values may be supplied in the HTTP request, or in the XSQL

• A page-private parameter using the <xsql:set-page-param> element


O
• A HTTP cookie parameter, using the <xsql:set-cookie> element, whose value

l &
is sent in a response to the browser, which returns it in subsequent requests
• A HTTP session parameter with the <xsql:set-session-param> element. The

n a
XSQLServlet creates the HTTP session state maintained by the Servlet engine.

te r
• An attribute in the <xsql:query> element or one of its ancestor elements
As shown in the the slide, the parameter value used in the XSQL Page is indicated by a

I n
value, which is based on the following order of precedence rules:
1. Use the page-private parameter value, if set.
l e
2. Use the HTTP cookie parameter value, if supplied with an HTTP request.
c
r a
3. Use the HTTP session parameter value, if it has been created.
4. Use the HTTP request parameter value, if supplied.

O
5. Use a default value in the attribute on the current action or its ancestors.
6. Use an XSQL Page built-in value (not shown in the slide) of NULL for a bind
parameter and an empty string value for a lexical parameter.
Note: This resolution order prevents users from supplying parameter values in a request to
override the parameter set in the XSQL Page, HTTP cookie, or the HTTP session.
Oracle 10g: XML Fundamentals 7-14
Providing a Fallback Query

A fallback query:
• Is specified using an <xsql:no-rows-query>
child element in the <xsql:query> element
• Is invoked when no rows are returned for a
SELECT statement inside the <xsql:query>
<?xml version="1.0"?>
<xsql:query xmlns:xsql="urn:oracle-xsql"
connection="hr">
SELECT first_name, last_name FROM employees
WHERE last_name = '{@lname}'
<xsql:no-rows-query>
SELECT employee_id, last_name FROM employees
WHERE last_name LIKE '%{@lname}%'
</xsql:no-rows-query>
</xsql:query>
Note: Without a fallback, a <ROWSET/> is returned.
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Providing a Fallback Query
U s
A I
If a query inside an <xsql:query> element does not return rows, then the XSQL Page
processor writes an empty <ROWSET/> element into the output results for the query. If this

O
is not desirable, you can provide a fallback query. A fallback query is created by writing a
SQL statement inside an <xsql:no-rows-query> element that is nested inside the
&
relevant <xsql:query> element. If the SELECT statement inside the parent
l
a
<xsql:query> element does not retrieve any rows, then the fallback query is executed.

n
te r
The example in the slide searches for employees by an exact match on their last name value
supplied by the {@lname} lexical parameter, and displays the employee first and last
names. If the query does not return any rows, then the fallback query attempts a pattern
I n
match operation on the same value by using the LIKE operation to attempt returning the

c l
fallback query are:e
matching rows and displaying the employee ID and last name. Some of the reasons to use a

r a
• To retry processing of a statement with other or default values
• To perform a pattern match on textual data, when an exact match operation fails, as
O shown in the slide
• To generate a data-driven error or informational message
Note: If the fallback query fails to return any rows, then you can handle this condition with
an additional <xsql:no-rows-query> element within the fallback query. This can be
applied repeatedly to any depth.
Oracle 10g: XML Fundamentals 7-15
Results of Fallback Query: Example

Main query results with Fallback query results with


parameter lname=Patel parameter lname=Pat

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Results of Fallback Query: Example
U s
A I
The slide shows the results of the example in the section titled “Providing a Fallback
Query.” The result on the left shows that the main query fetched one row matching the last

O
name value of Patel assigned to the HTTP request parameter lname, with the

executed.
l &
<FIRST_NAME> and <LAST_NAME> elements being returned. The fallback query is not

n a
The result on the right shows the result when the main query fails to return any rows when

te r
lname is the value Pat, in which case the the fallback query is executed and returns two
rows with the <EMPLOYEE_ID> and <LAST_NAME> elements shown.

I n
If, for example, you entered a URL similar to the following based on the employee data

l e
contained in the HR schema EMPLOYEES table:

c
http://localhost:8988/.../code_07_15_s.xsql?lname=Pierce

r a
Then, the following result is displayed in the browser:

O <?xml version="1.0" encoding="windows-1252" ?>


<ROWSET />
In this case, you get the empty <ROWSET/> element because neither the SQL statement in
the <xsql:query> and the <xsql:no-rows-query> fallback query element return
any rows.
Oracle 10g: XML Fundamentals 7-16
An XSQL Page with Multiple Queries

<?xml version="1.0">
<employees xmlns:xsql="urn:oracle-xsql"
connection="hr">
<department dept_id1="10">
<xsql:query rowset-element="">
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id={@dept_id1}
</xsql:query>
</department>
<department dept_id2="20">
<xsql:query rowset-element="">
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id={@dept_id2}
</xsql:query>
</department>
</employees>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
An XSQL Page with Multiple Queries
U s
A I
An XSQL page can have any number of <xsql:query> elements. They can appear
anywhere you want them to on the page, and nested among other XML tags, as long as the

O
resulting document is a well-formed XML document. The result of the example in the slide
is:
<employees>
l &
<?xml version="1.0" encoding="windows-1252" ?>
<department dept_id1="10">
<ROW num="1">
n a
te r
<EMPLOYEE_ID>200</EMPLOYEE_ID>
<LAST_NAME>Whalen</LAST_NAME>
<SALARY>4400</SALARY>

I n
</ROW>
</department>

c e
<department dept_id2="40">
l <ROW num="1">
<EMPLOYEE_ID>203</EMPLOYEE_ID>

r a <LAST_NAME>Mavris</LAST_NAME>
<SALARY>6500</SALARY>

O </ROW>
</department>
</employees>
Note: The dept_id1 and dept_id2 lexical parameters may be supplied in the HTTP
request to alter the result data produced.

Oracle 10g: XML Fundamentals 7-17


Transforming an XSQL Page with XSLT

An XSQL Page can be transformed:


• By the XSQL Page processor by adding one or more
xml-stylesheet processing instructions to the
XSQL Page, after the XML declaration
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="trans.xsl"?>
<page xmlns:xsql="urn:oracle-xsql">
...
</page>
• By using one of the multiple xml-stylesheet
processing instructions whose media attribute
value matches the User-Agent HTTP header field of
the browser
• By a client or browser, if the client="yes"
attribute is set:
<?xml-stylesheet type="text/xsl" href="trans.xsl"
client="yes"?>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Transforming an XSQL Page with XSLT
U s
A I
Transforming an XSQL Page with an XSL stylesheet can be done either by the XSQL Page
processor in the server, or the client or browser. The XSQL Page processor transforms the

O
XSQL Page into another XML, HTML, or text document, when an xml-stylesheet

<?xml version="1.0"?>
l &
processing instruction is added to the XSQL page, after the XML declaration. For example:

a
<?xml-stylesheet type="text/xsl" href="trans.xsl"?>

n
te r
<page xmlns="urn:oracle-xsql" connection="hr"> ...
The XSQL Page processor can select a stylesheet from more than one xml-stylesheet

I n
processing instructions added to the XSQL Page. The XSL stylesheet selected must have a
media pseudo-attribute value that matches the requesting browser’s User-Agent HTTP

l e
header field. For example:
c
<?xml version="1.0"?>

r a
<?xml-stylesheet type="text/xsl" media="lynx" href="mylynx.xsl"?>

O
<?xml-stylesheet type="text/xsl" media="msie" href="myie.xsl"?>
<?xml-stylesheet type="text/xsl" href="default.xsl"?>
<page xmlns:xsql="urn:oracle-xsql" connection="hr"> ...
Note: Use the client="yes" pseudoattribute in the <?xml-stylesheet?>
processing instruction to have the browser perform the transformation.
Oracle 10g: XML Fundamentals 7-18
XSQL Page with XSLT: Example

• Server-side transformation:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl"
href="code_07_19_sa.xsl"?>
<xsql:query xmlns:xsql="urn:oracle-xsql"
connection="hr">
SELECT * FROM regions
</xsql:query>
• Client-side transformation:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" client="yes"
href="code_07_19_sb.xsl"?>
<xsql:query xmlns:xsql="urn:oracle-xsql"
connection="hr" >
SELECT * FROM regions
</xsql:query>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XSQL Page with XSLT: Example
U s
A I
In the first example in the slide, the XSL stylesheet instruction causes the transformation to
occur in the server by the XSQL Page processor invoking the XSLT Processor.

O
The second example includes the client="yes" pseudo-attribute to the stylesheet

l &
processing instruction, informing the XSQL Page processor to suppress executing its own
XSLT Processor, and return the generated XSQL Page results and the XSL stylesheet

n a
instruction to the browser, which will perform the required transformation.

te r
Note: After trying each approach, you can view the source page displayed in the browser. If
the source contains the generated XML data and the XSL stylesheet instruction, then the
I n
client has performed the transformation. If the browser contains HTML tags or a

l e
transformation of the original generated XML data, then it is likely that the XSQL Page

c
processor in the server has performed the transformation.

r a
O
Oracle 10g: XML Fundamentals 7-19
Summary

In this lesson, you should have learned how to:


• Explain the XSQL Pages Publishing Framework
and its benefits
• Create and edit an XSQL Page with JDeveloper
• Write an <xsql:query> element containing a
SELECT statement
• Influence the result element names using various
<xsql:query> attributes
• Transform XSQL Pages in the client or server
using an XSL stylesheet
• Test an XSQL Page by using the embedded OC4J
Container in JDeveloper
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
In this lesson, you learned to create an XSQL Page in JDeveloper, and executed the XSQL
Page by using the XSQL Pages Publishing Framework, which is implemented in a J2EE

O
container running the Oracle XSQLServlet and associated components.

l &
This lesson introduced you to using the <xsql:query> element to query data stored in an
Oracle database and generate the associated XML elements. The XML element names and
a
format can be altered by using the rowset-element, row-element, tag-case, and
n
te r
other attributes. If the SELECT statement contained in an <xsql:query> returns no rows,
then you can provide a fallback query in an <xsql:no-rows-query> element.

I n
Transformation of the results generated for an XSQL Page is simply done by including one
or more xml-stylesheet processing instructions after the XML header of the XSQL

l e
Page. By default, the XSQL Page processor performs the transformation by using the XSLT
c
Processor component in the XSQL Pages Publishing Framework; otherwise, the browser

r a
performs the transformation if the client pseudo-attribute with a value of yes is added to

O
the xml-stylesheet processing instruction.
When using JDeveloper to develop an XSQL Page, you can run the XSQL Page in the
embedded OC4J container to run the XSQL Pages Publishing Framework components. In
this way, you can test and debug your application before deploying it in a production
environment.
Oracle 10g: XML Fundamentals 7-20
Practice 7: Overview

This practice covers the following topics:


• Writing an XSQL Page to retrieve department data
• Writing an XSQL Page to display employee data,
with and without parameters
• Transforming the results of the XSQL Pages for
the departments and employees

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Practice 7: Overview
U s
A I
In this practice, you generate an XML document by using XSQL Pages, and transform the
results by using the XSLT Processor in the XSQL Page processor, using the XSL stylesheets
that you created in the previous practices.
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 7-21
Practice 7
The goal of this practice is to use the Oracle XSQL Pages Publishing Framework to generate
XML data by using the information stored in the Oracle database tables, and transform the
information into HTML for display on the Web.
1. Write an XSQL Page to display the rows in the DEPARMENTS table, and create the
named database connection for the database.
a. Right-click XMLLabsProject, and create an XSQL Page by selecting New…,
expand the General category, and click XML (if required). Double-click XSQL
Page in the Items list.
Note: JDeveloper creates a skeleton XSQL Page in a file called
untitled1.xsql.
b. Rename the XSQL file to departments.xsql by clicking
untitled1.xsql in the Navigator and selecting File > Rename… from the
menu. In the Rename dialog box, enter departments.xsql in the File
Name: field, and click Save.
c. In the XML Editor, replace the root element start and end tag name page with
the text departments, in lowercase.
d. In the departments.xsql code, place the cursor inside the
<departments> element and click the Query component in the Component
Palette to add an XSQL query element. In the Query wizard, accept the default
settings for property values and click Next. In the next wizard page, click the
New… button to the right of the Connection field to create a database
connection.
n l y
e. Click Next to step past the Welcome page in the Create Database Connection
O
window. In Step 1 of 4: Type window, enter the hr in Connection Name field,
e
and click Next.

U s
f. In Step 2 of 4: Authentication window, enter the database username assigned to

oracle, and click Next.


A I
you, such as orax, where x is a number assigned to you, and your password

O
g. In Step 3 of 4: Connection window, enter the Host Name:, JDBC Port:, and
SID: field values assigned by your instructor for this course. Then, click Next.

l &
h. In Step 4 of 4: Test window, click Test Connection and make sure that you get
a
the text Success! displayed in the Status: field, and then click Finish.
n
te r
Note: In the E:\JDeveloper\jdev\system9.0.5.2.1618 directory,
double-click the file called XSQLConfig.xml to open it in your Web browser.

I n
Locate the <connectiondefs> element and you will find that it contains the
<connection name="hr"> child element with your connection details.

l e
i. You are returned to the Query window. Click Next. You are returned to the
c
Query window. Click Next. In the Enter SQL Statement: field, type the
r a
following SQL statement:

O SELECT * FROM departments


Click Finish. Tidy the code created and save the changes to the XSQL Page.
j. Execute the XSQL Page to view the generated XML elements. Right-click
departments.xsql in the XML Editor or Navigator, and select Run. Close
the browser window after you have finished.
Oracle 10g: XML Fundamentals 7-22
Practice 7 (continued)
2. Create an XSQL Page to retrieve all the employee data, and parameterize the page to
display employees in a specified department.
a. In the XMLLabsProject, create a new XSQL Page and rename it as
employees.xsql.
b. Edit employees.xsql, changing the root element start and end tags to be
xsql:query, in lowercase. Inside the <xsql:query> element, enter the
following SQL statement:
SELECT employee_id, first_name, last_name, salary
FROM employees
Save the changes to the XSQL Page.
c. Run employees.xsql. Explain the result. Close the browser window.
d. Edit employees.xsql, and add the connection attribute with a value of
hr to the root element. Save the changes and run employees.xsql page. Did
it work this time? Close the browser window.
e. Edit employees.xsql. In the <xsql:query> element, add the appropriate
attributes to change the ROWSET element name to EMPLOYEES, the ROW
element name to EMPLOYEE, and to set the output tags in lowercase. Save the
changes and run the XSQL Page to view the results.
f. Edit employees.xsql. In the <xsql:query> start tag, define an attribute
called dept_id with a string value of NULL. Modify the SELECT statement to
have a WHERE clause with a condition comparing the department_id column
l y
with the value of dept_id referenced as a lexical parameter. Include an NVL()
test in the comparison to convert a NULL value in dept_id to the n
e O
department_id, which will cause all the employee rows to be displayed
when dept_id is the value NULL. Save the changes and run the employees
s
XSQL page. Which employees are displayed? Do not close the browser.
U
A I
Note: Use the NVL({@dept_id},department_id) in the condition.
g. In the browser window, append ?dept_id=90 to the URL address, and press

O
[Enter]. Do not close the browser window.
h. Modify the dept_id value in the URL to 140, and press [Enter]. What is the

l &
result returned? Do not close the browser window.

n a
i. Edit the employees.xsql page, and insert a fallback query to display the
following message enclosed in an <error> element: The department

te r
{@dept_id} does not exist or does not have any

I n
employees. Save the changes, and refresh the browser to observe the results.
j. Modify the fallback query by using a SELECT statement to print the message.

l e
Add rowset-element and row-element attributes to suppress these

c
elements, and use the lower tag case. Save the changes and refresh the browser.

r a
After this is completed, close the browser window.

O Hint: In the query, use the DUAL table, and the ERROR column alias.

Oracle 10g: XML Fundamentals 7-23


Practice 7 (continued)
3. Transform the departments XSQL Page into an HTML page.
a. Edit departments.xsql, add a rowset-element attribute to suppress the
<rowset> element, and use row-element to change the tag name of the
<row> elements to department. Delete the comment text surrounding the
<?xml-stylesheet?> processing instruction after the XML declaration
page. Keep the processing instruction and change the file name
YourStylesheet.xsl in the href attribute to departments.xsl (the
stylesheet you created in a previous practice). Save the changes.
b. Run the departments.xsql XSQL page to view the results. Then, close the
browser window.
If you have time:
4. Transform the employees XSQL Page into an HTML page.
a. Edit employees.xsql, and delete the comment text surrounding the
<?xml-stylesheet?> processing instruction, but keep the processing
instruction. Replace the href value of YourStylesheet.xsl with
employees.xsl. Save the changes and run employees.xsql in the
browser to view the results. Do not close the browser window.
b. In the browser, append ?dept_id=60 to the URL, and refresh the browser. Are
the results formatted as expected? Do not close the browser window.
c. In the browser, change the dept_id value of 60 to 140, and press [Enter] to

browser window.
n
d. Edit employees.xsl, add a new template rule for the <error> element by
y
display the results in the browser. Does the page format as expected? Close the
l
using the following template body:
e O
<h3>
<font color="red">
U s
<xsl:value-of select="."/>
</font>
A I
</h3>.
Save the changes to the XSL stylesheet. O
l &
e. Run employees.xsql, and then after appending ?dept_id=140 to the

a
URL, press [Enter] to display the results in the browser. After this is completed,
n
close the browser.

te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 7-24
Additional Features in XSQL Pages

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Use CURSOR expressions in an XSQL query
• Set HTTP session parameters in an XSQL Page
• Set HTTP cookies parameters in an XSQL Page
• Set page-private parameters in an XSQL Page
• Use DML operations in XSQL Pages

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
In this lesson, you learn about the additional features of XSQL Pages. In particular, you
learn how to aggregate data, manage HTTP session and cookie parameter values, set page-

O
private parameters dynamically, and perform DML operations by using an XSQL Page.

l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 8-2
Using CURSOR Expressions

A CURSOR expression:
• Is a column expression with a nested query
CURSOR(subquery)
• Can be used in an XSQL Page to aggregate data
<?xml version="1.0"?>
<xsql:query xmlns:xsql="urn:oracle-xsql"
connection="hr" max-rows="2">
SELECT department_name,
CURSOR(SELECT first_name,last_name
FROM employees e
WHERE d.department_id=e.department_id) EMPLOYEE
FROM departments d
</xsql:query>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using CURSOR Expressions
U s
A I
The CURSOR expression returns a nested cursor, or data output that is nested in the data of
another SQL statement. You can use the CURSOR expression inside the SQL statement of
<xsql:query> to create nested output elements. The example in the slide retrieves each
O
department name and a list of their employee first and last names. A sample output is:
<ROWSET>
l &
<?xml version="1.0" encoding="windows-1252" ?>

<ROW num="1">
n a
<EMPLOYEE>
te r
<DEPARTMENT_NAME>Administration</DEPARTMENT_NAME>

<EMPLOYEE_ROW num="1">

I n
<FIRST_NAME>Jennifer</FIRST_NAME>

c l e <LAST_NAME>Whalen</LAST_NAME>
</EMPLOYEE_ROW>
</EMPLOYEE>

r a </ROW>

O
<ROW num="2">
<DEPARTMENT_NAME>Marketing</DEPARTMENT_NAME>
<EMPLOYEE>...
Note: The max-rows attribute applies to departments, and not the CURSOR
expression.

Oracle 10g: XML Fundamentals 8-3


Exchanging Data with XSQL Parameters

Data in Web application can be exchanged between


the browser and server, or stored by using:
Browser Application server

http://host/page.xsql?parm=val
Cookie: cookieparm=val

Servlet engine
• Page-private
parameters XSQLServlet
XSQL Page XSQL Page
• Cookie
parameters Page-private Page-private

• Session
parameters
HTTP session parameters

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Exchanging Data with XSQL Parameters
U s
the following techniques:
A I
The data for a Web application is exchanged between the browser and server by using one of

O
• Sending HTML form fields to the server with an HTTP request
• Sending cookies in the HTTP request header to the server. Cookies originate from the

l &
server in the HTTP response header to the browser.

a
Alternatively, XSQLServlet in the server can maintain the state data on behalf of a client
n
te r
browser by using an HTTP session. Session tracking is typically managed with cookies to
associate a particular client with its session data. The data values passed between the client

I n
and server, or managed in an HTTP session, can be stored in XSQL parameters. The
following XSQL parameters can be set by using data in form fields, HTTP headers, static
l e
values, or SQL queries:
c
r a
• A page-private parameter, which is visible to the XSQL Page in which it is created
• An HTTP cookie parameter, whose value is added as a cookie in the page response

O header returned to the browser. The cookie value is returned to the server with
subsequent HTTP requests from that browser. A cookie is typically destroyed when the
browser is closed, but survives beyond the browser session if its max-age is set.
• An HTTP session parameter, which stores data in the server memory for the life of the
HTTP session, and can be shared among different XSQL pages in the same server
Oracle 10g: XML Fundamentals 8-4
Setting Page Parameters

• Using static text or other parameters values:


<xsql:set-page-param name="dept_id" value="10"/>
• Using a SQL query:
<?xml version="1.0"?>
<page xmlns:xsql="urn:oracle-xsql"
connection="hr" lname="King">
<xsql:set-page-param name="id">
SELECT employee_id FROM employees
WHERE last_name='{@lname}'
</xsql:set-page-param>
<xsql:query >
SELECT * FROM job_history
WHERE employee_id = {@id}
</xsql:query>
</page>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Setting Page Parameters
U s
A I
The <xsql:set-page-param> action sets a page-private parameter identified by the
name attribute to a value that can be supplied by one of the following:

O
• A combination of static text and other parameter values
• The result of a SQL SELECT statement

l &
Note: The SQL statement option requires a database connection attribute to be defined

n a
on the document root, and obtains its parameter value from the first column in the first row
fetched from the result set.

te r
After a page-private parameter is set, subsequent action handlers can use this value as a
I n
lexical parameter (for example, {@id}) or as a SQL bind parameter value by referencing its

l e
name in the bind-params attribute of an action handler supporting SQL operations.

c
In the second example in the slide, the id parameter value is set to the employee_id

r a
column from the SQL statement. The id parameter is used in the <xsql:query> to

O
retrieve the job history records for that employee with the id value.
Note: A parameter can be set by using an XPath expression, which is evaluated against an
XML document or HTML form that has been posted to the XSQL Page Processor. How to
use this technique is not covered in this course.

Oracle 10g: XML Fundamentals 8-5


Setting Page Parameters (continued)
To set several session parameter values based on the results of a single SQL statement, use
the names attribute with a value containing a space-or-comma-delimited list of one or more
parameter names. For example:
<xsql:set-page-param names="id lname dept_id">
SELECT employee_id, last_name, department_id
FROM employees
WHERE first_name = 'King'
</xsql:set-page-param>
In this example, the values from employee_id, last_name, and department_id
columns are assigned to the id, lname, and dept_id parameters, respectively.
Note: In the <xsql:set-page-param> element, either the name or the names
attribute is required. The value attribute and the SQL statement in the body are mutually
exclusive.

n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 8-6
Including Parameters in an XSQL Page

• Include a named parameter by using:


<xsql:include-param name="param-name"/>
• Include HTTP request, cookie, and session
parameters by using:
<xsql:include-request-params/>
• Example:
http://host/page.xsql?id=1&lname=King
<?xml version="1.0"?>
<page xmlns:xsql="urn:oracle-xsql"
connection="hr">
<xsql:set-page-param
name="name" value="{@lname}"/>
<xsql:include-param name="name"/>
<xsql:include-request-params/>
</page>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Including Parameters in an XSQL Page
U s
A I
Use the <xsql:include-param> to include any parameter in your XSQL page as an
XML element with its tag name set to the parameter name and its content containing the
parameter value. The <xsql:include-param> element uses its name attribute select
O
parameter to include. For example, to dynamically create tags from the database:

l &
<xsql:set-page-param name="employee_name">
SELECT last_name FROM employees WHERE employee_id = 100

n
</xsql:set-page-param>
a
te r
<xsql:include-param name="employee_name">
Produces: <employee_name>King</employee_name>

I n
The <xsql:include-request-params/> element produces a complete set of HTTP

l e
request, session, and cookies parameters available to XSQL Page as child elements of a
<request> element. The example in the slide shows a URL request for an XSQL Page
c
r a
and the output, which contains a <name> element for the page-private parameter with the
value King. The page-private parameter is set by using the lexical parameter value lname

O
from the HTTP request. The <xsql:include-request-params/> generates an
element tree showing the id and lname HTTP request parameters, and an empty element
for the cookie and session parameters, which do not exist. An XSLT stylesheet can
transform included parameter elements to return context values received from a previous
request.
Oracle 10g: XML Fundamentals 8-7
Including Parameters in an XSQL Page (continued)
If the XSQL Page has request, session, and cookie parameters defined, the
<xsql:include-request-param/> action element produces the following
<request> element tree structure in the output results:
<request>
<parameters>
<param1>value1<param1>
<param2>value1<param2> ...
</parameters>
<session>
<parameters>
<name1>value1<name1>
<name2>value1<name2> ...
</parameters>
</session>
<cookies>
<parameters>
<cookiename1>value1<cookiename1>
<cookiename2>value1<cookiename2>...
</parameters>
</cookies>
</request>
Note: The <xsql:include-request-param/> action element does not output the
page-private parameter values. For example, the XSQL Page:
<?xml version="1.0"?>

y
<page xmlns:xsql="urn:oracle-xsql">
<xsql:set-cookie name="page_number" value="1"/>
<xsql:set-session-param name="sess1" value="logged in"/>
n l
<xsql:include-request-params/>
</page>
e O
U s
After refreshing a browser a second time by using a URL similar to:
http://host:port/code_08_23_n.xsql?id=1&lname=King, the result is:
<?xml version = '1.0'?>
<page>
<request> A I
<parameters>
O
<lname>King</lname>
<id>1</id>
l &
</parameters>
<session>
n a
</session>
te r
<sess1>logged in</sess1>

I n
<cookies>
<page_number>1</page_number>

c l e<JSESSIONID>
C0a80101231c8b0fb760514940b2bccca9aa3dda7898

r a </JSESSIONID>
</cookies>

O </request>
</page>
Note: From this output example, you can see that the XSQLServlet associates a client by
an automatically generated cookie called JSESSIONID, which is created when the session
variables are set for the client.
Oracle 10g: XML Fundamentals 8-8
Setting HTTP Cookie Values

• Using static text or other parameter values:


<xsql:set-cookie name="email_id" value="SKING"/>
• Using a SQL query:
<?xml version="1.0"?>
<page xmlns:xsql="urn:oracle-xsql"
connection="hr">
<xsql:set-cookie name="counter"
ignore-empty-value="yes">
SELECT counter.nextval FROM dual
</xsql:set-cookie>
<xsql:include-param name="counter"/>
</page>
Page
Request
1 2 3

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Setting HTTP Cookie Values
U s
A I
The first example in the slide sets a cookie called email_id to the text value SKING. The
second example uses an Oracle database sequence to set the cookie called counter.

O
Note: The numbers 1,2, and 3 at the bottom of the slide show results for the first, second,

l &
and third invocation of the XSQL Page setting the cookie. The Oracle database sequence
object must first be created by using the statement: CREATE SEQUENCE counter;

n a
The <xsql:set-cookie> action element creates a cookie parameter value that can be

te r
maintained for or across HTTP sessions. A cookie is sent to a browser in the HTTP
response. The browser stores the cookie and returns it in an HTTP request. By default, a

I n
cookie value persists for the life of the browser session. However, the cookie life can be
extended beyond the browser session by specifying the optional max-age attribute in units
l e
of seconds. Other useful <xsql:set-cookie> attributes are:
c

r a
only-if-unset: The value yes indicates that the cookie value must be set if it is
not present (the default) whereas the value no indicates that the cookie is prevented

• O from being set if it is present.


ignore-empty-value: The value yes indicates that the cookie is not set if it is an
empty string. The value no indicates that the cookie will be set to an empty string.
Note: Cookies are part of the HTTP protocol. So, the <xsql:set-cookie> action is
effective only if the XSQL page is processed by the XSQLServlet.
Oracle 10g: XML Fundamentals 8-9
Setting HTTP Session Variables

• Using static text or other parameter values:


<xsql:set-session-param name="id" value="100"/>
• Using a SQL query:
<?xml version="1.0"?>
<page xmlns:xsql="urn:oracle-xsql"
connection="hr">
<xsql:set-session-param name="email_id"
bind-params="emp_id" ignore-empty-value="yes">
SELECT email FROM employees
WHERE employee_id = ?
</xsql:set-session-param>
<xsql:include-request-params/>
</page>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Setting HTTP Session Variables
U s
A I
HTTP session variables are created by using the <xsql:set-session-param> XSQL
action element. The life or duration of HTTP session variables is defined by the

O
XSQLServlet configuration by using a specified session inactivity timeout period.

l &
The first example in the slide sets a session variable id to the static text value 100. The
second example uses a SQL query to obtain the session variable email_id whose value is

n a
obtained from the email column for an employee with a specified emp_id. If the

te r
emp_id bind parameter is not set, then the ignore-empty-value setting of yes
prevents the creation of the session variable until a valid emp_id value is provided for the

I n
query condition by using the URL request or by setting the emp_id value in other ways.

l e
If you execute XSQL Page for the first time without URL parameters, the output result is:

c
<?xml version="1.0" ?>

r a<page>
<request>
O <parameters/>
<session/>
<cookies/>
</request>
</page>
Oracle 10g: XML Fundamentals 8-10
Setting HTTP Session Variables (continued)
If you append the text ?emp_id=100 to the URL, the output result is:
<?xml version="1.0" ?>
<page>
<request>
<parameters>
<emp_id>100</emp_id>
</parameters>
<session>
<email_id>SKING</email_id>
</session>
<cookies>
<JSESSIONID>
c0a80101231cf8eb8d283a0348bdadb2bb25aa79a175
</JSESSIONID>
</cookies>
</request>
</page>
Note: The example here shows that the XSQLServlet automatically creates a cookie called
JSESSIONID, which is created when the session variable email_id is created. The
format of the JSESSIONID has been altered for appearance in this page. The servlet tracks
an HTTP session for a browser by using the JSESSIONID cookie value and discards the

n l y
session variable after the timeout period that can be configured for the XSQLServlet.

e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 8-11
Aggregating Information

• Group with results from another XSQL Page uses:


<xsql:include-xsql href="url"/>
• Example: Including job history
<?xml version="1.0"?> jobhistory.xsql
<xsql:query xmlns:xsql="urn:oracle-xsql"
connection="hr" id="101"
rowset-element="JOB_HISTORY" row-element="JOB">
SELECT * FROM job_history WHERE employee_id={@id}
</xsql:query>
<?xml version="1.0"?>
<EMPLOYEE xmlns:xsql="urn:oracle-xsql"
connection="hr">
<xsql:query max-rows="10" id="101"
rowset-element="" row-element="">
SELECT * FROM employees WHERE employee_id={@id}
</xsql:query>
<xsql:include-xsql href="jobhistory.xsql"/>
</EMPLOYEE>
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Aggregating Information
U s
A I
Using the <xsql:include-xsql> action makes it very easy to include the results of
one XSQL Page into another page, enabling you to easily aggregate content from pages

O
previously built and repurpose it. The <xsql:include-xsql> element provides the
following attributes:

l &
href specifies a relative or absolute URL of the XSQL Page to be included.

n a
reparse indicates that the output of the included XSQL Page must be reparsed

te r
before it is included, if set to yes. The default value is no.
The example in the slide illustrates one of the most common uses of <xsql:include-

I n
xsql>, which aggregates the job history information with the information about an

c l e
employee. An id value supplied as an HTTP request parameter is used in both pages.
If a page being aggregated contains an <?xml-stylesheet?> processing instruction,

r a
then that stylesheet is applied before the result is aggregated. So, by using
<xsql:include-xsql>, you can also easily chain the application of XSLT stylesheets
O
together. In addition, all the request-level parameters of the page containing the
<xsl:include-xsql> element are visible to the included page. This includes session-
level parameters and cookies, if processing is performed by the XSQLServlet.
Note: The aggregating page’s page-private parameters are not visible to the page included.
Oracle 10g: XML Fundamentals 8-12
Including External Well-Formed XML

• From a URL reference:


<xsql:include-xml href="url"/>
• From the first row of a single-column query:
<xsql:include-xml>
SELECT column_with_XML FROM table_name
</xsql:include-xml>
• Example of using URL and query:
<hrworld xmlns:xsql="urn:oracle-xsql"
connection="hr">
<xsql:include-xml href="regions.xml"/>
<xsql:include-xml>
SELECT &apos;&lt;country&gt;&apos;||
country_name||
&apos;&lt;/country&gt;&apos;
FROM countries
</xsql:include-xml>
</hrworld>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Including External Well-Formed XML
U s
A I
The <xsl:include-xml> action element can be used to include the contents of any
XML page from a relative or absolute URL reference, or a single-column query. XSL

O
stylesheet processing instructions in the included data are ignored.
If you use the URL form, then the URL may reference static files, as shown in the example

l &
in the slide, or even a dynamic XML document created from a variety of sources, such as

a
servlet, JSP page, Active Server Pages (ASP), an XSQL Page, and many others.

n
te r
If you use a single-column query, then a database connection attribute must be defined
in the root element of the XSQL Page. The queried column must contain the well-formed
XML data. The query in the example in the slide obtains plain text in the country_name

I n
column from the first row of the countries table. The query must concatenate a start tag

c l e
and an end tag around the column data to produce a well-formed XML structure. XSQL
Page is an XML document requiring the literal text in the SQL query to XML entity

r a
references (&apos; for single-quote, &lt; for <, and &gt; for >.) This is tedious;
therefore, it is preferable to store the XML data in the column value, ideally defined as a
O
CLOB or XMLType column.
Note: The results of the XML resource included by the <xsql:include-xml> action
element must be a well-formed XML; otherwise, you get an <xsql-error> element. The
XML/SQL functions, discussed in the lesson titled “Generating XML from an Oracle
Database10g,” provide a cleaner way to generate XML.
Oracle 10g: XML Fundamentals 8-13
Results of Including XML

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Results of Including XML
U s
A I
The XSQL Page output results in the slide show the included XML elements generated by
the XSQL Page actions from the section titled “Including External Well-Formed XML.” The
output results generated are:
O
1. The XML elements between the <regions> and </regions> elements inclusive,

l &
are generated as a result of the following XSQL action:
<xsql:include-xml href="regions.xml"/>
a
Note: The XSLT stylesheet referenced by the regions.xml file is not included or
n
processed.

te r
2. The <country>Argentina</country> element is the result of the following
XSQL action:
I n
<xsql:include-xml>

le
SELECT &apos;&lt;country&gt;&apos;||

c country_name||

r a &apos;&lt;/country&gt;&apos;
FROM countries

O </xsql:include-xml>
Note: The value from the first row for the SELECT statement is used, with or without
a WHERE clause. However, if a WHERE clause is used and no rows are found, an
<xsql-error> element is inserted in the output tree. For example:
<xsql-error action="xsql:include-xml"/>

Oracle 10g: XML Fundamentals 8-14


Data Manipulation by Using XSQL

• To execute DML or DDL statements, use:


<xsql:dml>
DML or DDL statement
</xsql:dml>
• Example:
<?xml version="1.0"?>
<page xmlns:xsql="urn:oracle-xsql"
connection="hr" id="5" name="North Pole">
<xsql:dml>
INSERT INTO regions VALUES ({@id},'{@name}')
</xsql:dml>
<xsql:query>
SELECT * FROM regions WHERE region_id = {@id}
</xsql:query>
</page>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Data Manipulation by Using XSQL
U s
The <xsql:dml> action element can be used to execute:

A I
• DML statements, such as INSERT, UPDATE, MERGE, and DELETE statements
• A PL/SQL block, which can call stored procedures
O
l &
• DDL statements, such as CREATE TABLE, CREATE SEQUENCE, and others
Database constraints and privileges are enforced, and <xsql:error> is returned if any

n a
are violated. Like any XSQL page, parameters may be used with the <xsql:dml>

te r
element. However, use parameters in <xsql:dml> elements with caution as a request may
contain damaging DDL commands. For example:

I n
<page xmlns:xsql="urn:oracle-xsql" connection="hr">

e
<xsql:dml>{@statement}</xsql:dml>

l
</page>
c
r a
This allows the following request to drop the customers table from the database:
http://host:port/dml.xsql?statement=drop+table+customers

O
where the + denotes a space in the URL. The example in the slide is less problematic
because the INSERT statement has a specific structure.

Oracle 10g: XML Fundamentals 8-15


Results of DML: Example

Success!

Constraints
enforced

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Results of DML: Example
U s
A I
The slide shows the results for two examples of inserting a row in the REGIONS table by
using an XSQL Page. The first time the XSQL Page is executed, without any HTTP request

O
parameters, the default values of 5 and North Pole are assigned to the id and name

l &
lexical parameters in the <xml:dml> operation. In this case, the insert is successful with
the <xsql-status> element indicating that one row was affected:
a
<xsql-status action="xsql:dml" rows="1" />
n
te r
The second time the DML operation is performed, the id value of 5 is reused with a name
value of Pacific+Rim passed in as request parameters. The XML results returned

I n
indicate the integrity violation error in the <xsql-error> element:

e
<xsql-error code="1" action="xsql:dml">

c l
<statement>INSERT INTO regions VALUES (5,'Pacific Rim')

r a </statement>
<message>

O ORA-00001: unique constraint (HR.REG_ID_PK) violated


</message>
</xsql-error>
Note: The layout of the <xsql-error> element has been altered for readability here. The
<ROWSET> element and its descendants are generated by the <xsql:query>.
Oracle 10g: XML Fundamentals 8-16
Posting XML Documents for DML
Operations

An XSQL Page can:


• Receive XML posted from an HTML form text area
• Perform a DML operation by using the posted
XML, optionally transformed to a <ROWSET>
structure
HTML XSQL
2 XSQLServlet <xsql:insert-request/>
<xsql:update-request/>
1 POST… XSQL Page
<xsql:delete-request/>
processor <xsql:insert-param/> 3
XSLT 4
Database
<ROWSET> <!--Canonical Structure-->
<ROW num="1"> 5
<REGION_ID>6</REGION_ID> DML
<REGION_NAME>Pacific</REGION_NAME> Table
</ROW>
</ROWSET> Column names

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Posting XML Documents for DML Operations
U s
A I
XSQL Pages Publishing Framework can accept an XML document posted in the HTTP
request from an HTML form field. The receiving XSQL Page can process the contents of the

O
XML document in a DML operation. The process is illustrated in the slide:
1. The browser presents an HTML form with a text area into which the user enters XML

l &
document elements, and submits the form by using a POST HTTP method.

a
2. The XSQLServlet receives the posted data, which is passed to the XSQL Page
n
te r
processor for use when it executes the request XSQL Page.
3. The XSQL Page can contain one of the following XSQL action elements:
- <xsql:insert-request> to do an INSERT by using XML in a request
I n
- <xsql:update-request> to do an UPDATE by using the request data

c l e
- <xsql:delete-request> to do a DELETE by using the request data
- <xsql:insert-param> to do an INSERT by using XML a parameter

r a
4. Optionally, the XSLT Processor can be invoked by specifying an XSL stylesheet in the
transform attribute to convert the XML input from the HTML form into the
O<ROWSET> element canonical structure, as shown in the slide.
5. The requested DML operation is performed in the database in a table identified by the
table attribute specified in the XSQL DML action element used.
Note: Canonical XML form has elements with column names inside the <ROW> element.
Oracle 10g: XML Fundamentals 8-17
Handling Posted XML Data

Use an XML document in canonical <ROWSET> form to:


• INSERT rows:
<xsql:insert-request table="regions"/>
• UPDATE rows:
<xsql:update-request table="regions"
key-columns="region_id" columns="region_id"/>

• DELETE rows:
<xsql:delete-request table="regions"
key-columns="region_id"/>

• Insert from a HTTP request parameter:


<xsql:insert-param name="xmldata"
table="regions"/>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Handling Posted XML Data
U s
A I
XML SQL Utility (XSU), used by the XSQL Pages Publishing Framework, provides the
ability to perform database inserts, updates, and deletes based on the content of an XML

O
document in “canonical” form with respect to a target table or view.

l &
An XML document in canonical form matches the target table structure by using a
<ROWSET> root element, which contains one or more <ROW> child elements. Each <ROW>

n a
element contains values enclosed in child elements with their tag names that are the same as

te r
the columns in the target database table. For example, the REGIONS table defines two
columns: REGION_ID and REGION_NAME. A canonical XML document with one row for
the REGIONS table is:
I n
e
<ROWSET>

c l
<ROW num="1">

a
<REGION_ID>1</REGION_ID>

O r <REGION_NAME>Europe</REGION_NAME>
<ROW>
</ROWSET>
Given an XML document in this canonical form, the XML SQL Utility can automatically
insert, update, or delete the rows. Using an XSLT, an XML document can be converted into
the canonical form for the target table, as required.
Oracle 10g: XML Fundamentals 8-18
Handling Posted XML Data (continued)
The slide shows four ways of managing posted XML data assumed to be in canonical form:
• The example of <xsql:insert-request> action element inserts the posted XML
data into the REGIONS table identified by the table attribute.
• The <xsql:update-request> action element uses the posted XML data in the
request to update the data in the REGIONS table specified in the table attribute, and
uses the key-columns attribute identify the column, region_id, as the key used
to target the row being updated. The columns attribute specifies the names of
columns being set in the update operation. The key-columns and columns
attributes may contain a space-or-comma-delimited list of column names. For
example, the JOB_HISTORY table contains a composite primary key composed of the
EMPLOYEE_ID and START_DATE columns. Therefore, the corresponding
<xsql:update-request> element is written as:
<xsql:update-request table="job_history"
key-columns="employee_id start_date"
columns="end_date job_id department_id"/>
• The <xsql:delete-request>action element uses the posted XML data to
identify the rows to be deleted, identified by the value in the REGION_ID column
specified in key-columns attribute, and the REGIONS table, specified in the
table attribute.
• The <xsql:insert-param> action element performs an insert operation by using
the XML data posted as the value of the HTTP request parameter called xmldata,
l y
specified by the name attribute, into the REGIONS table identified by the table
attribute. n
O
Note: All the examples in the slide expect the data to be entered in canonical form. If the
e
U s
input data does not conform to the canonical XML structure, then in all of the action
elements shown, add the transform attribute specifying an XSLT stylesheet used to

A I
convert the input document into canonical format for the target table. To see an example of
transforming an input XML document to canonical form, see the section titled
“Transforming XML to Canonical Form.”
O
l &
A database view can be used as the target of the DML operations. However, depending on
the view definition, the INSERT, UPDATE and DELETE operations may need to be
a
managed by their respective INSTEAD OF dml-operation trigger. For example, to
n
te r
perform an INSERT on a view, an INSTEAD OF INSERT trigger can invoke a PL/SQL
procedure to perform a MERGE operation. The MERGE operation is not available for an

I n
Oracle database earlier than Oracle9i. Therefore, the PL/SQL procedure can check for the
existence of a record and intelligently choose whether to perform an INSERT or an
l
UPDATE operation.
c e
r a
O
Oracle 10g: XML Fundamentals 8-19
Transforming XML to Canonical Form

XSQL DML actions use the transform attribute to


convert an XML document to canonical form:
<regions> <-- Input XML data -->
<region>
<id>10</id>
<name>Central America</name>
</region>
</regions> 1

<xsql:delete-request table="regions"
key-columns="region_id"
transform="regions-to-rowset.xsl"/> 2

<ROWSET> <-- Canonical XML -->


<ROW>
<REGION_ID><10</REGION_ID>
<REGION_NAME>Central America</REGION_NAME>
</ROW>
</ROWSET>
n l3
y
Copyright © 2004, Oracle. All rights reserved.

e O
Transforming XML to Canonical Form
U s
A I
An XSQL Page may receive any XML document with a structure that does not use the
canonical form required by the DML action elements. However, you can use the

O
transform attribute to specify an XSLT stylesheet that converts the input elements into

l &
canonical form. The slide shows parts of the process, and the target table structure:
1. The input XML document containing a <regions> element and its descendants

a
2. The XSQL <xsql:insert-request> with the transform attribute using the
n
te r
regions-to-rowset.xsl stylesheet to transform the input XML
3. The XML document transformed to canonical from with this XSL stylesheet:

I n
<?xml version="1.0"?>
<ROWSET xsl:version="1.0"

c l e
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:for-each select="regions/region">

r a <ROW>
<REGION_ID><xsl:value-of select="id"/></REGION_ID>
O <REGION_NAME><xsl:value-of select="name"/>
</REGION_NAME>
</ROW>
</xsl:for-each>
</ROWSET>
Oracle 10g: XML Fundamentals 8-20
Summary

In this lesson, you should have learned how to:


• Use CURSOR expressions in SQL to aggregate data
from multiple tables
• Use HTTP request and session parameters
• Create page-private parameters
• Create cookie parameters
• Include parameter values as XML in the output
• Aggregate data by using references to other XSQL
Pages and external XML content
• Perform DML operations by using XML data in
canonical format

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
Publishing Framework:
A I
In this lesson, you learned about the following additional features of the XSQL Pages

O
• Aggregating data through the use of CURSOR expressions, including XML content

l &
from other XSQL Pages, and including XML from references to external sources
• Creating page-private parameters that can be used in XSQL query and DML
a
operations to target a specific set of rows
n
te r
• Creating cookie values that are stored in the browser and received in HTTP request
headers for use in the XSQL Page operations

I n
• Creating HTTP session parameters that persist for the life of an HTTP session,
controlled by the XSQLServlet engine configuration
l e
• Using XML data structured or transformed into canonical form, which is posted from
c
a
the client and used to insert, update, or delete database data
r
O
Oracle 10g: XML Fundamentals 8-21
Practice 8: Overview

This practice covers the following topics:


• Creating an XSQL Page with a CURSOR expression
• Using page or session parameters for navigation
• If there is time, you can try
– Using cookies to track page hits in a browser
session
– Performing DML operations with XML data posted
from an HTML form

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
r a
O
Oracle 10g: XML Fundamentals 8-22
Practice 8
The goal of this practice is to explore the additional features of XSQL Pages. You create an
XSQL Page by using a CURSOR expression to combine department and employee
information to conform to an XSLT stylesheet. You create page or session parameters to
navigate between department rows. You use an existing HTML form to post XML data for
inserting, updating, and deleting rows in the COUNTRIES table. If you have time, add
cookies to track the number of page hits in a browser session.
1. Create an XSQL Page to display a department and its employees, and use a supplied
XSLT stylesheet to transform the results.
a. In the XMLLabsProject, create a new XSQL Page called
deptandemp.xsql.
b. In deptandemp.xsql, structure the XML output results to display a
department root element containing the department_id,
department_name, and by using a CURSOR expression include the
employees in the department. Inside the employees element, include each
employee with employee_id, last_name, and salary. Ensure that the tag
names are output in lowercase. In the <xsql:query> start tag, define a lexical
parameter dept_id with a default value of 10 that you use in the condition of
the query to display the department with the specified ID.
Hint: The XML output tree must contain the following structure:
<department>
<department_id>...</department_id>
<department_name>...<department_name>
<employees>
n l y
<employees_row num="n">
<employee_id>...</employee_id>
e O
<last_name>...</last_name>
<salary>...</salary>
U s
</employees_row>
:
A I
</employees>
O
</department>

l &
c. Check the XML syntax, fix any syntax errors, and save the changes to
a
deptandemp.xsql. Run deptandemp.xsql to confirm whether the XML
n
te r
output has the correct structure. Modify the XSQL Page until it produces the
correct output, if required.

I n
d. Add the E:\labs\lab\deptandemp.xsl XSLT stylesheet file to
XMLLabsProject. Edit deptandemp.xsql, and add an <?xml-

l e
stylesheet?> processing instruction to transform the results of the
c
deptandemp.xsql page output.
r a
e. Run deptandemp.xsql and view the transformed results in the browser. Test

O the application with the HTTP parameter dept_id set to a value of 60 and then
300.

Oracle 10g: XML Fundamentals 8-23


Practice 8 (continued)
2. The deptandemp.xsl stylesheet provides support for navigation between
department records in the HTML page. However, the XSQL Page must calculate
values for and include XML elements that are used to create the Next and Previous
buttons in the HTML page. You write queries to set page or session parameters to the
next and previous department_id, with respect to the current dept_id lexical
parameter value. The page or session parameter values are created as child elements of
a <page_navigation> element that must be added.
a. Edit the XSQL Page deptandemp.xsql, and move the dept_id="10"
default lexical parameter and value from the <xsql:query> element into the
start tag of the <department> root element.
b. In the deptandempl.xsql page, after the start tag of the <department>
root element, add the XSQL element to set a page or session parameter called
previous_id, whose value is calculated by using the following SQL
statement (which can be copied from the
E:\labs\lab\lab_08_02_b.txt file):
SELECT NVL(MAX(department_id),0) previous_id
FROM departments
WHERE department_id &lt; (SELECT department_id
FROM departments
WHERE department_id = {@dept_id})
c. In deptandemp.xsql, after setting the previous_id session parameter,

l
add another XSQL element to a page or session parameter called next_id,

n y
whose value is calculated from the following SQL statement (which can be
copied from the E:\labs\lab\lab_08_02_c.txt file):
SELECT NVL(MIN(department_id),0) next_id
e O
FROM departments

U s
WHERE department_id &gt; (SELECT department_id
FROM departments

A I
WHERE department_id = {@dept_id})

O
d. In deptandemp.xsql, before the end tag of the root element (the
</departments> tag), add the start and end tags for an XML element called

l &
<page_navigation> (in lowercase). Inside the body of the

a
<page_navigation> element, add the XML child elements for the
n
te r
previous_id and next_id page or session parameters and values by using
the <xsl:include-param> XSQL action element.

I n
e. Ensure that the XML syntax of deptandemp.xsql is well-formed, and save
the changes to the file. Run deptandemp.xsql to view how the XSL

l e
transformation changes the appearance of the HTML Page, which should now
c
include a Next button. Test the HTML page functionality by clicking the Next

r a
and Previous buttons.

O Note: The Previous button appears after you navigate to the next department,
and disappears when you are at the first department. The Next button disappears
when you reach the last department record in the set.

Oracle 10g: XML Fundamentals 8-24


Practice 8 (continued)
If you have time…
3. Use a cookie in deptandemp.xsql to track the number of times the XSQL Page is
requested in a browser session. The XSL template produces a hit count when you
include a cookie parameter in the <page_navigation> element.
a. Edit deptandemp.xsql, by adding an attribute called counter set to the
value 1 in the document root element.
b. In deptandemp.xsql, after the start tag of the document root, use the XSQL
set cookie action to create a cookie named counter whose value is set by using
the following SQL statement:
SELECT TO_NUMBER(NVL('{@counter}','1'))+1
FROM dual
c. In deptandemp.xsql, in the <page_navigation> element, include the
counter cookie parameter as the last child element. Check the XML syntax for
the page and save the changes when errors have been eliminated.
d. Run deptandemp.xsql. Notice that the Page Hit count line, which appears
under the page heading, increments each time you click the Next or Previous
buttons.
Note: You can look at the template rule for the document root in the
deptandemp.xsl stylesheet and see the XSL elements that conditionally
include the Page Hit count.
4. Use the country_form.html file provided to submit the country data to be
l y
inserted, updated, and deleted from the COUNTRIES table. You use and modify the
n
XML data in the form to send to XSQL Pages to insert, update, delete or query country

the form. The query functionality has been provided.


e O
rows. In this task, you create the XSQL Pages to perform the DML operations behind

s
a. In the XMLLabsProject, from the E:\labs\lab directory, add the
U
A I
country_dml.html, country-list.xsql, and country-list.xsl
files. Briefly, examine the source of each file, which form the basis of a country

O
maintenance Web application. Run the application by right-clicking
country_dml.html and selecting Run.

l &
Note: The Insert XML, Update XML, and Delete XML buttons will not work

a
because the XSQL Pages for their functionality need to be created.
n
te r
b. In the Country Web Application browser window, click List Countries to
display a list of countries. Observe that the country South Africa is not

I n
present in the existing database data. Close the browser window.
c. In the XMLLabsProject, create an XSQL Page called country-

l e
insert.xsql, and add the instruction to insert the XML data into the
c
COUNTRIES database table. Check the XML syntax, and save the file when

r a
there are no errors.

O Note: The source data is in canonical form; therefore, an XSLT is not required.
Remember to include the connection attribute in the document element.

Oracle 10g: XML Fundamentals 8-25


Practice 8 (continued)
d. In the XMLLabsProject, create an XSQL Page called country-
update.xsql, and add the instruction to update the XML data in the
COUNTRIES table. Specify country_id in the key-columns attribute, and
specify "country_name,region_id" as the value of the columns
attribute. Add the connection attribute. Check the XML syntax, and save the
file when there are no errors.
e. In the XMLLabsProject, create an XSQL Page called country-
delete.xsql, and add the instruction to delete the XML data from the
COUNTRIES table. Specify the key-columns attribute with the
country_id value. Add the connection attribute. Check the XML syntax,
and save the file when there are no errors.
f. Right-click country_dml.html in the Navigator or Editor, and click Run.
g. Click Insert XML. What is the response? Clear the alert window by clicking
Ok. To confirm whether the new country record has been inserted, enter ZA in
the Country Id: field at the bottom of the page, and then click Find…. Click
Back to return to the country HTML form page.
h. In the form XML text area, modify the text value of the <COUNTRY_NAME>
element to be Southern Africa. Click Update XML. What is the response?
Clear the alert window by clicking Ok. To confirm whether the country record
has been updated, enter ZA in the Country Id: field at the bottom of the page,
and then click Find…. Click Back to return to the country form page.
l y
i. In the country HTML form, click Delete XML. What is the response? Clear the
n
alert window by clicking Ok. To confirm whether the country record has been

e O
deleted, enter ZA in the Country Id: field at the bottom of the page, and then
click Find…. Click Back to return to the country form page. Close the browser
window.
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 8-26
Introduction to Oracle XML DB (XML DB)

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• List the XML features in the database
• Explain the architecture of the Database XML
components
• List the benefits of the XML components
• Register an XML Schema in the database

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
learn about using XMLType, and XML Schema and Repository.
A I
In this lesson, you learn about Oracle XML DB (XML DB) and its components. You also

O
Reference: For more information, refer to Oracle10g XML Database Developer’s Guide-
Oracle XML DB.
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 9-2
What Is Oracle XML DB?

Oracle XML DB:


• Is a high-performance XML storage and retrieval
technology
• Provides standard access methods for navigating
and querying XML
• Is a merge of XML and relational database
technology

Repository XMLType

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
What Is Oracle XML DB?
U s
A I
Oracle XML DB is a high-performance XML storage and retrieval technology available
with the Oracle10g server. It fully absorbs the W3C XML data model into the Oracle server,

O
and provides standard access methods for navigating and querying XML. With Oracle XML

same time. Oracle XML DB:


l &
DB, you get all the advantages of relational database technology and XML technology at the

a
• Is a native XML database, enabling you to build standards-based XML applications
n
and implementations

te r
• Provides a storage-independent, content-independent, and programming language-

I n
independent infrastructure to manage data. Although it is closely integrated with the
Oracle SQL engine, it introduces newer concepts never before present in relational

l e
databases. For example, it builds XML Document Object Model (DOM) into the

c
Oracle kernel so that most of the operations on the XML data can be performed as a

r a
part of regular database processing.
• Is designed to store and retrieve XML objects by using relational and hierarchical
O access APIs, and provides fine access control and configuration management for the
XML objects
• Implements popular protocols such as FTP, HTTP, and WebDAV to improve data
access performance, designed around open standards and implemented to provide
different views and intuitive access to a single repository
Oracle 10g: XML Fundamentals 9-3
When to Use Oracle XML DB

• You can use Oracle XML DB to perform the


following:
– Unify data and content
– Achieve faster storage and retrieval of complex
XML documents
– Integrate applications
• You can use XMLType views when your data is not
XML.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
When to Use Oracle XML DB
U s
Unifying Data and Content with Oracle XML DB

A I
Most application data and Web content is stored in a relational database or a file system, or a
O
combination of both. When stored in relational storage, XML loses DOM fidelity.

l &
Nowadays, structured data is moving to XML for transport and on the Internet to add
structure to the contents. Data is becoming more semistructured. As the volume of XML

n a
transported grows, the cost of regenerating these XML documents grows and these storage

te r
methods become less effective at accommodating XML content. With Oracle XML DB, you
have enhanced native support for XML.

I n
With Oracle XML DB, you can store and manage both structured, unstructured, and pseudo-

l e
or semistructured data, using a standard data model, and standard SQL and XML. You can

c
store structured data in structured storage such as tables and columns, and unstructured data

r a
in large objects (LOB). By using Oracle XML DB, you have complete transparency and

O
interchangeability between XML and SQL. Oracle XML DB enables you to perform:
• XML operations on structured (such as table) data
• SQL operations on XML documents

Oracle 10g: XML Fundamentals 9-4


When to Use Oracle XML DB (continued)
Faster Storage and Retrieval of Complex XML Documents
Users today face a performance barrier when storing and retrieving complex, large, or many
XML documents. Oracle XML DB provides very high performance and scalability for XML
operations. The major performance features are:
• Native XMLType
• The lazily evaluated virtual DOM support
• Database-integrated ad hoc XPath and XSLT support
• XML Schema-caching support
• CTXPATH Text indexing
• The hierarchical index over the Repository
Integrate Applications
With Oracle XML DB, you can access data from disparate systems through gateways and be
able to combine them into one common data model. This reduces the complexity of
developing applications that must deal with data from different stores.
When Your Data Is Not XML
XMLType views provide a way for you to wrap existing relational and structured data in
XML format. This is especially useful if, for example, your legacy data is not in XML but
you need to migrate to an XML format. Using XMLType views, you do not need to alter
your application code. To use XMLType views, you must first register an XML Schema
with annotations that represent the bidirectional mapping from XML to SQL object types
and back to XML. An XMLType view conforming to this schema (mapping) can then be

n l y
created by providing an underlying query that constructs instances of the appropriate SQL
object type.
Support for DOM Fidelity
e O
U s
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. All

A I
elements and attributes declared in the XML Schema are mapped to separate attributes in the
corresponding SQL object type. Some information are not represented directly by these
O
element or attributes. To assure the integrity and accuracy of this data, when regenerating

DOM fidelity.
l &
XML documents stored in the database, Oracle uses a data integrity mechanism, called

n a
DOM fidelity refers to how identical the returned XML documents are compared to the

te r
original XML documents, particularly for purposes of DOM traversals.
XMLType achieves DOM fidelity by maintaining information that SQL or Java objects

I n
normally do not provide for, such as:

c l e
• The ordering of child elements and attributes
• Unstructured content declared in the Schema

r a
• Undeclared data in instance documents, such as processing instructions, comments,
and namespace declarations
O
• Support for basic XML data types not available in SQL (Boolean, QName, and others)
• Support for XML constraints (facets) not supported directly by SQL

Oracle 10g: XML Fundamentals 9-5


How Is Oracle XML DB Implemented?

Repository XMLType

Folders Access control

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
How Is Oracle XML DB Implemented?
U s
Oracle XML DB Key Components
A I
The XMLType provides a native XML storage and retrieval capability in the database
O
because it is strongly integrated with SQL. XML data, including XML Schema definition
&
files, can be stored in XMLType columns and tables. The physical storage of the XML data
l
a
can be in LOBs, object-relational (O-R) structures, or a hybrid of LOBs and O-R structures.

n
te r
Oracle XML DB Repository (XML Repository) provides foldering, access control,
versioning, and other services, for XML resources. XML Repository:

I n
• Enables the creation of folders forming a “file system” structure in the database
• Stores data resources (database objects), such as XML, XSL, and XML Schema

l e
documents, in folders
c
• Can be used for fast access and manipulation of XML content, based on path names to

r a
the XML data stored in the database

O
XML Repository can be accessed by using Internet protocols, such as WebDAV, FTP and
HTTP, and is as fast as accessing data from any file system.

Oracle 10g: XML Fundamentals 9-6


Oracle XML DB: Features

Feature Benefit
XMLType Combines SQL and XML features
XML Schema Constrains XML documents to
registered XML Schemas
DOM Fidelity Preserves integrity of documents

XML Schema storage Provides structured storage to


store XML
XML Schema Validation Provides Schema-compliant
document structure
XML Piecewise update Updates individual elements

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Oracle XML DB: Features
U s
A I
XMLType is a native data type used to store and manipulate XML. Multiple storage options,
such as character large object (CLOB) and structured storage, are available with the

O
XMLType. Administrators can choose a storage option that meets their requirements. The

l &
CLOB storage option is unstructured and retains the original XML document. The structured
XML storage option is a “shredded” decomposition of XML into underlying table and
a
column structures (automatically created and managed by Oracle) for better SQL query and
n
te
XML data it contains, such as:r
manipulation performance. With XMLType objects, you can perform SQL operations on the

I n
• Queries, online analytic processing (OLAP) functions, and SQL/XML operations
• XPath searches and XSL Transformations (XSLT)

c l e
You can build regular SQL indexes or Oracle Text indexes on XMLType for high

a
performance of queries in a very broad spectrum of applications.
r
O
XPath search syntax can be used, embedded in an SQL statement or as part of an HTTP
request, to query XML content in the database. XPath expressions can be used to specify
parts of your document when you create XML indexes for XPath searches, for fast access to
content in XML documents.

Oracle 10g: XML Fundamentals 9-7


Oracle XML DB: Features

Feature Benefit

XPath Search Provides XPath syntax for


querying
XML Indexes Enable faster access to
documents
SQL/XML operators Provide ANSI SQL/XML support
XML Transformations Transform XML documents using
XSLT
PL/SQL interface Enables access and manipulation
of data
XML Views Offer views over relational data
or fragments

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Oracle XML DB: Features (continued)
U s
SQL/XML Operators

A I
Several new SQL member functions, based on the emerging ANSI SQL/XML standard, can

O
be used in queries to easily generate XML content. For example, the XMLElement()

XSL Transformations for XMLType


l &
function can be used to generate an XML element that contains database data.

a
Use XSLT to transform XML documents through a SQL operator. These XSL
n
PL/SQL Interface
te r
transformations provide high performance because they are database-resident.

I n
Use DOM and other APIs for accessing and manipulating XML data. You can get static and

XMLType Views
c l e
dynamic access to XML.

r a
You can create XMLType views to create permanent aggregations of various XML
document fragments or relational tables. You can also create views over heterogeneous data
O
sources by using Oracle Gateways.

Oracle 10g: XML Fundamentals 9-8


Oracle XML DB: Features

Feature Benefit
Schema caching Minimizes access time
XML generation Provides high-performance
generation of XML
Oracle XML DB Enables foldering;
repository Provides security by using
access control lists (ACLs);
Provides storage for
resources

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Oracle XML DB: Features (continued)
U s
A I
Oracle XML DB Schema caching maintains structural information for registered XML
Schema documents, such as element names, data types, and storage locations. The Schema

O
cache minimizes access time and storage costs to the XML Schema.

l &
XML generation is possible by using XML/SQL functions such as SYS_XMLGEN and
SYS_XMLAGG, which provide native, high-performance generation of XML from SQL

n a
queries. Oracle XML DB provides functions that conform with ANSI/ISO SQL/XML

te r
standard, such as, the XMLElement() function. SQL/XML functions are used to create an
XML documents or fragments containing data from columns in an SQL query.

I n
As previously discussed, Oracle XML DB Repository can be used for foldering whereby

l e
you can view XML content stored in Oracle XML DB as a hierarchy of directory-like

c
folders. The repository supports access control lists (ACLs) for any XMLType object.

r a
O
Oracle 10g: XML Fundamentals 9-9
XMLType

An XMLType:
• Is a native object data type
• Can be used as the data type for a column, and
object table
• Stores XML content
• Provides a SQL API with member functions that
operate on XML data

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XMLType
U s
XMLType:
• Is a native data type that stores XML content
A I
O
• Can be used as the data type of a column in a table or view, or an object table

l &
• Can store any content, but is designed optimally to store XML content
• Can be used in PL/SQL stored procedures as parameters, return values, and variables
a
• Represents an XML document as an instance of XMLType in SQL
n
te r
• Provides a SQL API framework that has built-in member functions that operate on
XML content. For example, you can use XMLType functions to create, extract, and

I n
index XML data stored in an Oracle database 10g.
• Provides its functionality through a set of APIs available to PL/SQL, Java, C++, and C

c l e
Using the above capabilities of XMLType, SQL developers can leverage the power of the

r a
relational database while working in the context of XML. Similarly, XML developers can
leverage the power of XML standards while working in the context of a relational database.
O
Oracle 10g: XML Fundamentals 9-10
When to Use XMLType

You can use XMLType to:


• Query against XML data
• Take advantage of structure when you have a
schema
• Provide efficient XPath access
• Shield applications from storage models
• Prepare for future optimizations
• Provide structured storage with DOM fidelity

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
When to Use XMLType
U s
Use XMLType to use:

A I
• SQL queries on part of or the whole document. The extract() and

O
existsNode() functions provide the necessary functionality to query XML
documents.

l &
• Strong types inside SQL statements and PL/SQL functions. Strong typing ensures that
a
values passed are XML values and not any arbitrary text strings.
n
te r
• The XPath functionality provided by extract() and existsNode() functions to
work on your XML document

I n
• Indexes with XPath searches on documents. XMLType provides member functions
used to create functional indexes for optimized searches.

c l e
Note: XMLType uses the built-in C XML Parser and processor and, therefore, provides

a
better performance and scalability when used inside the server.
r
O
By using XMLType instead of standard CLOB or relational storage, applications can
accommodate various storage alternatives while minimizing changes to SQL statements in
the application. Normally, storing XML data in tables and columns causes DOM fidelity to
be lost. Oracle XML DB provides a mechanism to combine the benefits of structured storage
while preserving DOM fidelity.
Oracle 10g: XML Fundamentals 9-11
XML Schema Support in Oracle
Database 10g

DBMS_XMLSchema

Local Global
schema schema

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Schema Support in Oracle Database 10g
U s
following tasks:
A I
Oracle Database 10g provides XML Schema support whereby you can perform the

O
• Register any World Wide Web Consortium (W3C)-compliant XML Schema
• Validate your XML documents against registered XML Schema definitions
• Register local and global XML Schemas
l &
• Generate XML Schema from object types
n a
te r
• Reference an XML Schema owned by another user
• Explicitly reference a global XML Schema when a local XML Schema exists with the
same name
I n
• Generate a structured database mapping from your XML Schemas during XML

c l e
Schema registration. This includes generating SQL object types, collection types, and
default tables, and capturing the mapping information by using XML Schema

r a
attributes.
• Specify a particular SQL type mapping when there are multiple legal mappings
O
• Create XMLType tables, views, and columns based on registered XML Schemas
• Perform manipulation (data manipulation language) and queries on XML Schema-
based XMLType tables
• Automatically insert data into default tables when Schema-based XML instances are
inserted into Oracle Database 10g repository by using FTP or HTTP, or SQL
Oracle 10g: XML Fundamentals 9-12
XML Schema Support in Oracle
Database 10g

• Creating schema-based XML tables


• Creating constraints on XML tables
• Querying and DML on XML tables
• Oracle Schema annotations
• Generating SQL types

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Schema Support in Oracle Database 10g (continued)
U s
Creating Schema-Based XML Tables

A I
You can create XMLType tables based on the XML Schema that has already been
O
registered. Hidden columns are created corresponding to the object type to which the

l &
primary key element has been mapped. In addition, an XMLExtra object column is created
to store the top-level instance data such as namespaces declarations, and so on.

n
Creating Constraints on XML Tables a
te r
You can create unique and referential integrity constraints on Schema-based XMLType

documents. I n
tables. The constraints are enforced every time a change is made to the stored XML

l e
Querying and Manipulating Using XML Tables
c
r a
New instances can be inserted into an XMLType table. The XMLType table can be queried
by using the XPath-based SQL operators. The query rewrite mechanism rewrites queries
O
involving existsNode and extract operators to access the underlying attribute
columns directly, thereby avoiding construction of the XML followed by subsequent XPath
evaluation.

Oracle 10g: XML Fundamentals 9-13


XML Schema Support in Oracle Database 10g (continued)
Oracle Schema Annotations
Using Oracle XML DB, application developers and database administrators can annotate the
XML Schema because they are given greater control over the set of objects that are
generated from the XML Schema and because of the way in which these SQL objects are
stored in the database. XML Schema annotations can be used to:
• Control the way collections are managed
• Define tablespace usage
• Specify partitioning of tables used to store and manage SQL objects
This makes it possible to fine-tune the performance of Oracle XML DB to meet the needs of
the application. Other annotations can be used to control how simple elements and attributes
are mapped into SQL columns.
Generation of SQL Types
During the Schema registration process:
• Oracle XML DB generates a 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 is mapped to an
attribute of the SQL Object Type

n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 9-14
XMLType and XML Schema

• When creating an XMLType,


you can specify that it:
– Conforms to a
preregistered Schema
– Is stored in object-
relational format by using
a mapping specified in
XML Schema called XML
Schema objects
• XML Schema is registered
by using the
DBMS_XMLSCHEMA package.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XMLType and XML Schema
U s
specify, for example, that:
A I
In Oracle Database 10g, you can create XMLType tables and columns, and optionally

• They conform to a preregistered XML Schema


O
l &
• They are stored in the object-relational format specified by XML Schema
You can also choose to wrap existing relational and object-relational data into XML format
by using XMLType views.
n a
te r
You can store an XMLType object as:
• XML Schema-based objects, which can be are stored as character large objects
I n
(CLOBs), or in object-relational format in tables, columns, and views

l e
• Non-XML Schema-based objects, which are stored as CLOBs

c
Mapping from an XML instance document to object-relational or CLOB storage is defined

r a
by registering your XML Schema in an Oracle database 10g by using the

O
DBMS_XMLSCHEMA package. Registering XML Schema is required before you store XML
Schema-based instance documents. A registered XML Schema is referenced by using its
URL.

Oracle 10g: XML Fundamentals 9-15


XMLType and XML Schema (continued)
Using XML Schema with Oracle XML DB
Oracle XML DB supports the use of the W3C XML Schema in two ways:
• Automatic validation of instance documents
• Definition of storage models
To use a W3C XML Schema with Oracle XML DB, the XML Schema document must be
registered with the database. After 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 XML Schema document
• The URL, which will be used by XML documents specifying conformance with the
XML Schema. The URL is provided in the root element of the instance document by
using one of the following:
- The noNamespaceSchemaLocation attribute
- The schemaLocation attribute as defined in the W3C XML Schema
recommendation
XML Schemas are registered by using methods provided by the DBMS_XMLSCHEMA
PL/SQL package. XML Schemas can be registered as global or local schemas.

n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 9-16
XML Schema Management

• The XML Schema functionality is available through


DBMS_XMLSCHEMA.
• DBMS_XMLSCHEMA supports:
– Schema registration
– Schema generation
– Schema deletion

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
DBMS_XMLSCHEMA
U s
A I
The XML Schema functionality of Oracle Database10g is available through the PL/SQL-
supplied package, DBMS_XMLSCHEMA, which is a serverside component that handles the

O
registration of XML Schema definitions for use by Oracle Database 10g applications.

l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 9-17
Registering an XML Schema

The registerSchema procedure registers an XML


Schema by:
• Associating an XML Schema document with a URL
• Specifying:
– A URL
– An XML Schema document
DBMS_XMLSCHEMA.registerSchema(
'http://www.oracle.com/ord.xsd',
'/home/HR/xsd/ord.xsd',TRUE,TRUE,FALSE,TRUE);

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Registering an XML Schema
U s
A I
The example in the slide registers the XML Schema with the URL specified in the first
parameter, that is, http://www.oracle.com/ord.xsd, which is loaded by FTP into the database

O
before executing this command. The following syntax shows that you can embed the XML
Schema document in the second parameter:
BEGIN
l
DBMS_XMLSCHEMA.registerSchema( &
a
'http://www.oracle.com/emp.xsd',
n
te r
'<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb">

I n
<xs:complexType name="ActionsType"
xdb:SQLType="XDBPO_ACTIONS_TYPE">

c l e <xs:sequence>
<xs:element name="Action" maxOccurs="4"

r a xdb:SQLName="ACTION"
xdb:SQLCollType="XDBPO_ACTION_COLLECTION">

O …
</xs:element>
</xs:schema>');
END;
/

Oracle 10g: XML Fundamentals 9-18


Registering an XML Schema (continued)
The DBMS_XMLSCHEMA package has an overloaded registerSchema procedure that
can be used to register an XML Schema specified as a CLOB, VARCHAR2 or XMLType.
The parameters of this procedure are as follows:
schemaURL: (IN) 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: (IN) A valid XML Schema document
local: (IN) Specifies whether the Schema is local or global. By default, all Schemas are
registered as local Schemas, that is, under /sys/schemas/<username>. If a Schema is
registered as global, it is added under the /sys/schemas/PUBLIC folder for which the
user needs write privileges.
genTypes: (IN) Specifies whether the Schema compiler must generate object types. By
default, this is set to TRUE.
genbean: (IN) Specifies whether the Schema compiler must generate JavaBeans. By
default, this is set to FALSE.
genTables: (IN) Specifies whether the Schema compiler must generate default tables. By
default, this is set TRUE.
force: (IN) Can be set to TRUE or FALSE. If this parameter is set to TRUE, the Schema
registration will not raise errors. Instead, it creates an invalid XML Schema object in case of
any errors. By default, the value of this parameter is FALSE.
owner: (IN) Specifies the name of the database user owning the XML Schema object. By
default, the user registering the Schema owns the XML Schema object. This parameter can
be used to register an XML Schema to be owned by a different database user.
The DBMS_XMLSCHEMA.registerSchema() registers an XMLSchema specified by a
URI name. The parameters are as follows: n l y
schemaURL: (IN) A name that uniquely identifies the Schema document
e O
U s
schemaDocUri: (IN) Specifies the path name (URI) corresponding to the physical
location of the schema document. The URI path can be based on HTTP, FTP, DB or XDB

invokes the registerSchema() function.


A I
protocols. This function constructs a URIType instance by using the URIFactory - and

O
local: (IN) Specifies whether the Schema is local or global. By default, all Schemas are
registered as local schemas, that is, under /sys/schemas/<username/.... If a

l &
Schema is registered as global, it is added under /sys/schemas/PUBLIC/.... The

n a
user needs write privileges on the above directory to be able to register a Schema as global.
genTypes: (IN) Specifies whether the Schema compiler must generate object types. By
default, this is set to TRUE.
te r
genbean: (IN) Specifies whether the Schema compiler must generate JavaBeans. By

I n
default, this is set to FALSE.

l e
genTables: (IN) Specifies whether the Schema compiler must generate default tables. By
default, this is set to TRUE.
c
r a
force: (IN) Can be set to TRUE or FALSE. If this parameter is set to TRUE, the Schema
registration will not raise errors. Instead, it creates an invalid XML Schema object in case of
O
any errors. By default, the value of this parameter is FALSE.
owner: (IN) Specifies the name of the database user owning the XML Schema object. By
default, the user registering the Schema owns the XML Schema object. This parameter can
be used to register an XML Schema to be owned by a different database user.

Oracle 10g: XML Fundamentals 9-19


Storage and Access Infrastructure

• While registering an XML Schema, Oracle


Database 10g performs the following:
– Creates types
– Creates default tables
• This is controlled by arguments to the
registerSchema() function.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Storage and Access Infrastructure
U s
A I
While registering a Schema, Oracle Database 10g also performs the following steps to
facilitate storing, accessing, and manipulation of XML instances that conform to the XML
Schema:
O
l &
1. Creating Types: When an XML Schema is registered, the appropriate SQL object
types are created to enable the structured storage of XML documents conforming to
a
the XML Schema. Use the Oracle Database 10g-defined attributes in the XML Schema
n
te r
documents to control how these object types are generated.
2. Creating Default Tables: As part of the XML Schema registration, Oracle Database

I n
10g generates default XMLType tables for all root elements. You can also specify any
column- and table-level constraints for use during table creation.

c l e
You can control creation of database objects, and suppress their generation by arguments to

r a
the registerSchema()function. For example:
Use xdb:SQLType to specify the name of the SQL type to be generated. Set
O
xdb:defaultTable to the empty string ("") to suppress the creation of the default table
for a particular root element.
You can see the objects created by the registerSchema() function by writing a query
that uses the USER_OBJECTS data dictionary view.
Oracle 10g: XML Fundamentals 9-20
Local and Global XML Schemas

An XML Schema can be registered as:


• Local: Visible only to the owner
• Global: Visible and usable by all
database users

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Local and Global XML Schemas
U s
XML Schemas can be registered as local or global:
• Local XML Schema
A I
O
An XML Schema registered as a local schema is by default, visible only to the owner.
• Global XML Schema

l &
An XML Schema registered as a global schema is, by default, visible and usable by all
a
database users. To register a global schema, a user must be granted the XDB_ADMIN
n
role.

te r
When you register an XML Schema, DBMS_XMLSCHEMA adds an Oracle database resource

I n
corresponding to the XML Schema into the Oracle XML DB repository. The XML Schema

c l e
URL determines the path name of the resource in the Oracle repository.

r a
O
Oracle 10g: XML Fundamentals 9-21
Deleting an XML Schema

• Use the DBMS_XMLSCHEMA.deleteSchema


procedure syntax:
PROCEDURE deleteSchema(
schemaURL IN VARCHAR2,
delete_option IN pls_integer := DELETE_RESTRICT);

• This procedure checks for:


– Appropriate privileges
– Dependents

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Deleting an XML Schema by Using DBMS_XMLSCHEMA
U s
A registered XML Schema can be deleted by using the

A I
DBMS_XMLSCHEMA.deleteSchema procedure. When you attempt to delete an XML
Schema, DBMS_XMLSCHEMA checks whether:
O
• The current user has the appropriate privilege, access control list (ACL), to delete the

l &
resource corresponding to the XML Schema within the repository
• There are any dependents. If there are dependents, it raises an error and the deletion

n a
operation fails. This is referred to as the RESTRICT mode of deleting schemas.


te r
Parameters for the deleteSchema procedure are:
schemaURL: A URL identifying the Schema to be deleted

I n
delete_option: An option for deleting the Schema, whose values are:
- DELETE_RESTRICT: Schema deletion fails if there are any tables or schemas

l e
that depend on this Schema.
c
- DELETE_INVALIDATE: Schema deletion does not fail if there are any

r a
dependencies. Instead, it simply invalidates all the dependent objects.

O - DELETE_CASCADE: Schema deletion will also drop all dependent SQL types
and tables. However, the deletion fails if there are any data in the tables
conforming to this Schema.
- DELETE_CASCADE_FORCE: This is similar to CASCADE, except that it does not
check for any stored data conforming to this Schema. Also, it ignores any errors.
Oracle 10g: XML Fundamentals 9-22
Example of Deleting an XML Schema

EXEC DBMS_XMLSCHEMA.deleteSchema(
'http://www.oracle.com/ord.xsd',
DBMS_XMLSCHEMA.DELETE_CASCADE_FORCE
);

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example of Deleting an XML Schema
U s
CASCADE modes:
A I
The following example deletes the order.xsd XML Schema by using the FORCE and

BEGIN
DBMS_XMLSCHEMA.deleteSchema( O
l &
'http://www.oracle.com/order.xsd',

a
DBMS_XMLSCHEMA.DELETE_CASCADE_FORCE );

n
r
END;

te
/

I n
For more information about this topic, refer to:
• Oracle10g XML API Reference–PL/SQL

l e
• Oracle10g XML Database Developer’s Guide
c
r a
O
Oracle 10g: XML Fundamentals 9-23
Validating XML

Oracle XML DB provides the following methods to


validate XML documents:
• Member functions:
– XMLisValid()
– isSchemaValid()
– isSchemaValidated()
• Member procedures:
– setSchemaValidated()
– schemaValidate()

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Validating XML
U s
A I
It is often necessary to know whether a particular document conforms to a specific XML
Schema, that is, it is valid with respect to a specific XML Schema. By default, the Oracle

O
Database 10g checks to ensure that XMLType instances are well-formed. In addition, for

l &
Schema-based XMLType instances, Oracle Database 10g performs a few basic validation
checks. Because full XML Schema validation (as specified by the W3C) is an expensive
a
operation, when XMLType instances are constructed, stored, or retrieved, they are also not
n
fully validated.

te r
To validate and manipulate the “validated” status of XML documents, several functions and

I n
SQL operator are provided. These functions can be used to check whether the XML

c l e
documents being sent for input to the database conform to specific XML Schemas, that is,
they are “valid.” This is not the same check as that performed by XML Parsers, which check

a
whether the XML documents are well-formed.
r
O
Schema validation in the server uses the same functionality as the XDK Schema validation.
Therefore, if you are using XDK in the middle tier, and then calling
setSchemaValidated(), it is equivalent to validating in the server.
Validating typically applies to XML Schema-based XMLType instances. However, you can
also perform a validation check on unstructured XMLType instances.
Oracle 10g: XML Fundamentals 9-24
Schema Validation

Valid
XML Schema Or
Not valid

isSchemaValid()

XML document

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Schema Validation
U s
A I
IsSchemaValid() member function of XMLType and XMLIsValid() SQL functions
can both be used to determine whether an XMLType instance conforms to the specified
Schema.
O
l &
This function validates the input instance against the target XML Schema and element. If
the Schema is NULL, it validates the instance by using the XML Schema information
specified within the instance.
n a
te r
XMLIsValid()function can also be used in CHECK constraints to ensure that incoming
XML documents are valid.
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 9-25
Schema Validation

XML document setSchemaValidated()

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Schema Validation (continued)
U s
setSchemaValidated()

A I
This procedure marks the XML document as being validated successfully against the

O
Schema specified within it. This is typically used if the XML document has previously been

l &
validated or is guaranteed to be valid in some other fashion, for example, the XML
document has been validated in the middle tier before insertion into the database.
schemaValidate()
n a
te r
This procedure can be used to validate an XML Schema-based XML instance, if it has not
already been validated. This procedure can be used in a database trigger to ensure that only

I n
valid documents are inserted into the table.

c l e
r a
O
Oracle 10g: XML Fundamentals 9-26
Schema Validation

1
XML Schema Or
0

isSchemaValid()

XML document

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Schema Validation (continued)
U s
A I
The XMLType isSchemaValidated() function returns the NUMBER data type. This
function returns 1 if the XML document has been validated successfully against the Schema

O
specified within it. Otherwise, it returns 0. This function can be used to test whether an

based XMLType instances.


l &
XMLType instance has already been validated. This applies only to transient XML Schema-

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 9-27
Overview of XML Repository

• Provides hierarchical abstraction for data


• Provides file system functionality
• Provides path names to objects, similar to file
systems
• Is useful for content-oriented applications

Folder

Resource
Link
ACL Path name Contents

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Overview of XML Repository
U s
A I
Oracle XML DB provides the functionality of a file system in the database that forms a
repository for data that is modeled via XML. The Oracle XML DB file system model maps

O
path names or URLs to database objects of XMLType, and provides management facilities

l &
for these objects. A database object that is mapped to the file system is called a Resource.
Oracle XML DB resources are database objects with another (navigational) access path in
a
addition to SQL. Oracle XML DB provides a generic access control list (ACL) mechanism
n
te r
usable by applications, but provides significantly more functionality for objects mapped to
the Oracle XML DB file system. ACLs are usable on a per-object (per-row) basis, and

I n
shareable across table boundaries. ACLs can be seen as a particular implementation of
database row-level security. Oracle XML DB also provides support for standard Internet
l e
protocols (FTP and WebDAV/HTTP) as a means of accessing its file system. XML elements
c
r a
are mapped to database tables, for XMLType tables, registered XML Schema-based tables
with XMLType columns, and views. These can be easily viewed and accessed in the XML

O
repository. Data in XMLType tables and tables containing XMLType columns can be stored
in character large objects (CLOBs) or natively in structured XML storage. Data in
XMLType views can be stored in local tables or remote tables that are accessed by using
DBLinks. Both XMLType tables and views can be indexed by using B*Tree, Oracle Text,
function-based, or bitmap indexes.
Oracle 10g: XML Fundamentals 9-28
What Is the Repository?

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
What Is the Repository?
U s
A I
The repository is similar to a directory structure inside the database. You can access it by
using any desktop tool such as a browser or Windows Explorer. In the address, you can

O
specify a database resource path. This maps to a Web folder so that Windows Explorer can

name, you are prompted for the password.


l &
view the database as a hierarchy. Access control applies so that when you enter the path

n a
The documents in each folder are listed just as any file system document. However, the

te r
documents are internally stored in rows and columns in the database.
The slide shows the contents of the PURCHASEORDER table inside the Scott Schema

I n
viewed by using Windows Explorer. On the right side, you see the content of the table as

l e
.xml files. These files can be accessed by using SQL and any editor such as Microsoft

c
Word, or a browser.

r a
O
Oracle 10g: XML Fundamentals 9-29
XML Repository: Features

XML repository has the following features:


• Foldering
• Access control list (ACL)
• Protocol support
• Versioning

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Repository: Features
U s
contain a resource. A folder is also a resource.
A I
Folder: A folder is a node or directory in the repository hierarchy that contains or can

O
Access control list (ACL): ACL restricts access to a resource or resources. Oracle XML DB

&
uses ACLs to restrict access to any Oracle XML DB resource.
l
n a
Protocol support: Oracle XML DB allows access through Internet protocols such as FTP
and HTTP as well as WebDAV, which is an extension of HTTP, to store and retrieve XML
data in the database.
te r
be maintained. I n
Versioning: With Oracle XML DB, you can have different versions of the same resource to

c l e
r a
O
Oracle 10g: XML Fundamentals 9-30
Repository Support for Internet Protocols

• Internet protocols
– Access data through URL
– Are mapped to path name in the repository
– Return the content of the resource
• The repository supports the FTP, HTTP, and
WebDAV protocols

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Repository Support for Internet Protocols
U s
A I
Oracle XML DB support for Internet protocols provides an alternative means of accessing
resources to Oracle Net Services (Net8). Oracle Net Services is optimized for record-

O
oriented data. The Internet protocols are designed for stream-oriented data, such as binary

useful for these scenarios:


l &
files or XML text documents by using a Web interface. Oracle XML DB protocol access is

a
• Direct access from file-oriented applications by using the database like a file system
n
te r
• Heterogeneous application server environments that want a uniform data access
method, for example, XML over HTTP and Web services, which are now supported by

I n
most application and data servers.

c l e
Oracle XML DB implements Hypertext Transfer Protocol (HTTP), HTTP 1.1 as defined in
RFC2616 specification, and supports only stateless servlets. State is maintained by storing

r a
information in HTTP cookies. Web Distributed Authoring and Versioning (WebDAV) is a
set of extensions to the HTTP protocol that you can use to edit or manage your files on
O
remote Web servers. WebDAV can also be used to share and edit content by using the
Internet. Oracle XML DB supports World Wide Web distributed authoring and versioning
(WebDAV) features, such as folders (specified by RFC2518), access control, and
versioning.

Oracle 10g: XML Fundamentals 9-31


Oracle XML DB Versioning

• Provides basic support for the versioning of


resouces
• Manages multiple versions of resources:
– Except folders, XML Schemas, and ACLs
• Supports single-branch operations:
– Check-in
– Check-out v1
– DML v2
– Version history v3
– Get predecessor
– Get successor
Resource

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Oracle XML DB Versioning
U s
A I
The Oracle XML DB versioning system provides a way to create and manage different
versions of a resource. In the past, when a resource, such as a table or column, was updated,

O
its previous contents and properties were lost. Using Oracle XML DB, versioning can

l &
prevent this loss by storing a new version of the resource in the database, and retaining the
old resource contents and properties when an update is made. A version history of a resource
a
is maintained so that earlier versions may be accessed and loaded, if required.
n
te r
Oracle XML DB provides the DBMS_XDB_VERSION and DBMS_XDB PL/SQL packages
for version-control management of a resource. The Oracle XML DB versioning system

I n
tracks all the changes on version-controlled resources (VCR) and includes the following
features:

c l e
• Enabling and disabling version control on a resource

r a
• 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.
O
• Loading a specific version of the resource by using the object ID of the version. The
resource’s object ID can be found from the version history of the resource, or the
version-controlled resource.

Oracle 10g: XML Fundamentals 9-32


Benefits of Oracle XML DB

• An XML file system


• Support for open XML standards
• XML and relational data integrated in the same
data model
• Optimized storage of large XML documents
• Scalability and performance

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Benefits of Oracle XML DB
U s
A I
The benefits of integrating native XML capabilities within the Oracle database are:
• The ability to store and manage both structured and unstructured data under a standard
W3C XML data model
O
l &
• Complete transparency and interchangeability between the XML and SQL metaphors
so that XML operations can be performed on database data, and SQL operations on
XML documents stored in the database
n a
WebDAV protocol access
te r
• XML Repository functionality, such as creating folders, access control, FTP and

I n
• Version control of database resources
• Superior performance and scalability for XML operations
l e
• Better management of unstructured XML data through piecewise updates, indexing,
c
r a
search, multiple views on the data, managing intradocument and interdocument
relationships
O
• Enabling data and documents from disparate systems to be accessed. For example, by
using Oracle gateways and external tables, data can be combined into a standard data
model. These integrative capabilities reduce the complexity of developing applications
that must deal with data from different sources.

Oracle 10g: XML Fundamentals 9-33


Summary

In this lesson, you should have learned how to:


• Describe Oracle XML DB
• Identify the components of Oracle XML DB
• Understand the applications of Oracle XML DB
• List the benefits of Oracle XML DB
• Describe the XML repository
• Describe foldering in the repository
• Use protocol server support to access data
• Describe versioning
• Register an XML Schema in the database

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
Oracle XML DB functionality provides a high-performance XML storage and retrieval
technology available with the Oracle 10g database. It fully absorbs the W3C XML data

O
model into the Oracle Database, and provides new standard access methods for navigating

l &
and querying XML. With Oracle XML DB, you get all the advantages of relational database
technology and XML technology at the same time.

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 9-34
Practice 9: Overview

This practice covers the following topics:


• Mapping a Web Folder to the XML DB repository
• Creating your student folder under the /home
parent folder
• Copying and displaying an XML document in your
student folder
• Copying an XSL stylesheet and an XML document
that uses the stylesheet to the folder, and
accessing the XML document

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Oracle 10g: XML Fundamentals 9-35
Practice 9
The goal of this practice is to work with the Oracle XML DB (XDB) repository for storing
and accessing XML resources, such as XML and XSL documents.
1. Map a Web Folder to the Oracle XDB repository.
a. Start Windows Explorer on your computer.
Hint: You can do this by selecting your XMLlabsProject node and click
Tools > Explorer, which has been configured for this course.
b. In the Explorer window, click Tools > Map Network Drive ….
c. Click the text Web Folder or FTP site in the last line that reads Create a
shortcut to a Web Folder or FTP site in the Map Network Drive window.
d. In the Add Network Place Wizard, enter the URL
http://<host>:160<nn>/ in the Type the location of the Network
Place: field. Then, click Next >.
Note: Check with your instructor for the name of the <host> and port number
suffix <nn> for your course.
e. You will be prompted for a User Name and Password in the Enter Network
Password window. Enter your Oracle database User Name ORAx and Password
oracle, select the Save this password in your password list check box, and
then click OK.
f. In the Add Network Place Wizard, you are prompted to Enter a name for this
Network Place. Enter the name OracleXDB in the field and click Finish.
g. Windows opens another Explorer window with the top-level folders of the Oracle
XDB repository displayed.
Note: Do not close the Explorer windows.

n l y
2. In the home parent folder, create your own student folder called ORAx, where x is
your assigned student number.
O
a. Double-click the home folder, and create a new folder called ORAx by clicking
e
File > New > Folder.
s
b. Replace the text New Folder, next to your new folder icon, with the text ORAx
U
A I
(using uppercase characters), where x is your student number, and press [Enter].
Note: The folder must have the same name as your Oracle database username.
3. Copy the E:\labs\lab\hr.xml file to your /home/ORAx folder in the Oracle
XDB repository. O
l &
Hint: Using the two Windows Explorer windows, drag hr.xml from Explorer with
E:\labs\lab displayed and drop it to the ORAx Web folder in the other Explorer

n a
window that you created in the previous step.

te r
4. Navigate to your ORAx folder in the OracleXDB Explorer window, and double-click
on the hr.xml file. Internet Explorer is started and you are prompted to enter your

are displayed. I n
User Name ORAx and Password oracle. Click OK and the hr.xml file contents

l e
5. Using the Explorer windows, copy the employees.xml and the related files to the
c
Web folder.

r a
a. Copy employees.xml, employees.xsl, and employees.dtd files

O from the E:\labs\lab directory to your /home/ORAx folder.


b. After copying the files to the Web folder, double-click employees.xsl in
the Web folder.
c. Double-click the employees.xml. Does a complete transformation occur?

Oracle 10g: XML Fundamentals 9-36


Generating XML from an Oracle
Database 10g

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe SQL/XML generation functions
• Use SQL/XML generation functions in SQL
• Generate XML by using native Oracle SQL
functions

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
relational tables in the database.
A I
In this lesson, you learn about the different methods available to generate XML from

O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 10-2
SQL/XML Generation Functions

• SQL/XML generation functions available are:


– XMLElement()
– XMLForest()
– XMLSequence()
– XMLConcat()
– XMLAgg()
• Oracle database extension function to SQL/XML
is:
– XMLColAttVal()

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
SQL/XML Generation Functions
U s

A I
The Oracle SQL environment provides the following built-in XML generation functions:
XMLElement() generates an XML element from a relational value.

O
XMLForest() generates a list of XML elements form a list of relational values.


l &
XMLSequence() generates a sequence of XMLType objects.
XMLConcat() concatenates arguments to create an XML fragment.

n a
XMLAgg() generates a forest of XML elements from a collection.

te r
The SQL/XML generation functions listed above are:
• Used to generate XML elements by using relational and object-relational data

I n
• Part of the emerging SQL standards for XML

l e
The XMLColAttVal() function is an Oracle database extension function to the

c
SQL/XML standards. The XMLColAttVal() function generates an XML element whose

r a
tag name is column, with a name attribute and value set to the database column name, and
content set to the database column value. The XMLAttributes() function adds attributes
O
to an element generated by XMLElement().
Note: The Oracle Database implementation of SQL/XML functionality is in conformity
with the ISO Standard (ISO/IEC 9075-14:2003) published in December 2003.

Oracle 10g: XML Fundamentals 10-3


The XMLElement() SQL/XML Function

Syntax:
XMLElement(
[NAME] identifier
[, XML_attributes_clause]
[, value_expression] ...)

Example:
SELECT e.employee_id,
XMLElement("Emp",
e.first_name||' '||e.last_name) AS result
FROM employees e
WHERE employee_id > 200;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XMLElement()SQL/XML Function
U s
A I
The XMLElement() is primarily used to construct XML instances from relational data.
The XMLElement() function takes an element name, an optional collection of attributes

O
for the element, and zero or more arguments that make up the element’s content and returns
an instance of XMLType. The collection of attributes is called an XML attribute clause.

l &
The first argument is an identifier name to specify the name of the XML element to be
a
created. The identifier does not have to be a column name, but it cannot be an expression.
n
te r
Use double quotes around the identifier name to preserve its case.
In the example, the XMLElement() function retrieves the first and last names of

I n
employees whose employee_id is greater than 200. The output produced by the query

cl e
shows an <Emp> element for each employee containing the employee’s name:
EMPLOYEE_ID RESULT

r a -----------
201
----------------------------
<Emp>Michael Hartstein</Emp>

O 202
203
204
<Emp>Pat Fay</Emp>
<Emp>Susan Mavris</Emp>
<Emp>Hermann Baer</Emp>
205 <Emp>Shelley Higgins</Emp>
206 <Emp>William Gietz</Emp>
Oracle 10g: XML Fundamentals 10-4
XML Elements with Attributes

In the second argument of the XMLElement()


function, use an XMLAttributes() function with:
• A column name:
SELECT XMLElement("Emp",
XMLAttributes(employee_id),
first_name||' '||last_name) as result
FROM employees e
WHERE employee_id = 201;

• A literal value or column expression, with aliases:


SELECT XMLElement("Emp",
XMLAttributes(employee_id AS "id", '10' "dept"),
first_name||' '||last_name) as result
FROM employees e
WHERE department_id = 10;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Elements with Attributes
U s
A I
The XMLAttributes() function can be used as an optional XML attribute clause in the
second argument of the XMLElement() function. The XMLAttributes() function

O
accepts a comma-separated list of arguments. An argument can be a column name, a column
expression, or a literal value.

l &
Note: An alias, optionally preceded by an AS keyword, must be specified for a column
expression and a literal value.
n a
te r
The column name is used for the name of the attribute. Otherwise, the alias name, if
specified, is used to name the attribute. The attribute value is set to the column value, the
I n
result of the column expression, or the literal value. If an expression evaluates to the NULL

l e
value, then the attribute is excluded from the element.

c
The XML output result for the first slide example is:

r a<Emp EMPLOYEE_ID=“201”>Michael Hartstein</Emp>

O
The XML output result for the second slide example is:
<Emp id=“200” dept=“10”>Jennifer Whalen</Emp>

Oracle 10g: XML Fundamentals 10-5


The XMLForest() SQL/XML Function

The XMLForest() function


• Generates an XML element for each argument
• Syntax is:
XMLForest(value_expression [AS alias]
[, value_expression [AS alias]] ...)

• Arguments can be:


– A column name
– A column expression or an object type instance
– A literal value
• Must specify an element name by using an alias
for an expression, object type, and literal
arguments
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XMLForest() SQL/XML Function
U s
A I
The XMLForest() function produces an XML element for each value expression
specified in the comma-separated list of arguments. The result is called a forest. The

O
XMLForest() function arguments can be a column name, column expression, an object
type instance, and a literal value. The XML element names for each argument is derived

l &
from the column name, or an optional alias. An alias is required if an argument is a column

a
expression, object type, or a literal value. The alias is optional if an argument is a simple
n
column name.

te r
Note: If a value expression evaluates to a NULL, then an element is not created for that

I n
expression. The XMLForest() function can be used by stand-alone, nested inside itself, or
nested inside an XMLElement() function to provide the root element for the forest. For

l e
example, using the XMLForest() function by itself:

c
SELECT employee_id, XMLForest(first_name,last_name) result

r aFROM employees WHERE department_id = 10;

O
Produces:
EMPLOYEE_ID RESULT
----------- ----------------------------------------
200 <FIRST_NAME>Jennifer</FIRST_NAME>
<LAST_NAME>Whalen</LAST_NAME>

Oracle 10g: XML Fundamentals 10-6


Generating Nested XML Elements

• Use nested XMLElement() functions:


SELECT employee_id, XMLElement("Emp",
XMLElement("name",
e.first_name||' '||e.last_name),
XMLElement("hire_date", e.hire_date)) result
FROM employees e
WHERE employee_id > 200;

• Use the XMLForest() function:


SELECT employee_id, XMLElement("Emp",
XMLForest(first_name||' '||last_name "name",
hire_date AS "hire_date")) result
FROM employees
WHERE employee_id > 200;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Generating Nested XML Elements
U s
However, the XMLForest() function is better suited to the task.
A I
The XMLElement() function can be nested to produce XML data with a nested structure.

O
In the examples in the slide, the XMLElement() and XMLForest() functions are used

l &
to produce an <Emp> element for each employee with child elements that provide the
employee’s name and the date hired. The result produced is:
EMPLOYEE_ID RESULT
n a
te r
----------- ----------------------------------------
201 <Emp><name>Michael Hartstein</name><hire

I n _date>17-FEB-96</hire_date></Emp>

c l e 202 <Emp><name>Pat Fay</name><hire_date>17-A


UG-97</hire_date></Emp>

r a
O ...
203 <Emp><name>Susan Mavris</name><hire_date
>07-JUN-94</hire_date></Emp>

Note: In the XMLForest() function, the AS keyword between the value and its alias is
optional.
Oracle 10g: XML Fundamentals 10-7
The XMLSequence() SQL/XML Function

• Syntax:
XMLSequence(
{XMLType_instance | SYS_REFCURSOR_instance}
[, XMLformat_instance])
• Example, using a reference cursor:
SELECT e.*
FROM TABLE(XMLSequence(
CURSOR(SELECT first_name, last_name
FROM employees
WHERE department_id =10))) e;
SELECT e.*
FROM TABLE(XMLSequence(
CURSOR(SELECT first_name, last_name
FROM employees
WHERE department_id =10),
XMLFormat('EMPLOYEE'))) e;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XMLSequence() SQL/XML Function
U s
A I
The XMLSequence() function returns a sequence of XMLType objects. The function
returns an XMLSequenceType which is a VARRAY of XMLType instances. Because the

O
function returns a collection, it can be used in the FROM clause of SQL queries.
The XMLSequence() function has two forms:

l &
• The first form inputs an XMLType instance and returns a VARRAY of top-level nodes.
a
This form can be used to separate XML fragments into multiple rows.
n
te r
• The second form takes as input a SYS_REFCURSOR argument with an optional
instance of an XMLFormat object. Each row of the cursor corresponds to an

I n
XMLType object instance. The second form can be used to construct XMLType
instances from arbitrary SQL queries.

c le
The first example in the slide produces the following XML result:

r aCOLUMN_VALUE
------------------------------------

O <ROW>
<FIRST_NAME>Jennifer</FIRST_NAME>
<LAST_NAME>Whalen</LAST_NAME>
</ROW>
In second example, XMLFormat() alters the root element from <ROW> to <EMPLOYEE>.
Oracle 10g: XML Fundamentals 10-8
The XMLConcat() SQL/XML Function

The XMLConcat() function concatenates its


arguments to create an XML fragment.
• Syntax:
XMLConcat(
XMLType_instance [, XMLType_instance]...)

• Example, using the XMLSequenceType() function:


SELECT XMLConcat(
XMLSequenceType(
XMLElement(name, 'Steven King'),
XMLElement(salary, 2400),
XMLElement(job, 'AD_PRES')
)) result
FROM dual;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XMLConcat() SQL/XML Function
U s
fragment. The XMLConcat() function has two forms:
A I
The XMLConcat() function concatenates all the arguments passed in to create an XML

O
• The first form takes an XMLSequenceType() function, which collapses a VARRAY

l &
of XMLType instances into a single XMLType instance.
• The second form concatenates an arbitrary number of XMLType instance values. If
a
one of the value is NULL, then it is excluded from the result. If all the values are
n
te r
NULL, the result is NULL. The next page provides an example.
Note: The XMLAgg() function can be used to concatenate XMLType instances across

I n
rows. The XMLAgg() function is discussed in the section titled “The XMLAgg()
SQL/XML Function.”

c l e
The example in the slide produces the following result:

r aRESULT
----------------------------------------
O <NAME>Steven King</NAME>
<SALARY>2400</SALARY>
<JOB>AD_PRES</JOB>
Note: The XMLElement() function returns an XMLType instance.
Oracle 10g: XML Fundamentals 10-9
The XMLConcat() SQL/XML Function (continued)
The following example concatenates multiple XMLType instance values created by using
the XMLElement() function:

SELECT employee_id, XMLConcat(


XMLElement("first", e.first_name),
XMLElement("last", e.last_name)) result
FROM employees e
WHERE department_id = 60;

The results produced by the above query is:

EMPLOYEE_ID RESULT
----------- ----------------------------------------
103 <first>Alexander</first>
<last>Hunold</last>

104 <first>Bruce</first>
<last>Ernst</last>

105 <first>David</first>
<last>Austin</last>

106 <first>Valli</first>
<last>Pataballa</last>
n l y
107 <first>Diana</first>
e O
<last>Lorentz</last>

U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 10-10
The XMLAgg() SQL/XML Function

• Syntax:
XMLAgg(XMLType_instance
[ORDER BY sort_list])

• Examples:
SELECT XMLElement(department,
XMLAgg(XMLElement(employee,
XMLForest(last_name, salary))) ) result
FROM employees WHERE department_id = 20;

SELECT XMLElement(department,
XMLAgg(XMLElement(employee,
XMLForest(last_name, salary))
ORDER by last_name)) result
FROM employees WHERE department_id = 20;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XMLAgg() SQL/XML Function
U s
The XMLAgg() function is:

A I
• A group function that produces a forest of XML elements from a set of XML elements.

O
• Used to concatenate XMLType instances across multiple rows.

l &
Note: Any argument with a NULL value is excluded from the result. The XMLAgg()
function does not accept an XMLFormat() parameter.

n a
The result produced by the example in the slide (using a SQL*Plus column format of A42)
is:
RESULT
te r
I n
------------------------------------------
<DEPARTMENT><EMPLOYEE><LAST_NAME>Hartstein

le
</LAST_NAME><SALARY>13000</SALARY></EMPLOY
c
a
EE><EMPLOYEE><LAST_NAME>Fay</LAST_NAME><SA

O r LARY>6000</SALARY></EMPLOYEE></DEPARTMENT>
The result for the second example using the ORDER BY clause is:
<DEPARTMENT><EMPLOYEE><LAST_NAME>Fay</LAST
_NAME><SALARY>6000</SALARY></EMPLOYEE><EMP
LOYEE><LAST_NAME>Hartstein</LAST_NAME><SAL
ARY>13000</SALARY></EMPLOYEE></DEPARTMENT>
Oracle 10g: XML Fundamentals 10-11
Generating Master-Detail Content

SELECT department_id, XMLElement("department",


XMLAttributes(e.department_id "dept_id"),
XMLAgg(XMLElement("emp", e.last_name))
) result
FROM employees e
WHERE department_id in (10, 20)
GROUP BY department_id;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Generating Master-Detail Content
U s
A I
The example in the slide produces a <department> element for each row returned by the
query. Each <department> element contains an <emp> child element for each employee
belonging to the department rows returned by the query.
O
DEPARTMENT_ID RESULT
l &
The query produces the following XML result:

a
------------- ----------------------------------------
n
te r
10 <department dept_id="10"><emp>Whalen</em
p></department>

I n 20 <department dept_id="20"><emp>Hartstein<

c l e /emp><emp>Fay</emp></department>
Note: The example must use a GROUP BY clause because the XMLAgg() function is a
r a
group function that is used with the single-valued department_id column, which is used

O
in the SELECT list and as an argument in the XMLAttributes() function.

Oracle 10g: XML Fundamentals 10-12


A Complex Master-Detail: Example

Generate XML elements of each employee with job


history within the department.
SELECT department_id, XMLElement("Department",
XMLAttributes(d.department_name "name"),
(SELECT XMLAgg(XMLElement("emp",
XMLAttributes(e.last_name name),
(SELECT XMLAgg(XMLElement("jobs",
XMLAttributes(j.job_id "job")))
FROM job_history j
WHERE j.employee_id=e.employee_id)))
FROM employees e
WHERE e.department_id=d.department_id))
AS result
FROM departments d
WHERE department_id < 40;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
A Complex Master-Detail: Example
U s
A I
The XMLAgg() function can be used to reflect the hierarchical nature of some relationships
that exist in tables. The example generates department elements containing an element

O
for each employee. Within each employee element is his or her job history. The output is:
DEPARTMENT_ID RESULT

l &
------------- ----------------------------------------

a
10 <Department name="Administration"><emp N

n
te r
AME="Whalen"><jobs job="AD_ASST"></jobs>
<jobs job="AC_ACCOUNT"></jobs></emp></De
partment>

I n 20 <Department name="Marketing"><emp NAME="

c l e Hartstein"><jobs job="MK_REP"></jobs></e
mp><emp NAME="Fay"></emp></Department>

r a 30 <Department name="Purchasing"><emp NAME=


"Raphaely"><jobs job="ST_CLERK"></jobs><

O /emp><emp NAME="Khoo"></emp><emp NAME="B


aida"></emp><emp NAME="Tobias"></emp><em
p NAME="Himuro"></emp><emp NAME="Colmena
res"></emp></Department>

Oracle 10g: XML Fundamentals 10-13


The XMLColAttVal() SQL/XML Function

• Syntax:
XMLColAttVal(value_expression [AS alias]
[, value_expression [AS alias]]...)

• Example:
SELECT XMLElement("Emp",
XMLAttributes(
e.first_name||' '||e.last_name AS "name"),
XMLColAttVal(e.hire_date, e.department_id
AS "department")
) result
FROM employees e
WHERE e.department_id = 20;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The XMLColAttVal() SQL/XML Function
U s
A I
XMLColAttVal() function generates a forest of XML column elements containing the
value of the arguments passed in. The name of the arguments are put in the name attribute
of the column element.
O
l &
The example generates an <Emp> element for each employee. Each <Emp> element has a
name attribute and column child elements for the hire date and department ID as the

n a
content. The query example produces the following XML result:
RESULT

te r
--------------------------------------------------

I n
<Emp name="Michael Hartstein"><column name = "HIRE
_DATE">17-FEB-96</column><column name =

l e
"department">20</column></Emp>
c
r a<Emp name="Pat Fay"><column name = "HIRE_DATE">17-

O AUG-97</column><column name = "department">20</col


umn></Emp>
Note: The column name or alias associated with each XMLColAttVal() argument is used
as the corresponding name attribute value for each <column> element.

Oracle 10g: XML Fundamentals 10-14


Native XML Generation

• Generate XML documents by using the Oracle


database SQL function:
– SYS_XMLGEN, to accept a single argument and
generate an XML document for each row from a
SQL statement
– SYS_XMLAGG, to process groups of rows,
aggregating several XML fragments into a single
XML document
• In PL/SQL, use the DBMS_XMLGEN package to
execute any SQL query and map the results into
an XML document as a CLOB or XMLType.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Native XML Generation
U s
A I
The native XML generation methods effectively provide XML SQL Utility (XSU)
functionality in the server. If the Oracle XML SQL Utility (XSU) is installed on a client

O
system, then a user can generate XML by using XSU commands from the client.

l &
This Oracle database-specific SYS_XMLGEN() function accepts an argument and returns a
well-formed XML document. The SYS_XMLGEN() function operates at the row level

n
returning an XML document for each row. a
te r
The SYS_XMLAGG() function groups all XML documents or fragments represented by its
argument to produce a single XML document. SYS_XMLAGG() adds an enclosing

I n
<ROWSET> element by default. To alter the name of the <ROWSET> element, use the

l e
parameter accepting an XMLformat() object.

c
If you are using PL/SQL, you can programmatically generate XML documents by using the

r a
DBMS_XMLGEN package. The details of using DBMS_XMLGEN are not covered in this

O
course.

Oracle 10g: XML Fundamentals 10-15


Using SYS_XMLGEN()

The SYS_XMLGEN() function:


• Converts its argument into an XML document
• Accepts two arguments:
– A scalar value, object type, or XMLType instance
– An optional XMLFormat() object
• Returns an XMLType instance
• Creates and queries XML instances within SQL
SELECT SYS_XMLGEN(last_name) result
FROM employees WHERE last_name LIKE 'K%';

SELECT SYS_XMLGEN(XMLForest(last_name, salary),


XMLFormat('EMPLOYEE')) result
FROM employees WHERE department_id = 30;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using SYS_XMLGEN()
U s
A I
The SYS_XMLGEN function accepts a single argument within a SQL query and converts it
to an XML document. SYS_XMLGEN operates on expressions and columns within each row,

O
and returns an XMLType. The result of the first query in the slide is:
RESULT

l &
--------------------------------
<?xml version="1.0"?>

n a
te r
<LAST_NAME>Kaufling</LAST_NAME>
<?xml version="1.0"?>
<LAST_NAME>Khoo</LAST_NAME>

I n
<?xml version="1.0"?>

c l e
<LAST_NAME>King</LAST_NAME>
<?xml version="1.0"?>

r a <LAST_NAME>King</LAST_NAME>
<?xml version="1.0"?>

O <LAST_NAME>Kochhar</LAST_NAME>
<?xml version="1.0"?>
<LAST_NAME>Kumar</LAST_NAME>

6 rows selected.
Oracle 10g: XML Fundamentals 10-16
Using SYS_XMLGEN() (continued)
The second example in the slide generates the following results:

RESULT
--------------------------------------------------
<?xml version="1.0"?>
<EMPLOYEE>
<LAST_NAME>Raphaely</LAST_NAME><SALARY>11000</SALA
RY></EMPLOYEE>

<?xml version="1.0"?>
<EMPLOYEE>
<LAST_NAME>Khoo</LAST_NAME><SALARY>3100</SALARY></
EMPLOYEE>

<?xml version="1.0"?>
<EMPLOYEE>
<LAST_NAME>Baida</LAST_NAME><SALARY>2900</SALARY><
/EMPLOYEE>

<?xml version="1.0"?>
<EMPLOYEE>
<LAST_NAME>Tobias</LAST_NAME><SALARY>2800</SALARY>
</EMPLOYEE>

n l y
<?xml version="1.0"?>
<EMPLOYEE>
e O
<LAST_NAME>Himuro</LAST_NAME><SALARY>2600</SALARY>
</EMPLOYEE>
U s
<?xml version="1.0"?>
A I
O
<EMPLOYEE>
<LAST_NAME>Colmenares</LAST_NAME><SALARY>2500</SAL
ARY></EMPLOYEE>
l &
6 rows selected.
n a
te r
Note: The SQL*Plus result column format is 50 characters wide. Excluding the
XMLFormat() element from the second argument generates a <ROW> element instead of

I n
the <EMPLOYEE> element. Each row instance is preceded by the XML declaration:

c l e
<?xml version="1.0"?>

r a
O
Oracle 10g: XML Fundamentals 10-17
Using SYS_XMLAGG()

The SYS_XMLAGG() function:


• Groups all the input documents and produces a
single XML document
• Is used to aggregate (concatenate) fragments
SELECT SYS_XMLAGG(SYS_XMLGEN(last_name),
XMLFormat('Employees')) result
FROM employees
WHERE department_id < 30
GROUP BY department_id;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using SYS_XMLAGG()
U s
A I
The example in the slide aggregates data together similar to the GROUP BY operation, with
the GROUP BY also showing up on the XML document produced. SYS_XMLAGG also works

O
with OLAP aggregation functionality such as ROLLUP and CUBE. You can thus create
different XML documents based on ROLLUP and CUBE operations. Oracle database

l &
provides windowing functions that can be used to compute cumulative, moving, and

a
centered aggregates. SYS_XMLAGG can be used with these as well, to create documents

n
RESULT
te r
based on rank and partition. The output from the above statement looks as follows:

--------------------------------------------------

I n
<?xml version="1.0"?>

l e
<EmployeeGroup>
<LAST_NAME>Whalen</LAST_NAME>
c
a
</EmployeeGroup>

O r <?xml version="1.0"?>
<EmployeeGroup>
<LAST_NAME>Hartstein</LAST_NAME>
<LAST_NAME>Fay</LAST_NAME>
</EmployeeGroup>

Oracle 10g: XML Fundamentals 10-18


DBMS_XMLGEN

• Creates an XML document from any SQL query


• Gets the document as a CLOB
• Provides a fetch interface
• Is useful for pagination in Web applications

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
DBMS_XMLGEN
U s
A I
DBMS_XMLGEN creates XML documents from any SQL query by mapping the database
query results into XML. It gets the XML document as a CLOB or XMLType. It provides a

O
“fetch” interface, whereby you can specify the maximum rows and the rows to skip. This is

l &
useful for pagination requirements in Web applications. DBMS_XMLGEN also provides
options for changing tag names for ROW, ROWSET, and so on.

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 10-19
Summary

In this lesson, you should have learned how to:


• Use SQL/XML functions in SQL statements
• Generate XML by using the native SYS_XMLGEN
and SYS_XMLAGG functions

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
In this lesson, you learned to use the SQL/XML functions to manipulate the XML data
stored in the database. You also learned about the native Oracle database functions, the

O
SYS_XMLGEN and SYS_XMLAGG functions, for generating XML from relational tables.

l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 10-20
Practice 10: Overview

This practice covers the following topics:


• Generating XML by using SQL/XML functions
• Generating XML by using SQL functions

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Oracle 10g: XML Fundamentals 10-21
Practice 10
The goal of this practice is to generate XML by using SQL/XML generation functions. You
use SQL*Plus for tasks by using the login information provided by your instructor.
SQL*Plus can be started in several ways, two of which are the following:
a. Double-click the SQLPlus icon on the desktop
b. Click the Connections tab in JDeveloper Navigator, expand the Database node and
right-click the hr connection created in the XSQL practices, and select SQL*Plus. If
you use this technique, then the first time you invoke SQL*Plus from a database
connection, JDeveloper prompts you for the location of the SQL*Plus executable. In
this case, enter the file path name E:\oracle\ora10\bin\sqlplusw.exe, or
click Browse… and locate the same file.
The practices generate XML by using the EMPLOYEES table.
1. Generate XML by using SQL by retrieving the concatenated value of the first and last
names, and the salaries of employees in department 60. Use fullname and pay as
the respective XML elements, and employee for their parent element.
2. Use XSQL/XML to generate employees’ salaries and their department IDs as content
for employees in department 10 and 20. Employees’ last names and department IDs
should appear as XML attributes of an element named employee.
3. Use SYS_XMLGEN to generate the values of employee last names and salaries for all
employees in department 20.
4. Use SYS_XMLAGG to create a group of employees in department 30 and 40, in an
element named EMPLOYEE_GROUP, listing the employee last names and grouping
them by hire_date.
n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 10-22
Managing XML Data in an Oracle 10g
Database

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c l e
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe XMLType
• Create objects of XMLType
• Describe XMLType storage options
• Load data into XMLType
• Retrieve data from XMLType columns
• Use XMLType member functions called methods
• Use XPath functions on XMLType data

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A
about creating tables by using XMLType and loading data into them. I
In this lesson, you learn about XMLType and the different types of storage. You also learn

O
You learn different methods to query data stored in the XMLType columns. You see the

l &
different methods for XMLType data type. Oracle Text uses standard SQL to index, search,
and analyze text and documents stored in the Oracle database. This lesson discusses how to

n a
index columns having XML data and build a query to search and retrieve data from XML
documents.

te r
References: For more information about these topics, refer to:
I n
Oracle10g: XML Database Developer’s Guide–Oracle XML DB, Text Application

l e
Developer’s Guide, Text Reference
c
r a
O
Oracle 10g: XML Fundamentals 11-2
XMLType

XMLType:
• Is a data type in Oracle database10g
• Stores XML data or documents in a native
database format by using:
– A CLOB
– Object-relational tables and views
• Can be accessed by all Oracle SQL interfaces,
bringing the XML and SQL worlds together
• Enables SQL operations on XML content, and XML
operations on SQL content
• Provides built-in functions for indexing, and
navigation of XML content
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XMLType
U s
A I
XMLType is a SQL data type that is stored natively in the database and recognized by all
interfaces that recognize SQL, such as OCI, JDBC, and PL/SQL, among others. Therefore,

O
you can create programs that use XMLType for parameters or variables.

l &
XMLType is a data type that stores XML content in two ways or a combination of both:
• Character large objects (CLOBs). Using CLOB storage maintains content accuracy to

n a
the original XML including the white space. In this case, the XML documents are

te r
composed as complete documents like files.
• Object-relational tables and views. Object-relational storage maintains Document

I n
Object Model (DOM)-fidelity. In this case, the XML documents are broken up

c l e
(decomposed) into object-relational tables or views. XMLType achieves DOM fidelity
by maintaining information that SQL or Java objects normally do not provide.

r a
Native XMLType instances contain hidden columns that store extra information, which is
accessible by using C, SQL, or Java API functions. It is possible to store XMLType as a
O
combination of CLOB and object-relational data. Changing the XML storage is useful when
tuning your application because each storage option has its own benefits.

Oracle 10g: XML Fundamentals 11-3


The Benefits of Using XMLType

XMLType:
• Is a data type for database columns, object type
attributes, object tables, and views
• Provides constructors to create XMLType
instances for insertion
• Can be queried with SQL, using built-in member
functions on the XML content
• Can be used in the PL/SQL variable declarations,
subprogram parameters, and function return
values
• Supports references to registered XML Schemas
• Can be indexed by using Oracle Text indexes

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The Benefits of Using XMLType
U s
A I
The big benefit of a native XMLType is a seamless operation with SQL and the rest of the
database platform. You first define a column of XMLType. You can specify optional storage

O
characteristics along with the definition. The XMLType constructor can be used to create the

l &
XMLType instance when inserting the XML data into the column. You can also use the
SYS_XMLGEN and SYS_XMLAGG operators to create instances of XMLType directly.

n a
You can select the XMLType instance from the column. XMLType offers a choice of
functions, such as:

te r
• The extract() function to extract a particular node

I n
• The existsNode() function to check whether a particular node exists

l e
You can also create a text index on the XMLType column. The extract() and

c
existNodes() functions can be used in SQL operations that insert and delete rows from

r a
a table. Both document and piecewise updates are supported by using the updateXML()

O
function.
You can define variables, parameters, and return values of XMLType in the PL/SQL
programs.

Oracle 10g: XML Fundamentals 11-4


Declaring an XMLType

• For a column in a relational table:


CREATE TABLE emp_resumes (
employee_id NUMBER(6) PRIMARY KEY,
resume XMLType);

• For an object-relational table:


CREATE TABLE emp_xmlresumes OF XMLType;

• For an attribute in an object type:


CREATE TYPE resume_t AS OBJECT (
employee_id NUMBER(6),
resume XMLType);
/

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Declaring an XMLType
U s
developers a convenient abstraction to store the XML content.
A I
Oracle database10g has a native XMLType for storing the XML content. XMLType gives

O
The examples in the slide show three ways to use the XMLType data type:

l &
1. As a resume column type in a relational table called emp_resumes
2. As the data type for objects in the object table called emp_xmlresumes

n a
3. As the data type for the resume attribute in the resume_t object type definition

te r
I n
c le
r a
O
Oracle 10g: XML Fundamentals 11-5
XMLType Storage Characteristics

The XMLType is a virtual column:


• Encapsulating a real CLOB column type
• That allows the characteristics for the CLOB
storage to be specified with a STORE AS clause

CREATE TABLE emp_resumes_clob (


employee_id NUMBER(6) PRIMARY KEY,
resume XMLType)
XMLType COLUMN resume
STORE AS CLOB (TABLESPACE data01
STORAGE (INITIAL 4096 NEXT 4096)
CHUNK 4096 NOCACHE LOGGING);

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XMLType Storage Characteristics
U s
A I
In the example shown, creating the resume column creates a virtual column of XMLType,
and a real, hidden column of CLOB type. The storage characteristics of the underlying CLOB

O
column can be specified by using the STORE AS clause, as shown in the example. The

l &
arguments to the storage clause are the same for regular LOB types.
Physically, the data can either be stored as a CLOB or object-relationally. When stored in an

n a
object-relational structure, the structure of the XML content stored in an XMLType instance

te r
must conform to an XML Schema that is registered with the XML DB repository.
When storing as a CLOB, the entire document along with all its white space is stored, to
I n
preserve the original document structure, that is, preserving the document fidelity.

l e
However, when storing an XML document in an XMLType stored in an object-relational

c
table, the node structure of the XML document and the relationship between the nodes is

r a
preserved, that is, the DOM fidelity is preserved, but not the original document structure

O
because the white space is not retained.

Oracle 10g: XML Fundamentals 11-6


Unstructured Versus Structured Storage

employees.xml employees.xsd

Store as CLOB Structured storage


Create XMLType table

Employees table Employees tables


. . . XMLType Column ... ... first_name last_name email … dept_id
. . . Steven King CLOB ... ... Steven King SKING … 90
--------- ----------- ------- ---------
. . . CLOB ... ... --------- ----------- ------- ---------
. . . CLOB ... ... --------- ----------- ------- ---------
. . . CLOB ... ... --------- ----------- ------- ---------

The XML document or fragments The XML elements are mapped


are stored in a CLOB data type. to columns in tables.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Unstructured Versus Structured Storage
U s
CLOB storage

A I
This stores an entire document as a CLOB, and specifies the storage characteristics of the
underlying CLOB column by using the STORE AS clause.
O
Object-relational storage
l &
This is based on XML Schema.
n a
• It provides relational storage.

te r
• Structured types are generated according to an XML Schema.

types. I n
• The structured part of XML document is decomposed into tables and columns of these

l e
• It requires a registered XML Schema.
c
r a
Unstructured Versus Structured Storage
Oracle XML DB creates XML Schema-based XMLType tables by using an XML document
O
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.

Oracle 10g: XML Fundamentals 11-7


CLOB Versus Object-Relational Storage

CLOB Storage Object-Relational Storage


Uses text search Uses full SQL search
Uses Oracle Text index Uses Oracle Text and B-Tree index

Is easier to generate Is more complex to generate


Is flexible for Schema changes Offers limited flexibility
Maintains document fidelity Maintains DOM fidelity
Supports whole document
Supports piecewise updates
updates
Provides better performance for Provides better performance for
storage and retrieval DML operations
Uses more space because of Uses less space because only
tags and spaces data, and not metadata, is stored

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
CLOB Versus Object-Relational Storage
U s
CLOB Storage (with Oracle Text index)
• Is very flexible when schemas change
A I
O
• Maintains the original XML byte for byte (important in some applications)
• Offers mediocre performance for DML, but fast for storing and retrieving complete
documents
l &
• Has some accessibility to SQL features
n a
te r
• Can consume considerable space
Object-Relational Storage (with B-Tree index)

I n
• Offers limited flexibility for schema changes, similar to ALTER TABLE restrictions
• Does not maintain trailing new lines, white space within tags, and data format for non-
l e
string data types, but maintains DOM fidelity
c
r a
• Offers excellent DML performance for piecewise updates and queries
• Has good accessibility to existing SQL features, such as constraints and indexes
O
• Consumes much less space in particular when used with an Oracle database-registered
XML Schema
DOM fidelity refers to how identical the returned XML documents are compared to the
original XML documents. That is, the tree structure of the document is preserved.

Oracle 10g: XML Fundamentals 11-8


Loading Data into XMLType

You can load data into XMLType columns by using:


• An INSERT with the XMLType() constructors by
using a VARCHAR2, CLOB, BLOB, or a BFILE:
INSERT INTO emp_resumes VALUES (100,
XMLType(
'<?xml version="1.0"?>
<RESUME>
<FULL_NAME>Steven King</FULL_NAME>
<JOB_HISTORY>
<JOB_ID>AD_PRES</JOB_ID>
</JOB_HISTORY>
</RESUME>'));
• Utilities, such as:
– Oracle XML/SQL Utility for Java, FTP, and WebDAV
– Oracle export, import, and SQL*Loader

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Loading Data into XMLType
U s
A I
Loading data into an XMLType column by using the INSERT statement, as shown in the
slide, creates a row containing the resume XML document for the employee Steven King by
using a VARCHAR2 argument in the XMLType() constructor. Constructors replace the
O
XMLType.createXML() function for inserting XML data into the column. For example:
INSERT into emp_resumes
l &
VALUES (101, XMLType.createXML('<?xml version="1.0"?>
<RESUME>
n a
te r
<FULL_NAME>Neena Kochhar</FULL_NAME>
<JOB_HISTORY><JOB_ID>AD_VP</JOB_ID></JOB_HISTORY>
</RESUME>'));

I n
Note: You can also load the XML data into XMLType columns by using a BFILE. For
example:

c le
INSERT INTO emp_resumes VALUES (102,

r a XMLType(BFILENAME('XML_FILES','code_11_09_lex.xml'),
NLS_CHARSET_ID('AL32UTF8')));

O
Oracle Database10g allows the creation of XML objects as resources in XML DB by using
WebDAV and FTP utilities to load and access documents in the database. Oracle XML SQL
Utility for Java offers a command-line interface for loading the XML data. The export,
import, and SQL*Loader utilities can load data into an XMLType only if it is stored as a
CLOB.
Oracle 10g: XML Fundamentals 11-9
Overview of Querying XML

• Select XMLType columns:


SELECT resume
FROM emp_resumes
WHERE employee_id = 100;

• Use XMLType member functions:


– existsNode() to filter query results based on the
XML content
– extract() to extract XML fragments or nodes
– extractValue() to extract text node values
• Query the XML content by using Oracle Text
operators

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Overview of Querying XML
U s
A
statement as shown in the slide where the result of the query is:I
An XMLType column, such as resume, can be queried by using a standard SQL SELECT

RESUME
----------------------------------------- O
<?xml version="1.0"?>
<RESUME>
l &
n a
<FULL_NAME>Steven King</FULL_NAME>
<JOB_HISTORY>

te r
<JOB_ID>AD_PRES</JOB_ID>

I n
<JOB_HISTORY>
</RESUME>

l e
XMLType provides many member functions, three of which are:

c
• The existsNode() function that is useful in query conditions to filter results based

r a
on the XML content in XMLType instances

O
• The extract() function that is used to query XML documents or fragments
contained in an XMLType instance.
• the extractValue() function that is used to obtain the text node value from an
XMLType instance
Note: Oracle Text operators facilitate the searching of XML documents stored in XMLType.
Oracle 10g: XML Fundamentals 11-10
Subset of XMLType Member Functions

XMLType Function Description


getClobVal() Returns the XMLType contents as a CLOB
value
getStringVal() Returns the XMLType value as a string value
getNumberVal() Returns the XMLType mode as a numeric
value
isFragment() Returns the value 1 if the document is a
fragment; otherwise, returns 0 (when the
XML declaration is present)

SELECT e.resume.getClobVal()
FROM emp_resumes e
WHERE employee_id = 100;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Subset of XMLType Member Functions
U s
A I
XMLType is an object-relational structure that provides methods called member functions
that perform operations on the data stored in XMLType. The slide shows a subset of

O
XMLType member functions that can be used when a column or function return type is an
XMLType instance. The example in the slide returns an XMLType as its CLOB value:
RESUME
l &
n
<?xml version="1.0"?> a
-----------------------------------------

<RESUME>

te r
<FULL_NAME>Steven King</FULL_NAME>

I n
<JOB_HISTORY>
<JOB_ID>AD_PRES</JOB_ID>

c l e
<JOB_HISTORY>
</RESUME>

r a
The correlation variable (e) is required to execute XMLType member functions.
Note
O
• The isFragment() function determines that an XMLType is not a fragment if the
data returned contains the XML declaration: <?xml version="1.0"?>.
• The getNumberVal() function returns the numeric value of a target node if the
node really contains a string of digits; otherwise, an error is generated.
Oracle 10g: XML Fundamentals 11-11
Querying an XMLType by Using XPath

The SQL and XMLType functions that use XPath


expressions are:
• existsNode()
SQL function: existsNode(xmltype, xpath-expr)
XMLType function: xmltype.existsNode(xpath-expr)

• extract()
SQL function: extract(xmltype, xpath-expr)
XMLType function: xmltype.extract(xpath-expr)

• extractValue()
SQL function: extractValue(xmltype,xpath-expr)
XMLType function: xmltype.extractValue(xpath-expr)

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Querying an XMLType by Using XPath
U s
A I
Based on the World Wide Web Consortium (W3C) XPath standard, XPath enables the
traversal of nested XML elements by specifying a slash-separated list of element, attribute,

O
and function names. Oracle XML DB provides the application developer with the ability to
express hierarchical queries against XML documents by using XPath expressions in the
following XMLType functions:
l &
n a
• The existsNode() function evaluates whether a given document contains a node
that matches the XPath expression. If the XMLType column contains the node, the

te r
function returns 1; otherwise, it returns 0.
• The extract() function is used to return a node or collection of nodes identified by

I n
the XPath expression. The result is an XMLType instance, which can be an entire

l e
document or a document fragment.
• The extractValue() function is used to return the value of a text node or attribute
c
r a
values associated with an XPath expression from an XML document stored as an
XMLType. It returns a scalar data type.
O
Note: The slide shows the syntax for using the functions either as a SQL function or as an
XMLType member function. In the latter case, a correlation variable is required to execute
the XMLType member function. For example, e is the correlation variable in the query:
SELECT e.resume.extract('/RESUME/FULL_NAME/text()') name
FROM emp_resumes e;
Oracle 10g: XML Fundamentals 11-12
Using the existsNode() Function

• As a SQL function:
SELECT COUNT(*)
FROM emp_resumes
WHERE existsNode(resume,
'/RESUME[FULL_NAME="Steven King"]') = 1;

• As an XMLType member function:


SELECT employee_id
FROM emp_resumes e
WHERE e.resume.existsNode(
'//JOB_ID[text()="AD_VP"]') = 1;

• In the SELECT list:


SELECT employee_id, existsNode(resume,
'//JOB_ID[text()="AD_VP"]') VP
FROM emp_resumes;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the existsNode() Function
U s
A I
The most common use for the existsNode() function is in the WHERE clause of a SQL
SELECT, UPDATE, or DELETE statement. In this situation, the XPath expression passed to

O
the existsNode() function is used to determine which of the XML documents stored in
the table will be processed by the SQL statement. Based on the three rows inserted in the
&
emp_resumes table shown in the section titled “Loading Data into XMLType”:
l
COUNT(*)
n a
• The result for the first example in the slide is:
----------
1
te r

I n
The result for the second example in the slide:
EMPLOYEE_ID

l e
-----------

c 101

• r a 102
The result for the last example is:
O EMPLOYEE_ID VP
----------- ----------
100 0
101 1
102 1
Oracle 10g: XML Fundamentals 11-13
Using the extract() Function

The extract() function:


• Accepts an XPath expression parameter
• Returns an XMLType instance
• Can be used for pretty printing of XML results
Example:
SELECT e.resume.extract('//JOB_ID/text()') result
FROM emp_resumes e
WHERE e.employee_id = 100;

Result:
RESULT
-----------------
AD_PRES

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the extract() Function
U s
A I
The extract() function takes an XPath expression as its argument and returns an
XMLType instance. The example in the slide extracts the text node value of the JOB_ID

O
node in the XML fragment and displays the string result. A SQL example that uses the

example in the slide:


l &
getStringVal() XMLType function, although redundant, yields the same result as the

SELECT extract(resume,
n a
te r
'//JOB_ID/text()').getStringVal() result
FROM emp_resumes e

I n
WHERE e.employee_id = 100;
Note: The correlation variable (e) used in the query example in the slide is required to

l e
execute the extract() method of the resume object instances.
c
r a
Tip: To conform with the SQL/XML standard, the XML results from queries are formatted
without white space between element tags. However, using the extract() function on
O
any XML result will force pretty printing of XML element tags by including some white
space. For example, if a query returns an XMLType result and does not use an extract()
function, append the .extract('/*') on the XMLType result to force a pretty output
format.

Oracle 10g: XML Fundamentals 11-14


Using the extract() Function

• Extracting a fragment:
SELECT employee_id,
e.resume.extract('//FULL_NAME') result
FROM emp_resumes e;
EMPLOYEE_ID RESULT
----------- -------------------------------------
100 <FULL_NAME>Steven King</FULL_NAME>
101 <FULL_NAME>Neena Kochhar</FULL_NAME>
102 <FULL_NAME>Lex De Haan</FULL_NAME>
• Testing for fragments:
SELECT extract(resume,'//JOB_HISTORY') result,
extract(resume,'//JOB_HISTORY').isFragment() frag
FROM emp_resumes
WHERE employee_id = 101;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the extract() Function (continued)
U s
A I
The extract() function is used when the XPath expression can result in a collection of
nodes being returned, that is, the XPath expression may identify a single node, a set of

O
nodes, or a text node value. The nodes are always returned as an XMLType instance either
as a fragment or an entire document. The statement in the slide returns an XMLType of an

l &
XML document fragment containing the FULL_NAME node found in the resume
XMLType columns.

n a
te r
Extracting fragments of the XML data can result in data that is not well-formed because the
result may contain more than one root node. To check whether the result is a fragment, use

RESULT
I n
the isFragment() function, as shown in the last example which returns the result:
FRAG

c l e
---------------------------------------- ----------
<JOB_HISTORY> 1

r a <JOB_ID>AD_VP</JOB_ID>
</JOB_HISTORY>
O
Note: The value 1 indicates that it is a fragment because of the absence of the XML
declaration. Using
SYS_XMLGEN(extract(resume,'//JOB_HISTORY')).isFragment() returns
0 indicating that the result is not a fragment because the SYS_XMLGEN adds the XML
declaration to the result.
Oracle 10g: XML Fundamentals 11-15
Combining extract() and existsNode()

• It is typical to combine extract() and


existsNodes() in the same query.
• Example:
SELECT employee_id,
extract(resume, '//JOB_ID/text()') result
FROM emp_resumes
WHERE existsNode(resume,
'/RESUME[FULL_NAME="Steven King"]') = 1;

• Results:
EMPLOYEE_ID RESULT
----------- --------------------
100 AD_PRES

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Combining extract() and existsNode()
U s
A I
It is common to find that extract() is used to obtain a text value, a node, or set of nodes
from an XMLType column based on a condition that uses existsNode() to check for the

O
presence of some node or value in the XML data. The example in the slide extracts the text

is Steven King.
l &
value of the JOB_ID descendant element for an employee whose full name text node value

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 11-16
Using the extractValue() Function

• Extracting the text value of a “single” node does


not require using the text() XPath function:
SELECT employee_id,
extractValue(resume, '//FULL_NAME') result
FROM emp_resumes;
EMPLOYEE_ID RESULT
----------- --------------------
100 Steven King
101 Neena Kochhar
102 Lex De Haan
• In comparison, using extract() requires using
the text() XPath function:
SELECT employee_id,
extract(resume,'//FULL_NAME/text()') result
FROM emp_resumes;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the extractValue() Function
U s
A I
The extractValue() function can return the text value of a single node or attribute
value. An error is generated if multiple nodes are returned. The extractValue()

O
function can be used in the WHERE clause of a SELECT, UPDATE, or DELETE statement,
making it possible to perform joins between tables containing XMLType columns or other
&
relational tables. The query in the slide shows the use of the extractValue() function
l
n a
in both the SELECT list, and compares it to using the extract() function containing an
XPath expression with the text() function.

te r
Note: Although not required, the text() function may be used in the XPath expression
supplied with the extractValue() function. An example that uses extractValue()
I n
and extract() functions without the text() XPath function in the expression is:

c l e
SELECT employee_id, extract(resume,'//JOB_ID') extract,
extractValue(resume,'//JOB_ID') extract_value

r a FROM emp_resumes;
The following results highlight the differences between the two functions:
O EMPLOYEE_ID
-----------
100
EXTRACT
-------------------------
<JOB_ID>AD_PRES</JOB_ID>
EXTRACT_VALUE
--------------------
AD_PRES
101 <JOB_ID>AD_VP</JOB_ID> AD_VP
102 <JOB_ID>AD_VP</JOB_ID> AD_VP
Oracle 10g: XML Fundamentals 11-17
Filtering with extractValue()

• Searching XML data:


SELECT employee_id,
extract(resume,'/RESUME/JOB_HISTORY') result
FROM emp_resumes
WHERE extractValue(resume,'//JOB_ID') = 'AD_PRES';

• Searching relational data:


SELECT last_name, salary
FROM emp_resumes er, employees e
WHERE e.employee_id = er.employee_id
AND extractValue(er.resume,'//JOB_ID') = e.job_id;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Filtering with extractValue()
U s
A I
The examples in the slide show how to use the extractValue() function in the WHERE
clause of a query to retrieve the text value from the XMLType instance content, and use the

O
value to form the comparison in the condition The first example in the slide extracts the

l &
JOB_HISTORY element, as an XML fragment, for employees whose resume XMLType
contains the text value AD_PRES. The result is:
EMPLOYEE_ID RESULT
n a
te r
----------- ------------------------------
100 <JOB_HISTORY>

I n <JOB_ID>AD_PRES</JOB_ID>
</JOB_HISTORY>

l e
The second example joins the emp_resumes and employees table and displays the last
c
name and salary for employees whose job_id column value is the same as the text value

r a
extracted from the JOB_ID descendant element in the resume column. The result is:

O LAST_NAME SALARY
---------- ----------
King 24000
Kochhar 17000
De Haan 17000
Oracle 10g: XML Fundamentals 11-18
Summary

In this lesson, you should have learned how to:


• Describe XMLType
• Create objects of XMLType
• Describe XMLType storage options
• Load data into XMLType
• Retrieve data from XMLType columns
• Use XMLType member functions called methods
• Use XPath functions on XMLType data

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
In this lesson, you learned how the XMLType data type is an integral part of the Oracle
XML database environment. You learned to create XMLType columns, object tables of
XMLType instances, and object types with an XMLType attribute.
O
The lesson showed you how to use SQL operations to insert and query XML data stored in

l &
the XMLType instances in columns of relational tables, and use various member functions
of XMLtype.

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 11-19
Practice 11: Overview

This practice covers the following topics:


• Creating XMLType columns
• Inserting data into XMLType columns
• Querying XMLType columns
• Using existsNode(), extractValue(), and
extract()

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Oracle 10g: XML Fundamentals 11-20
Practice 11
The goal of this practice is to work with XMLType. Use SQL*Plus for these tasks.
1. Create a table to store employee internal orders. The table must contain two columns,
employee_id and order_document. The employee_id column must be
numeric and the order_document column must be of XMLType. The table can be
called internal_orders.
2. Using script lab_11_02.sql, insert some data into the table created in the previous
question.
3. Query the internal_orders table to select the number of purchase orders for
employee 100.
4. In SQL*Plus, enter SET HEADING OFF, and then COL order_document
format a60. Then, write a query on the internal_orders table to retrieve the
purchase order for the employee called King.
Hint: Use the LIKE operator and use SQL*Plus SET LONG nn to increase the
amount of XML data you want to see.
5. Use the extract function to get the text value of the Description element from the
order_document column.
6. Use the existsNode() function to determine the number of purchase orders for the
user King.
7. Use the extractValue() function to obtain the value of the User node from
internal_orders table where Description contains “Amarcord.”
8. Retrieve the content of the order_document column from the
internal_orders table.
n l y
e O
U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 11-21
n l y
e O
U s
A I
O
l &
na
te r
I n
c le
ra
O
Creating XMLType Views

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Create non-schema-based XMLType views
• Create XML Schema-based XMLType views
• Create XMLType views from XMLType tables
• Perform DML on XMLType views

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
In this lesson, you learn to create XMLType views to present relational, or object-relational
data in an XML format. You learn how to create and use non-schema-based and XML
Schema-based XMLType views.
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 12-2
What Are XMLType Views?

An XMLType view:
• Wraps existing relational and object-relational
data in XML formats
• Shows data as a collection of XMLType instances
• Can be one of the two types:
– Non-schema-based
– XML Schema-based

Relational XML
table

Object XMLType
XMLType
table view objects

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
What Are XMLType Views?
U s
A I
An XMLType view wraps the existing data stored in the relational and object-relational
tables in XML formats. Similar to an object view, an XMLType view presents the contents
as XMLType instances.
O
There are two types of XMLType views:
l &
• Non-schema-based views, which do not conform to an XML Schema definition

n a
• XML Schema-based views, which conform to a registered XML Schema definition

te r
Use XML Schema-based view to provide stronger typing of the data.

I n
The main advantages of using XMLType views are the ability to:
• Exploit Oracle XML DB features by using XML Schema functionality without

l e
migrating the legacy data
c
• Experiment with various other forms of storage, besides the object-relational or CLOB

r a
storage choices available to the XMLType tables

O
Note: XMLType views can be optimized by the Oracle Database 10g that can use XPath
Rewrite functionality.

Oracle 10g: XML Fundamentals 12-3


Creating XMLType Views

An XMLType view may be created by using:


• SQL/XML operators
• Object types Object
types

XMLType
view
SQL/XML
operators

Object Object Object


tables views constructors
Relational XML
tables Relational
Schema
tables
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating XMLType Views
U s
• Based on SQL/XML generation functions, such as XMLElement(),
A I
As illustrated in the slide, an XMLType can be created in the following ways:

O
XMLForest(), XMLConcat(), XMLAgg() and the XMLColAttVal()Oracle

l &
Database extension function. SQL/XML generation functions can be used to construct
both non-schema-based XMLType views and XML Schema-based XMLType views.
a
• Based on object types, object views and the SYS_XMLGEN() function. Non-schema-
n
te r
based XMLType views can be constructed by using object types, object views, and the
SYS_XMLGEN() function. XML Schema-based XMLType view can be constructed

n
by using object types, and object views, and directly from an XMLType table.
I
c l e
Note: Except for XMLType views based on an XMLType table, you can use these
techniques to construct the XMLType view from underlying relational or object-relational

r
into XML. a
tables directly, without physically migrating the relational or object-relational legacy data

O
Note: Creating an XMLType view by using object tables and views is discussed in the
section titled “XML Schema XMLType Views with Object Types,” without an example. For
more information, refer to the Oracle XML DB Developer’s Guide 10g Release 1 (10.1).

Oracle 10g: XML Fundamentals 12-4


Creating Non-Schema-Based Views

Non-schema-based XMLType views are:


• Not constrained by a registered XML Schema
• Created in two ways:
– Using SQL/XML functions
– Using object types and views with SYS_XMLGEN()
• Created by using the CREATE VIEW statement with
the following syntax:
CREATE OR REPLACE VIEW view_name
OF XMLType WITH OBJECT ID {DEFAULT|(expression)}
AS sql_query;

Note: Set the OBJECT_ID using:


extract(OBJECT_VALUE,'...').getNumberVal()
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating Non-Schema-Based Views
U s
Non-schema-based XMLType views can be created in two ways:

A I
• Writing a query that exploits the XSQL/XML generation functions to format the
relational data as XML
O
l &
• Using a query that calls the SYS_XMLGEN() function whose argument is a SQL
object created from an object type definition

n a
In either case, the XMLType view is created by using a CREATE VIEW OR REPLACE

te r
statement with the OF XMLType WITH OBJECT ID clause, as shown in the slide.
Note: Non-schema-based XMLType views are not constrained by an XML Schema

I n
definition, and can be more flexible with the way XML elements are generated.

l e
In an Oracle database, object tables, XMLType tables, object views, and XMLType views
c
do not have column names specified. Therefore, a system-generated pseudocolumn

r a
OBJECT_ID can be used in queries. The OBJECT_ID uniquely identifies objects in an

O
object view by using the WITH OBJECT ID clause and the DEFAULT keyword, or by
specifying an expression to be used as a unique identifier. To set the object ID, it is
recommended that you specify an expression that uses the extract() function with the
getNumberVal() method of the XMLType, for example:
extract(OBJECT_VALUE,'/region/region_id').getNumberVal()
Oracle 10g: XML Fundamentals 12-5
Non-Schema XMLType Views with
SQL/XML Functions

• Create the view:


CREATE OR REPLACE VIEW emp_view OF XMLType
WITH OBJECT ID (extract(
OBJECT_VALUE,'/employee/@empno').getNumberVal())
AS SELECT XMLElement("employee",
XMLAttributes(employee_id AS "empno"),
XMLForest(e.last_name AS "last_name",
e.hire_date AS "hiredate",
e.salary as "salary")) AS "result"
FROM employees e
WHERE salary > 15000;
• Query the view:
SELECT * FROM emp_view;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Non-Schema XMLType Views with SQL/XML Functions
U s
A I
The slide shows an example of creating a non-schema-based XMLType view by using
SQL/XML generation functions. The results of the query executed on the view are:
SYS_NC_ROWINFO$
O
--------------------------------------------------

l &
<employee empno="100"><last_name>King</last_name><

a
hiredate>17-JUN-87</hiredate><salary>24000</salary

n
r
></employee>

I n te
<employee empno="101"><last_name>Kochhar</last_nam
e><hiredate>21-SEP-89</hiredate><salary>17000</sal

c l e
ary></employee>

r a <employee empno="102"><last_name>De Haan</last_nam


e><hiredate>13-JAN-93</hiredate><salary>17000</sal

O ary></employee>
Note: The view obtains the data from relational tables. The example in the slide creates a
view of XMLType objects, each of which represents an employee element, with an
empno attribute, and contains the last_name, hiredate, and salary child elements.

Oracle 10g: XML Fundamentals 12-6


Non-Schema XMLType Views with Object
Types and SYS_XMLGEN()

• Create the object type:


CREATE TYPE employee_t AS OBJECT (
"@empno" NUMBER(6),
name VARCHAR2(30),
paycheck NUMBER(8,2));
/

• Create the view by using SYS_XMLGEN():


CREATE OR REPLACE VIEW empobj_view OF XMLType WITH
OBJECT ID (EXTRACT(
OBJECT_VALUE,'/employee/@empno').getnumberval())
AS SELECT SYS_XMLGEN(
employee_t(e.employee_id, e.last_name, e.salary),
XMLFormat('EMPLOYEE'))
FROM employees e
WHERE salary > 15000;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Non-Schema XMLType Views with Object Types and SYS_XMLGEN()
U s
The example in the slide shows the creation of:
• An object type called employee_t
A I
O
• The XMLType view called empobj_view, based on the employee_t object type.
The XMLType view uses the SYS_XMLGEN() function with an employee_t object

l &
argument. Each object instance is derived from rows in the EMPLOYEES table. The query:
SELECT * from empobj_view;

n a
Produces the following result:
SYS_NC_ROWINFO$
te r
----------------------------

I n
<?xml version="1.0"?>

c l e
<EMPLOYEE empno="100">
<NAME>King</NAME>

r a <PAYCHECK>24000</PAYCHECK>
</EMPLOYEE>

O <?xml version="1.0"?>
<EMPLOYEE empno="101">
<NAME>Kochhar</NAME>
<PAYCHECK>17000</PAYCHECK>
</EMPLOYEE>
...
Oracle 10g: XML Fundamentals 12-7
Creating XML Schema-Based Views

XML Schema-based XMLType views:


• Require the XML Schema to be registered first
• Are constrained by the registered XML Schema
• Are created by using the CREATE VIEW statement
with the following syntax:
CREATE OR REPLACE VIEW view_name OF XMLType
XMLSCHEMA "url" ELEMENT "element-name"
WITH OBJECT ID {DEFAULT|(expression)}
AS sql_query;
– Identifying the XML Schema in the XMLSCHEMA
clause
– Specifying the document element in the ELEMENT
clause

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating XML Schema-Based Views
U s
A I
To create XMLType views based on an XML Schema, known as XML Schema-based
XMLType views, you must first register the XML Schema in the database. XML Schema is

O
registered by using the DBMS_XMLSCHEMA.registerSchema() PL/SQL packaged

l &
procedure, as discussed in the lesson titled “Introducing Oracle XML Database.”
After the XML Schema has been registered, the XMLType view can be defined by using the

n a
XMLSCHEMA clause to specify a URL identifying the location of the registered XML

registered schema.
te r
Schema. The ELEMENT clause specifies the name of the document (root) element in the

I n
Note: The url string and element-name values are enclosed in double quotes.

c le
r a
O
Oracle 10g: XML Fundamentals 12-8
XML Schema XMLType Views with
SQL/XML Functions

Register the XML Schema:


BEGIN
DBMS_XMLSCHEMA.registerSchema('region.xsd',
'<xsd:schema version="1.0"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="region">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="region_id" type="xsd:int"/>
<xsd:element name="region_name"
type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>', TRUE, TRUE, FALSE);
END;
/

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Schema XMLType Views with SQL/XML Functions
U s
A I
The schema is registered by using the DBMS_XMLSCHEMA.registerSchema()
procedure, as shown in the slide. The XML Schema in the slide does not define a

O
targetNamespace. Therefore, the XML instances that reference this XML definition

(See the example on the next page.)


l &
must use the the xsi:noNamespaceSchemaLocation attribute in their root element.

n a
Note: If the XML Schema declares targetNamespace, then rows in the XMLType view

te r
definition must reference the XML Schema document by including the following attributes:
• The xmlsns:xsi namespace attribute mapped to the URL,

I n
http://www.w3.org/2001/XMLSchema-instance

c l e
• The xsi:schemaLocation attribute mapped to the targetNamespace
followed by a space and the Schema document name

r a
• An xmlns attribute as the default or prefixed namespace mapped to the
targetNamespace
O
Oracle 10g: XML Fundamentals 12-9
XML Schema XMLType Views with
SQL/XML Functions

Create the XML-Schema-based XMLType view:


CREATE OR REPLACE VIEW region_xmlv OF XMLType
XMLSCHEMA "region.xsd" ELEMENT "region"
WITH OBJECT ID (extract(OBJECT_VALUE,
'/region/region_id').getNumberVal())
AS SELECT XMLElement("region",
XMLAttributes(
'http://www.w3.org/2001/XMLSchema-instance' AS
"xmlns:xsi",
'region.xsd' AS
"xsi:noNamespaceSchemaLocation"),
XMLForest(region_id AS "region_id",
region_name AS "region_name"))
FROM regions;
Note: The noNamespaceSchemaLocation attribute

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Schema XMLType Views with SQL/XML Functions (continued)
U s
SELECT * FROM region_xmlv WHERE ROWNUM < 3;
A I
After the XML Schema XMLType view is created, you can query the data, for example:

O
This query returns the following results in SQL*Plus by using a column format of 55
characters wide with word wrapping:
SYS_NC_ROWINFO$
l &
a
-------------------------------------------------------
n
<region

te r
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

I n
xsi:noNamespaceSchemaLocation="region.xsd"><region_id>1
</region_id><region_name>Europe</region_name></region>

c l e
<region

r a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="region.xsd"><region_id>2
O </region_id><region_name>Americas</region_name></region
>
Note: Each row is returned as an XML fragment with the appropriate attributes in their root
elements.
Oracle 10g: XML Fundamentals 12-10
Using Namespaces with
SQL/XML Functions

When the XML Schema defines targetNamespace,


use partially escaped mapping in SQL/XML functions
to create elements with namespaces and prefixes.
CREATE OR REPLACE VIEW region_ns_xmlv OF XMLType
XMLSCHEMA "region_ns.xsd" ELEMENT "region"
WITH OBJECT ID (extract(OBJECT_VALUE,
'/region/region_id').getNumberVal()) AS
SELECT XMLElement("rgn:region",
XMLAttributes(
'http://www.w3.org/2001/XMLSchema-instance' AS
"xmlns:xsi",
'http://www.hr.com/regions' AS "xmlns:rgn",
'http://www.hr.com/regions region_ns.xsd' AS
"xsi:schemaLocation"),
XMLForest(region_id AS "rgn:region_id",
region_name AS "rgn:region_name"))
FROM regions;
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using Namespaces with SQL/XML Functions
U s
If the XML Schema declares the targetNamespace attribute with the

A I
http://www.hr.com/regions URI in its schema definition, then the XMLType view can refer

O
to targetNamespace with a default or prefixed namespace. The example in the slide

l &
uses a namespace prefix when creating the XMLType view, which also applies partially
escaped mapping in SQL/XML functions for the rgn namespace prefix. In the example:
a
• The XMLElement() and XMLForest() functions use the rgn prefix in their
n
element names.

te r
• The XMLAttributes() function declares the xsi:schemaLocation and

I n
xmlns:rgn attributes, each using the value of the targetNamespace attribute as
appropriate for the XML Schema document.

c l e
The query: SELECT * FROM region_ns_xmlv WHERE ROWNUM = 1;
Produces:
r a <rgn:region
O xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rgn="http://www.hr.com/regions"
xsi:schemaLocation="http://www.hr.com/regions
region_ns.xsd"><rgn:region_id>1</rgn:region_id><rgn:reg
ion_name>Europe</rgn:region_name></rgn:region>
Oracle 10g: XML Fundamentals 12-11
XML Schema XMLType Views
with Object Types

The steps to create an XMLType view by using object


types are:
1. Create the object types.
2. Create or generate the XML Schema.
3. Register the XML Schema.
4. Create the XMLType view by using one of the
following:
a. One-step process
Use a query on the relational tables with its
columns in the object constructor.
b. Two-step process:
Create an object view.
Create an XMLType view on the object view.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
XML Schema XMLType Views with Object Types
U s
A I
The slide shows these steps for creating an XMLType view based on the SQL object types:
1. First, create the object types by using the CREATE TYPE statement.

O
2. Create an XML Schema definition manually, or generate the XML Schema by using

l &
the DBMS_XMLSCHEMA.generateSchema() function. For example, if you have
an object type called EMPLOYEE_T in the HR schema, you can generate the XML
a
Schema by using the following SELECT statement:
n
FROM dual;
te r
SELECT DBMS_XMLSCHEMA.generateSchema('HR','EMPLOYEE_T')

I n
3. After the XML Schema is created or generated, register the XML Schema in the
database as shown in the previous pages.

l e
4. Finally, create the XMLType view by using a one-step or a two-step process.
c
r a
The one-step process for creating an XMLType view defines a SELECT statement that
queries the SQL object type constructors filled with the relational column values from the
O
relational tables in the FROM clause.
In the two-step approach, first create an object view with a query like that of the one-step
approach, and then create an XMLType view with its query selecting the object values from
the object view.
Oracle 10g: XML Fundamentals 12-12
Creating XMLType Views from
XMLType Tables

To create an XMLType view on an XMLType table:


• Create and populate the XMLType table:
CREATE TABLE region_xmltab OF XMLType
XMLSchema "region.xsd" ELEMENT "region";
INSERT INTO region_xmltab
VALUES (XMLType(
'<region xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="region.xsd">
<region_id>5</region_id>
<region_name>Japan</region_name>
</region>'));
• Create the XMLType view:
CREATE OR REPLACE VIEW region_xmltabv OF XMLType
XMLSchema "region.xsd" ELEMENT "region"
AS SELECT value(r) FROM region_xmltab r;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Creating XMLType Views from XMLType Tables
U s
A I
The first example in the slide shows the step of creating and populating an XMLType table
with an instance of an XML document conforming to the XML Schema specified. The

O
second example is a simple XMLType view definition based on the XMLType table.

l &
Typically, the XMLType view performs more work than the simple query of the XMLType
table. For example, the view can restrict data obtained from the table:
a
CREATE OR REPLACE VIEW region_xmlview OF XMLType
n
te r
XMLSchema "region.xsd" ELEMENT "region"
AS SELECT value(r) FROM region_xmltab r
WHERE extractValue(value(r),'/region/region_id')='5';

I n
You may transform table data by using the XMLTransform() function:

l e
CREATE OR REPLACE VIEW region_xmlview OF XMLType

cXMLSchema "region.xsd" ELEMENT "region"

r a AS SELECT XMLTransform(value(r), XMLType(


'<?xml version="1.0"?>
O <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
...
</xsl:stylesheet>'))
FROM region_xmltab r;
Oracle 10g: XML Fundamentals 12-13
DML with XMLType Views

An XMLType view:
• Is updateable if its underlying objects are
inherently updateable
• Is not directly updateable if the underlying objects
are not directly updateable, and requires DML
operations to be performed in INSTEAD OF
triggers
Note: The steps to create an updateable XMLType view
are similar to creating an XMLType view with SQL
object types.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
DML with XMLType Views
U s
A I
An XMLType view may be updateable provided all its underlying objects are directly
updateable. However, when the underlying objects are not directly updateable, the

O
XMLType view will not be updateable, and will require DML operations to be performed in
the INSTEAD OF triggers.

l &
The steps to create an updateable XMLType view is similar to creating an XMLType view
based on SQL object types:
n a
1. Create the object type.

te r
2. Create or generate, and register the XML Schema.

I n
3. Create the XMLType view by using the object type constructor populated with the

c l e
relational table columns in the SELECT clause, and the relational table in the FROM
clause of the view SELECT statement.

a
4. Perform the DML operations.
r
O
The next few pages illustrate these steps.

Oracle 10g: XML Fundamentals 12-14


Example of an Updateable XMLType View

1. Create the SQL object type:


CREATE TYPE region_t AS OBJECT(
"id" NUMBER,
"name" VARCHAR2(25));
/

2. Generate and register the XML Schema:


BEGIN
DBMS_XMLSCHEMA.registerSchema(
'http://www.hr.com/region_t.xsd',
DBMS_XMLSCHEMA.generateSchema(
USER,'REGION_T','region'),
TRUE, FALSE, FALSE);
END;
/

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example of an Updateable XMLType View
U s
A I
The first step in the example creates the region_t object type with a CREATE TYPE
statement. The object type attributes, id and name, are enclosed in double quotes to ensure

O
that their relative XML element names are in lowercase. Without the double quotes, the

l &
attribute names are stored and will have XML element names in uppercase.
The second step uses the DBMS_XMLSCHEMA.registerSchema() procedure to
a
register the XML Schema name ,http://www.hr.com/region_t.xsd, for the
n
te r
region XML root element and its children by using the output generated by the
DBMS_XMLSCHEMA.generateSchema() function, which accepts three arguments:

I n
1. The database schema name owning the region_t object type. The PL/SQL block in
the example makes uses of the database USER function, which generates a string for
l e
the user executing the block, such as 'HR'. You can enter a single-quoted string
c
r a
containing the database schema name.
2. The object type name REGION_T identifying the object structure from which the
O XML Schema is generated. The object name is in uppercase because it is stored in the
data dictionary in uppercase by default, that is, the CREATE TYPE statement did not
enclose the type name in double quotes.
3. The name for the document root element in the generated XML Schema definition (in
this case, the document element) set to region in lowercase
Oracle 10g: XML Fundamentals 12-15
Example of an Updateable XMLType View

3. Create the XMLType View


CREATE OR REPLACE VIEW region_upd_xmlv OF XMLType
XMLSCHEMA "http://www.hr.com/region_t.xsd"
ELEMENT "region" WITH OBJECT ID
(object_value.extract(
'/region/id').getNumberVal())
AS SELECT region_t(r.region_id, r.region_name)
FROM regions r;
4. Perform the DML operation
INSERT INTO region_upd_xmlv
VALUES (XMLType(
'<region xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation=
"http://www.hr.com/region_t.xsd">
<id>5</id>
<name>Pacific</name>
</region>'));

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Example of an Updateable XMLType View (continued)
U s
A I
The third step creates the XMLType view, based on the XML Schema registered in the
second step. The OBJECT ID is obtained from the id element value in each region XML
fragment. The view query selects a region_t object instance with attribute values derived
O
from the region_id and region_name columns in the regions relational table. This
&
is a good example of wrapping relational data into an XML structure.
l
n a
The final step is to perform the DML operations. The example in the slide shows an
INSERT statement adding a new XMLType object into the view. After the insert, if you
execute:
te r
SELECT * FROM regions WHERE region_id = 5;
The row returned is:
I n
l e
REGION_ID REGION_NAME
---------- -------------------------
c
a
5 Pacific

O r
To update the name value for an element with an id value of 5, executing the following
UPDATE statement alters the region_name column for that row to Japan:
UPDATE region_upd_xmlv r
SET r.object_value = updateXML(r.object_value,
'/region/name/text()', 'Japan')
WHERE existsNode(r.object_value, '/region[id=5]') = 1;

Oracle 10g: XML Fundamentals 12-16


Summary

In this lesson, you should have learned how to:


• Create XMLType views without an XML Schema for
validation by using SQL/XML functions, or
SYS_XMLGEN() with objects
• Create XML Schema-based XMLType views based
on SQL/XML functions, or object tables and views
• Create XMLType Views from XMLType tables for
restricting or transforming XMLType data
• Perform DML on XMLType views

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
In this lesson, you discovered how to create and use XMLType views that do not conform to
an XML Schema called non-schema-based XMLType views, and strongly-typed XMLType

O
views that conform to an XML Schema definition known as XML Schema-based XMLType
views.

l &
The purpose of XMLType views is to present existing relational, and object-relational data
in an XML format.
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 12-17
Practice 12: Overview

This practice covers the following topics:


• Creating a non-schema-based XMLType view of
employees by using SQL/XML functions
• Creating an updateable XML Schema-based
XMLType view based on an object type by using
the department data

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Oracle 10g: XML Fundamentals 12-18
Practice 12
The goal of this practice is to create a non-schema-based XMLType view of employees by
using SQL/XML functions, and an updateable XML Schema-based XMLType view based
on an object type by using the department data.
1. Create a non-schema-based XMLType view of employee data.
a. Start SQL*Plus (if not already started) and log in with your username and
password to the course database.
Note: You can start SQL*Plus by using the hr connection in JDeveloper.
b. In JDeveloper, right-click XMLLabsProject, select New…, expand the
Database Tier category, and click Database Files. Double-click SQL File in the
the Items section. In the File name field, enter employee_xmlv.sql and
click Ok.
c. Edit the employee_xmlv.sql file in JDeveloper and create an XMLType
view called employee_xmlv that uses SQL/XML generation functions to form
the XML structure. For each employee row, use employee as the root element
containing the employee_id and department_id as attributes, and child
elements for the first_name, last_name, job_id, and salary. Use the
employee_id attribute in the WITH OBJECT ID expression. Save changes
to the file.
Note: The element and attribute names are the same as the column names but in
lowercase.
d. Execute the E:\labs\lab\employee_xmlv.sql file in SQL*Plus to
create the view object.
n l y
Note: You can cut and paste the text between windows or use the @file.sql
SQL*Plus command.
e O
three rows.
U s
e. In SQL*Plus, write a query on the employee_xml view to display the first

A I
Hint: Use the ROWNUM pseudocolumn in the WHERE clause.
Note: To control the output display format execute the script called

O
E:\labs\lab\lab_12_01_c.sql or enter the following SQL*Plus
commands before executing the query: set pagesize 60, set long

l &
500, column SYS_NC_ROWINFO$ format a70 word.

a
f. In SQL*Plus, write a query to display employee_xml rows with a
n
WHERE clause.
te r
department_id value of 60 by using the existsNode() function in the

I n
g. In SQL*Plus, write a query to display employee_xml rows with last_name
starting with the uppercase letter P.

c l e
r a
O
Oracle 10g: XML Fundamentals 12-19
Practice 12 (continued)
2. Create an updateable XML-Schema-based XMLType view for the DEPARTMENTS
table.
a. In SQL*Plus, create an object type called DEPARTMENT_T with the attribute
names: ID, NAME, MANAGER_ID, LOCATION_ID with the same database data
type as their associated columns in the DEPARTMENTS table.
Hint: In SQL*Plus, use the DESCRIBE departments command to view the
table and column data type details.
Note: Do not double-quote the object type or its attribute names, so that they are
stored in uppercase in the data dictionary.
b. In SQL*Plus, register an XML Schema with the name
http://www.hr.com/department_t.xsd generated from the
DEPARTMENT_T object type, assigning the name DEPARTMENT (in uppercase)
for the root element of the XML Schema.
Note: Use the E:\labs\lab\lab_12_02_b.sql file as a template for this
step.
c. In SQL*Plus, create the XMLType view called department_xmlv to query
all rows in the DEPARTMENTS table by using the relational column names as
arguments in the DEPARTMENT_T object constructor used in the query. Use the
numeric value of the /DEPARTMENT/ID path in the OBJECT ID expression.
Save the CREATE VIEW statement in a file called department_xmlv.sql
after it is executed.
d. In SQL*Plus, write a query on the department_xmlv to display XML
fragments for departments with a LOCATION_ID of 1800. n l y
elements for each fragment.
e O
Note: First, execute a SET LONG 200 command to display all the XML

s
e. Insert a new department with the name Education Services, with a
U
A I
MANAGER_ID value of 201, and LOCATION_ID of 1800. Use the
DEPARTMENTS_SEQ sequence to generate the value for the ID element.

O
Hint: Concatenate DEPARTMENTS_SEQ.NEXTVAL to obtain the ID value.
Note: Use the E:\labs\lab\lab_12_02_e.sql file as a template for this
step.
l &
n a
f. In SQL*Plus, write a query to display departments in location_id 1800, to
confirm that the new row is inserted into the DEPARTMENTS relational table.

te r
Commit the operation.

command:
I n
Note: Format the DEPARTMENT_NAME column using the following SQL*Plus

c l e
COL DEPARTMENT_NAME FORMAT A30

r a
O
Oracle 10g: XML Fundamentals 12-20
Executing SQL Operations on XML

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Transform XML by using SQL functions
• Perform updates on XML data by using the
updateXML() function
• Delete rows based on XML contexts by using the
existsNode() function
• Create CTXXPATH and context indexes on the
XMLType columns

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
In this lesson, you learn about different SQL operations that can be done with XMLType
instances. You also learn to transform XML by using XSL stored in the database. You learn

O
to update and delete XML documents and content, and about the types and benefits of

&
indexes that you can create on XMLType instances.

l
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 13-2
Overview of Transforming XML

XMLType
instance
XDK

XSL

XMLTransform()
Stored

Object relational data CLOB

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Overview of Transforming XML
U s
A I
In Oracle XML DB, XMLType instances of the XML data stored in XMLType tables,
columns, or views can be transformed (formatted) into HTML, XML, and other mark-up

O
languages by using XSL stylesheets and the transform() XMLType function. This

l &
process conforms to the recommendation of the World Wide Web Consortium (W3C) XSLT
1.1. XMLType instances can be transformed by using the XMLTransform() SQL
a
function or the transform() member function of XMLType in the database.
n
te r
XML documents have structure but no format. To add format to the XML documents, you
can use Extensible Stylesheet Language (XSL). XSL provides a way of displaying XML

I n
semantics. It can map XML elements into other formatting or mark-up languages such as

c l e
HTML. XSL can be stored as XMLType in tables and columns, as a resource in the
repository, and as a B-file on the local file system. The Transform() function for

r a
XMLType takes an additional map argument that is not supported by XMLTransform()
in this release. You can also transform XML by using Oracle XML Developer’s Kit (XDK).
O
Oracle 10g: XML Fundamentals 13-3
Transform Functions

Transformation functions are:


• XMLTransform(XMLType, XMLType)
• XMLType.Transform(XMLType, XMLType)

XML (XMLType)
Output document
Transform (XMLType)
function
XSL (XMLType)
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Transform Functions
U s
A I
The XMLTransform() and XMLType.transform() functions transform an XML
document, by using the XSL stylesheet, into an output document. Both functions accept two
arguments:
O
1. The XML document as an XMLType instance

l &
2. The XSL stylesheet as an XMLType instance

n a
The transformation functions and returns a transformed output as an XMLType instance.

te r
The output can be transformed into another XML document, HTML page, or textual
information as specified by the XSL stylesheet template rules.

I n
You typically need to use XMLTransform() when retrieving and/or generating XML

l e
documents stored as XMLType in Oracle Database 10g. You can also use the

c
XMLTYPE.transform() function, which produces the same results as using the

r a
XMLTransform() function.

O
Oracle 10g: XML Fundamentals 13-4
Using the XMLTransform() Function

1. Store the XSL styleheet in an XMLType column:


CREATE TABLE stylesheets (
id NUMBER(4), xsldoc XMLType);
INSERT INTO stylesheets
VALUES (1, XMLType('<xsl:stylesheet ...'));
2. Store the XML document in an XMLType column:
CREATE TABLE xmldocuments (
id NUMBER(4), xmldoc XMLType);
INSERT INTO xmldocuments
VALUES (1, XMLType('<employees>...</employees>'));

3. Use XMLType columns in XMLTransform():


SELECT XMLTransform(xmldoc, xsldoc) result
FROM xmldocuments d, stylesheets s
WHERE d.id = s.id

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the XMLTransform() Function
U s
A I
The example in the slide shows the steps to make use of XML transformation in the database
by using the XMLTransform() function. The steps shown are the following:

O
1. Create a table with an XMLType column to store the XSL stylesheet to be used for

l &
transformations. Insert the XSL styleheet into the XMLType column of the
stylesheet table. The example uses the XMLType() constructor to create an
a
XMLType object that is inserted into the xsldoc column.
n
te r
2. Create a table to store the XML document in an XMLType column by using an
INSERT statement with the XMLType()object constructor.

I n
3. Use the XMLTransform() function to transform the XML document with id 1 in
the xmldocuments table by using the XSL stylesheet with id 1 from the

l e
stylesheets table. The query can also be written as follows:
c
a
SELECT XMLType.transform(xmldoc,

O r (SELECT xsldoc FROM stylesheets WHERE id = 1)) result


FROM xmldocuments d
WHERE d.id = 1
Note: The XMLType.transform() function can be used instead of the
XMLTransform() function. The complete code example is shown on the next page.

Oracle 10g: XML Fundamentals 13-5


Using the XMLTransform() Function (continued)
1. Create the stylesheets table and populate it with an XSL stylesheet document:
CREATE TABLE stylesheets (
id NUMBER(4)
CONSTRAINT stylesheets_pk PRIMARY KEY,
xsldoc XMLType);
--
INSERT INTO stylesheets VALUES (1,
XMLType(
'<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html><body>
<ul><xsl:apply-templates/></ul>
</body></html>
</xsl:template>
<xsl:template match="employees/employee">
<li><xsl:value-of select="first_name"/>,
<xsl:value-of select="last_name"/></li>
</xsl:template>
</xsl:stylesheet>'));
2. Create the xmldocuments table and populate the table with one XML document:
CREATE TABLE xmldocuments (
id NUMBER(4)
CONSTRAINT xmldocuments_pk PRIMARY KEY, n l y
--
xmldoc XMLType);

e O
INSERT INTO xmldocuments VALUES (1,
U s
I
XMLType(
'<?xml version="1.0"?>
<employees>
<employee>
O A
l &
<employee_id>100</employee_id>
<first_name>Steve</first_name>
a
<last_name>King</last_name>
n
</employee>
<employee>
te r
I n
<employee_id>101</employee_id>
<first_name>Neena</first_name>

c l e<last_name>Kocchar</last_name>
</employee>

r a </employees>'));
3. Execute a query by using the XMLTransform() function:
O SELECT XMLTransform(xmldoc, (SELECT xsldoc
FROM stylesheets WHERE id = 1)) result
FROM xmldocuments d
WHERE d.id = 1;

Oracle 10g: XML Fundamentals 13-6


Results of Using the XMLTransform()
Function

• Write the transformation query:


SELECT XMLTransform(xmldoc, (SELECT xsldoc
FROM stylesheets WHERE id = 1)) result
FROM xmldocuments d
WHERE d.id = 1;
• Spool these results to an HTML file for viewing in
a browser:
RESULT
---------------------------------------
<html>
<body>
<ul>
<li>Steve, King</li>
<li>Neena, Kocchar</li>
</ul>
</body>
</html>

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Results of Using the XMLTransform() Function
U s
document into an HTML page.
A I
The example presented in the preceding slides uses the XSL stylesheet to transform an XML

O
The HTML results can be copied and pasted into a text editor and saved, or spooled from

&
SQL*Plus, into a file with an htm or html extension.
l
n a
The HTML file can be viewed by using Internet Explorer or any other browser.
Alternatively, you can open the HTML file in JDeveloper and use the HTML Editor Preview

te r
tab to observe the final result.

I n
c l e
r a
O
Oracle 10g: XML Fundamentals 13-7
Benefits of XML Transformation

Using Oracle XML DB transformation functions


provides better performance when processing XML
stored in the database.
URL
Protocol handler
HTML
SQL XMLTransform()
Browser
contains contains

XMLType XMLType

XML document XSLT

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Benefits of XML Transformation
U s
A I
An XML document describes the content and does not provide presentation information.
Applying XSLT to an XML document can transform the XML content into a specific

O
presentation format. Oracle XML DB supports the W3C XSLT standard by providing

l &
support for performing XSLT transformations inside the database. Because the
transformation takes place close to the data, Oracle XML DB can optimize features such as
a
memory usage, I/O operations, and the network traffic required to perform the
n
te r
transformation. Most transformations are from XML to HTML or XML. Oracle XML DB
supports transformation to Wireless Markup Language (WML) as well.

I n
Using XDK Versus Oracle XML DB for XML Transformation

l e
Users who need to perform transformations in the middle tier must use the Oracle XML

c
Developer’s Kit (XDK). Middle-tier-based performance distributes processing, but can lead

r a
to additional complexity and some performance penalty. Using the XDK is the preferred

O
approach for accessing information stored outside the database.
Using the features of Oracle XML DB is best for processing XML and XSL data that is
stored within the database itself. Transformation in the database gives better overall
performance when data is stored in the database. However, the additional processing adds
more load to the database.
Oracle 10g: XML Fundamentals 13-8
Updating XML

• The updateXML() function changes the XML


element, text, and, attribute values in the XMLType
columns.
• Syntax:
updateXML(XMLType, XPath-expr1, value-expr1
[, XPath-expr2, value-expr2,...])

XMLType
XPath
Updated
value
XMLType
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Updating XML
U s
A I
XML documents stored in an XMLType column or table in the database can be updated by
using the updateXML() function. The updateXML() function can be used to update any

O
part of the XML document, such as an attribute value, a text node, an element, or a node
tree. The updateXML() function arguments are:

l &
• The name of the XMLType column to be updated
a
• One or more XPath and value expression pairs, where the XPath expression identifies
n
target node
te r
the target node to be updated, and the value expression specifies the new value for the

I n
If you update an XML element to NULL, the Oracle database removes the attributes and

c l e
children of the element, and the element becomes empty. If a text node of an element is
updated to NULL, then the text value is removed and the element is retained as an empty

r a
element. Setting an attribute to NULL sets the value to an empty string.
Note: If you are using object-relational storage, then the updateXML() function can
O
perform a piecewise update. If you are using CLOB storage, then the updateXML()
function writes out the entire CLOB.
The examples on the next few pages show how the updateXML() function can be used to
modify the contents of an XML document stored as an XMLType.
Oracle 10g: XML Fundamentals 13-9
Using the updateXML() Function

Example: Update the last_name text node.


• XML data:
<employees>
<employee>
<employee_id>100</employee_id>
<first_name>Steve</first_name>
<last_name>King</last_name>
</employee> ...
</employees>

• SQL with updateXML() function:


UPDATE xmldocuments
SET xmldoc = updateXML(xmldoc,
'/employees/employee/last_name/text()',
'Kingsley')
WHERE existsNode(xmldoc,
'/employees/employee[employee_id="100"]') = 1;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using the updateXML() Function
U s
identified by the XPath expression:
A I
In the example, the updateXML() function is used to update the value of the text node

'/employees/employee/last_name/text()'
O
l &
The WHERE clause uses an existsNode() function to target the employee node with the
employee_id text node value of 100 in the XML document tree. To display the XML
a
data before and after the update, use a query such as:
n
te r
SELECT xmldoc FROM xmldocuments WHERE id = 1;
The result after the update, for the example in the slide, is:
XMLDOC
I n
-------------------------------------------

l e
<?xml version="1.0"?>

c
<employees>

r a <employee>
<employee_id>100</employee_id>
O <first_name>Steve</first_name>
<last_name>Kingsley</last_name>
</employee>
...
</employees>
Oracle 10g: XML Fundamentals 13-10
Piecewise Update of XML

Example: Update an employee element node in the


XML tree stored in the XMLType column.
UPDATE xmldocuments
SET xmldoc = updateXML(
xmldoc,
'/employees/employee[2]',
XMLType('<employee>
<employee_id>102</employee_id>
<first_name>Lex</first_name>
<last_name>De Haan</last_name>
<salary>17000</salary>
</employee>'))
WHERE id = 1;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Piecewise Update of XML
U s
A I
In the example, the updateXML() function replaces the entire node tree associated with
the second <employee> element. The target <employee> element is identified by the

O
XPath expression '/employees/employee[2]'. The replacement value is a new

l &
<employee> node tree supplied as an XMLType instance in the third argument of the
updateXML() function. The XML data (in bold) before the update is:
XMLDOC
n a
te r
--------------------------------------
<?xml version="1.0"?>
<employees>

I n
<employee>

c l e
<employee_id>100</employee_id>
<first_name>Steve</first_name>

a
<last_name>Kingsley</last_name>

O r </employee>
<employee>
<employee_id>101</employee_id>
<first_name>Neena</first_name>
<last_name>Kingsley</last_name>
</employee>
</employees>
Oracle 10g: XML Fundamentals 13-11
Piecewise Update of XML (continued)
The changes to the XML document tree after the update is performed is shown here in bold:
XMLDOC
--------------------------------------
<?xml version="1.0"?>
<employees>
<employee>
<employee_id>100</employee_id>
<first_name>Steve</first_name>
<last_name>Kingsley</last_name>
</employee>
<employee>
<employee_id>102</employee_id>
<first_name>Lex</first_name>
<last_name>De Haan</last_name>
<salary>17000</salary>
</employee>
</employees>
Note: The updateXML() function cannot be used to add or delete an element or an
attribute. However, to give the appearance of adding or removing an element or attribute,
you can update the containing element with a new value.
In the preceding example, the second <employee> element, before the update was

l y
performed, did not contain a <salary> element. After the update was performed, the new

n
<employee> element tree contains a <salary> element. To insert additional employee

must be updated with an entire new set of <employee> elements.


e O
elements, the <employees> element, which contains all the <employee> elements,

U s
A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 13-12
Deleting Rows Based on XML Contents

Use the existsNode() function in the WHERE clause:


DELETE FROM xmldocuments
WHERE existsNode(xmldoc,
'//employee[last_name="Kingsley"]') = 1;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Deleting Rows Based on XML Contents
U s
A I
Data rows can be deleted from tables by using standard conditions in the WHERE clause.
However, if the condition to delete a row is based on the content held in an XMLType

O
instance in the table, then it is more common to use the existsNode() function is in the
WHERE clause of the SQL DELETE statement.

l &
The example in the slide uses an XPath expression in the existsNode() function to

n a
delete rows, whose XML documents contain an <employee> element with a
r
<last_name> child element, whose text node has the value Kingsley.

te
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 13-13
Indexing XML Data

Improve the performance of search operations on the


XML data stored in the database by using:
• Regular indexes
• Function-based indexes for XMLType functions
that are used in the WHERE clause, such as:
– The existsNode() function
– The extract() function
• Oracle Text indexes
– Section group indexes
– CTXXPATH index

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Indexing XML Data
U s
A I
You can create regular, function-based, and Oracle Text indexes on XML data. If the data is
stored in a CLOB data type, then Oracle Text indexes are the best choice. When the data is

O
stored in the object-relational format, any of the indexes can be used.

following query:
l &
For example, build a function-based index on the existsNode() function to speed up the

SELECT *
n a
FROM xmldocuments

te r
WHERE existsNode(xmldoc,

I n '//employee[last_name="Kingsley"]') = 1;

c l e
The Oracle Text indexes support XPath expressions in Oracle Database10g, allowing full-
text search capabilities to be integrated with XML.

r a
O
Oracle 10g: XML Fundamentals 13-14
Function-Based Indexes

• B*tree index on the existsNode() function:


CREATE INDEX last_name_xmlidx
ON xmldocuments (existsNode(xmldoc,
'//employee[last_name="Kingley"]'));

• Useful in the following query:


SELECT *
FROM xmldocuments
WHERE existsNode(xmldoc,
'//employee[last_name="Kingsley"]') = 1;

• A BITMAP index on the existsNode() function:


CREATE BITMAP INDEX last_name_exists_xmlidx
ON xmldocuments (xmldoc.existsNode('//last_name'));

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Function-Based Indexes
U s
A I
The first example in the slide shows how to create a B*tree (regular) function-based index
on the existsNode() function, when searching for an employee with the

O
<last_name> element containing the text node value King. The query in the slide shows
an example of where the function-based index is used. The BITMAP function-based index in

l &
the last example in the slide is useful for queries such as:
SELECT * FROM xmldocuments e

n a
te r
WHERE existsNode(xmldoc, '//last_name') = 1;
You can create indexes on the extract() function as well, for example:

I n
CREATE INDEX last_name_text_xmlidx ON xmldocuments
(xmldoc.extract(

c l e
'//employee[1]/last_name/text()').getStringVal());
The function-based index with the extract() function is useful in the following query:

r a SELECT * FROM xmldocuments e WHERE e.xmldoc.extract(

O '//employee[1]/last_name/text()').getStringVal()
= 'Kingsley';
Note: Appending the getStringVal() function is required when using the
extract() function to create a function-based index, and when the function is used in the
WHERE clause of the query.
Oracle 10g: XML Fundamentals 13-15
Using a CTXXPATH Index

The CTXXPATH index (provided with Oracle Text):


• Improves performance of XPath searches used in
the existsNode() function
• Serves as a primary filter for existsNode()
• Syntax:
CREATE INDEX [schema.]index
ON [schema.]table(XMLType-column)
INDEXTYPE IS ctxsys.CTXXPATH;

• Example:
CREATE INDEX xmldoc_ctxxpath_idx
ON xmldocuments (xmldoc)
INDEXTYPE IS ctxsys.CTXXPATH;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
CTXXPATH Index
U s
A I
The existsNode() function cannot use Oracle Text indexes to speed up its evaluation.
Therefore, using a CTXXPATH index type improves the performance of XPath searches used

O
in the existsNode() function, and serves as a primary filter mechanism for the
existsNode() function.

l &
The CTXXPATH index produces a superset of the results that will be produced by the

n a
existsNode() function. A query that will benefit from the creation of the CTXXPATH
index in the slide is:
SELECT id
te r
FROM
I n
xmldocuments x
WHERE x.xmldoc.existsNode('//employee_id') > 0;

c le
For more information about creating CTXXPATH indexes, refer to the Oracle Text Reference

a
10g Release 1 (10.1).
r
O
Oracle 10g: XML Fundamentals 13-16
Using a Context Index

• Syntax for a context index:


CREATE INDEX [schema.]index
ON [schema.]table (XMLType-column)
INDEXTYPE IS ctxsys.context;

• Example:
CREATE INDEX xmldoc_context_idx
ON xmldocuments (xmldoc)
INDEXTYPE IS ctxsys.context;

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Using a Context Index
U s
A I
The example in the slide creates a context index on the xmldoc column of the
xmldocuments table. The index in the slide can be used to speed up queries that use an
Oracle Text CONTAINS operator, for example:
O
SELECT *
FROM xmldocuments
l &
a
WHERE CONTAINS(xmldoc, 'Kingsley') > 0;

n
te r
Note: The CONTAINS operator is used in the WHERE clause of a SELECT statement to
specify the query expression for an Oracle Text query. The CONTAINS operator returns a

I n
relevance score for every row selected. For more information, refer to the Oracle Text
Reference 10g Release 1 (10.1).

c l e
r a
O
Oracle 10g: XML Fundamentals 13-17
Summary

In this lesson, you should have learned how to:


• Use SQL statements to transform XMLType data
stored in the database by using:
– The XMLTransform() function
– The XMLType.transform() function
• Perform updates on the contents of XMLType
instances by using the updateXML() function
• Delete rows based on the data stored in XMLType
instances by using the existsNode() function
• Create CTXXPATH and context indexes on the
XMLType columns

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
A I
In this lesson, you learned about some of the support functions for SQL operations on XML
available in Oracle Database 10g. You learned how to apply a stylesheet stored in an

O
XMLType column to transform an XML document stored in an XMLType column in the

l &
database. You also learned about performing DML in XML stored in columns within tables,
and how to create indexes on XMLType instances, and use XPath indexes.

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 13-18
Practice 13: Overview

This practice covers the following topics:


• Transforming XML by using stored stylesheets
• Using XPath functions

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Oracle 10g: XML Fundamentals 13-19
Practice 13
1. XML Transformation in Oracle Database 10g is done: (Choose the best answer.)
a. Only by using XDK
b. In the server and by using XDK
c. Only in the server

2. The XMLTransform() function: (Choose all that apply.)


a. Accepts XSL stylesheet and an XMLType instance as arguments
b. Applies an XSL stylesheet to the XMLType instance
c. Returns an XSL stylesheet
d. Returns an XMLType instance
e. Returns both XML and HTML as output

3. Which of the following are XPath functions? (Choose all that apply.)
a. existsNode()
b. under_path()
c. extract()
d. get_path()
e. extractValue()

4. Which of the following is true? (Choose all that apply.)


a. You can update only the entire XML document.
b. You can do piecewise updates. n l y
c. The updateXML() function can be used for updating XML.
e O
d. Using the updateXML() function, you can update an attribute value, text nodes,
and node or node tree.
U s
A I
Run the script E:\labs\lab\lab_13_05.sql to create the objects for the following
questions:
O
l &
5. Apply the stylesheet stored in stylesheet_tab to the XML PurchaseOrder

n a
with reference containing “King-20011127121040988PST”.

te r
Hint: Use existsNode() in the WHERE clause, and either use a subquery or a join
operation with the stylesheet_tab to obtain the stylesheet column.

I n
c l e
6. Update the XPath expression for '/PurchaseOrder/Reference' for
'King-20011127121560988PST' to

r a
'De Haan-200203311200000000PST'

O
Oracle 10g: XML Fundamentals 13-20
Accessing XML Through URIs

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Objectives

After completing this lesson, you should be able to do


the following:
• Describe the DBUri servlet
• Use the DBUri servlet to obtain the database data
as an XML document
• Use the DBUri servlet to transform the XML data
into another document by using an XSL stylesheet

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Objectives
U s
A I
In this lesson, you learn to use the DBUri servlet to retrieve information in the form of XML
from relational tables within the database. You also learn to transform data retrieved in the

O
XML format by using an XSL stylesheet stored in the Oracle XML DB repository.

l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 14-2
Definitions

• A Uniform Resource Locator (URL) refers to a


complete document or a particular location within
a document.
• A Uniform Resource Identifier (URI) is a more
general form of URL. It can:
– Be identical to a URL
– Use extra notation in the place of the anchor to
identify an enclosed section of a document

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Definitions
U s
often need to refer to data on a network by using URLs or URIs.
A I
In developing Internet applications, and particularly Internet-based XML applications, you

O
A URI, or Uniform Resource Identifier, is a generalized kind of URL. Like a URL, it can

l &
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

n
document. A URI consists of two parts: a
te r
• URL, which identifies the document by using the same notation as a regular URL
• Fragment, which identifies a fragment within the document. The notation for the

I n
fragment depends on the document type. For HTML documents, it has the

c l e
#anchor_name form. For XML documents, it uses the XPath notation.

r a
O
Oracle 10g: XML Fundamentals 14-3
URI Support in Oracle Database

Oracle provides support for URIs with:


• The DBUri servlet that:
– Allows access to data by using HTTP requests with
XPath-like expressions
– Returns responses as plain text, HTML, or XML
• The UriType supertype to store URI references by
using subtypes, such as:
– The DBUriType for accessing data in the database
– The HttpUriType for accessing external data
– The XDBUriType for accessing Oracle XML DB
repository resources
• The UriFactory PL/SQL package

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
URI Support in Oracle Database
U s
A I
Oracle Database10g includes a DBUri servlet that makes table data available through HTTP
requests. The response data can be returned as plain text, HTML, or XML. Any Web-

O
enabled client or application can use the data without SQL programming or any specialized
database API. The XML data can be obtained through links in a Web page, or by making a

l &
request through the HTTP-aware APIs of Java, PL/SQL, or PERL.

a
The DBUri servlet supports the generation of XML and non-XML content, and can
n
package.
te r
transform the XML content by using XSLT stylesheets, aided by the UriFactory

I n
Creating Columns and Storing Data by Using UriType

c l e
Database columns can be assigned the UriType object type, or any of its child types:
• The DBUriType for storing references to relational data inside the database

r a
• The HttpUriType for storing URLs to access Web pages or files external to the
database. These URLs can be accessed by using HTTP.
O
• The XDBUriType to store references to resources in the Oracle XML DB repository
Note: A UriType object column stores the URI or URL path as text. It is best to define the
column data type as a UriType, which allows you to store various subtypes within the same
column. The UriFactory PL/SQL package provides a programmatic interface for
creating UriType objects.
Oracle 10g: XML Fundamentals 14-4
The DBUri Servlet

The DBUri servlet:


• Makes database data accessible from your
browser or any Web client
• Is accessed by using:
– HTTP request on port 8080 and /oradb as base
URI, which are set in the xdbconfig.xml file
– A required XPath-like expression
http://host:8080/oradb/xpath
• Requires you to log in as a valid database user
• Can specify a MIME type of the response by using
the contenttype parameter:
http://host:8080/oradb/xpath?contenttype=mime-type

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
The DBUri Servlet
U s
A I
The DBUri servlet is built into the database, and the installation is handled by the Oracle
XML DB configuration file called xdbconfig.xml, which can be located by using the

O
Oracle XML DB user, through WebDAV, FTP, Oracle Enterprise Manager, or in the

l &
database. The DBUri servlet is used to access information in the database by using an
HTTP request formed by using the following base URL:
http://host:8080/oradb
n a
te r
The port 8080 is the default port used to access the DBUri serlvet. The base URI must start
with /oradb and must be followed by an XPath-like expression. The xdbconfig.xml

I n
configuration file can be modified to customize the base URI path and the HTTP port used.

c l e
Note: The first time you make a request to the DBUri servlet URI, you are prompted by the
browser for a valid database username and password. The data access operations are

r a
performed in the context of the schema for the username used in the login process.

O
The output document generated by the DBUri servlet can be a Web page, an XML
document, plain text, or other formats. By default, the response from the DBUri servlet is
produced with the text/xml MIME type. However, if the URI ends with a text()
function, then the text/plain MIME type is used. You can override the MIME type
format by using the contenttype HTTP parameter in the URI to the servlet.
Oracle 10g: XML Fundamentals 14-5
Retrieving Table Data as an XML
Document

• The HTTP request syntax is:


http://host:8080/oradb/<schema>/<table>
• Use an XPath expression with a case-sensitive
schema name, such as HR, followed by the table
name (as stored in the data dictionary):
http://host:8080/oradb/HR/REGIONS
• The result is:

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Identifying a Table as XML Document
U s
Use the following HTTP request syntax:
http://host:8080/oradb/schema/table
A I
O
An XML document is returned, which retrieves all the rows from the specified table. The

l &
response shows the root element as the name of the table, and the column values are
enclosed in a <ROW> element. The schema, table name, and column names are case-

n a
sensitive and must be specified by using the case in which they are stored in the Oracle data

te r
dictionary; by default, they are in uppercase. In the example in the slide, HR is the schema
name and REGIONS is the name of the table, and oradb is the virtual path for the servlet.

I
Optional URI Argumentsn
l e
To change the default root element tag name, use the rowsettag: parameter, for example:

c
http://host:8080/oradb/HR/REGIONS?rowsettag=places

r a
You can use the transform parameter, whose value is a URL, to UriFactory object,

O
which retrieves an XSL stylesheet at that location. The stylesheet is used to transform the
XML data being returned by the servlet. The contenttype parameter can be used to
specify the MIME type for the result of the transformation, as discussed in the preceding
section titled “The DBUri Servlet.”

Oracle 10g: XML Fundamentals 14-6


Retrieving a Single Row as XML

Use an XPath predicate to select the specific row:


.../oradb/HR/EMPLOYEES/ROW[EMPLOYEE_ID="121"]

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Retrieving a Single Row as XML
U s
A I
To select a particular ROW element in the table, use an XPath predicate to select a row by
using a condition that ensures that one row is returned. The syntax is:

O
http://host:8080/oradb/schema/table/ROW[predicate_expression]

l &
The result is an XML document that contains the single ROW element with its columns as
child elements. In the slide, the row for the employee with the ID 121 is retrieved.

n a
Note: You can add the rowsettag parameter to change the name of the root element.

te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 14-7
Retrieving Multiple Rows as XML

• Use the rowsettag parameter to create a root for


multiple rows returned for an XPath predicate:
.../ROW[DEPARTMENT_ID="20"]?rowsettag=EMPLOYEES

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Retrieving Multiple Rows as XML
U s
A I
If the XPath expression contains a predicate that targets multiple rows in the table, you must
provide the rowsettag parameter to create a root element that contains the row data being

O
returned. The root element is required to ensure that the response is well-formed.

l &
The example in the slide uses the XPath expression:
/HR/EMPLOYEES/ROW[DEPARTMENT_ID="20"]?rowsettag=EMPLOYEES after

n a
the HTTP prefix of http://host:8080/oradb to return the two rows for employees in
department 20.

te r
Note: If the rowsettag parameter is not specified, then the following XML response is
returned:
I n
l e
<ERROR>ORA-19003: Missing XML root element name</ERROR>

c
r a
O
Oracle 10g: XML Fundamentals 14-8
Retrieving Column Data

• Specify a child element representing the column.


• Use rowsettag if a column from multiple rows are
returned:
http://machine.oracle.com:8080/oradb/HR/
EMPLOYEES/ROW[EMPLOYEE_ID= "121"]/LAST_NAME
• The column is returned as an XML element, with
the text/xml MIME type:

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Retrieving Column Data
U s
The URI syntax needed to retrieve a single column in a table is:
http://host:8080/oradb/schema/table/ROW[predicate]/column
A I
O
In this case, a target column is identified and retrieved as XML. The example in the slide

multiple rows, for example:


l &
retrieves a single column from the employee 121. If you entered a predicate that retrieves

a
http://host:8080/oradb/HR/EMPLOYEES

n
te r
/ROW[DEPARTMENT_ID=60]/LAST_NAME?rowsettag=NAMES
Then, rowsettag parameter is required. The results returned are:
<NAMES>
I n
<LAST_NAME>Hunold</LAST_NAME>

c l e
<LAST_NAME>Ernst</LAST_NAME>
<LAST_NAME>Austin</LAST_NAME>

r a <LAST_NAME>Pataballa</LAST_NAME>
<LAST_NAME>Lorentz</LAST_NAME>

O </NAMES>
Note: You cannot traverse into a nested table or VARRAY columns. However, to retrieve an
attribute of an object type column, use the syntax:
http://host:8080/oradb/schema/table/ROW[predicate]/column/attrib

Oracle 10g: XML Fundamentals 14-9


Retrieving the Column Text

• Use the XPath text() function in the expression:


http://host:8080/oradb/HR/EMPLOYEES
/ROW[EMPLOYEE_ID="121"]/LAST_NAME/text()

• The data is returned as plain text, with the


text/plain MIME type:

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Retrieving the Column Text
U s
A I
In many cases, it can be useful to retrieve only the text values of a column and not the
enclosing tags. For example, if XSL stylesheets are stored in a CLOB column, you can

O
retrieve the document text without having any enclosing column name tags. You can use the

following syntax:
l &
text() function for this. It specifies that you want only the text value of the node. Use the

a
http://host:8080/oradb/schema/table/ROW[predicate]/column/text()
n
te r
The example in the slide retrieves the text value of the last name for employee 121, without
the XML element structure, that is, the start and end tags. This data is returned as a text

I n
document, not an XML document, with the value Fripp.

c l e
r a
O
Oracle 10g: XML Fundamentals 14-10
Using Multiple Predicates

The XPath expression can:


• Contain multiple predicates
• Use Boolean operators: and, or, and not
• Use relational operators: >, >=, <, <=, =, and !=
.../oradb/HR/EMPLOYEES/ROW[EMPLOYEE_ID="120" and
DEPARTMENT_ID="50"]/LAST_NAME

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Retrieving with Multiple Predicates
U s
A I
The example in the slide requests the data for the last name of an employee with the ID 120
in department 50. The result displays the <last_name> element for the employee Weiss.

O
The XPath expression added after the http://host:8080/oradb prefix can use the
following syntax:

l &
/<schema>/<table>/ROW[predicate1 and predicate2]/<column>

a
Predicates can be defined at any element other than the schema and table elements. Object
n
te r
columns allow searches on the attribute values as well. The predicate expressions can use
the following XPath expressions:

I n
• Boolean operators (in lowercase): and, or, and not
• Relational operators: <, >, <=, !=, >=, =, mod, div, * (multiply)

l e
Note: XPath expressions only support the child axes, unless the target is with an XMLType
c
r a
of XMLType tables. The wild card (*), descendant (//), and other operations are not valid.
The text() XPath function is the only one supported on a scalar node, and cannot be used
O
at the row or table elements.

Oracle 10g: XML Fundamentals 14-11


Applying a Stylesheet

To transform XML data returned from a URI request:


1. Store an XSL stylesheet in the XML DB repository.
a. Map a Web folder to the XML DB repository.
http://host:8080/public
b. Drag the XSL document to the target location in the
XML DB repository.
2. Use the transform and contenttype parameters
with the HTTP request.
http://host:8080/oradb/HR/EMPLOYEES
?rowsettag=ROWSET&transform=/public/emprows.xsl
&contenttype=text/html
Optionally, use the rowsettag parameter to set
the root element name required by the stylesheet.
n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Applying a Stylesheet
U s
A I
To transform the data being retrieved from a request to the DBUri servlet, use the
transform parameter in the URI request to select the XSL stylesheet to be used. The slide

O
shows the steps and syntax required to enable a stylesheet to be applied to the data returned
by a DBUri servlet request:

l &
1. First, create the XSL stylesheet document and store it in the Oracle XML DB
a
repository. To store any document in the Oracle XML DB repository, you copy the
n
te r
XSL document to a folder in the repository by:
a. Creating a Web folder mapped to a location in the Oracle XML DB repository by

I n
using Windows Explorer with the Server Message Block (SMB) protocol
b. Dragging the document and dropping it into the target folder. The slide example

l e
uses the /public folder provided in the Oracle XML DB repository.

c
Note: The XSL file can be copied to to the Oracle XML DB repository by using

r aFTP or a WebDAV-enabled tool.


2. Issue an HTTP request for the data by using the DBUri servlet, as previously
O discussed, but add the transform parameter set to the full Oracle XML DB
repository path to the XSL document, for example, /public/emprows.xsl. You
must also specify the contenttype (for example, with the value text/html) for
transforming the data into an HTML document.
Oracle 10g: XML Fundamentals 14-12
Results After Applying a Stylesheet

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Results After Applying a Stylesheet
U s
A I
The slide shows the transformation of the employee XML content into HTML by using the
following empows.xsl stylesheet, which is stored in the /public directory of the XML
DB repository:
O
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
l &
a
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

n
te r
<xsl:template match="/">
<HTML><BODY><H1>Employees</H1><TABLE BORDER="1">
<TR><TH>Department</TH><TH>Employee</TH>

I n
<TH>Job Id</TH><TH>Salary</TH> </TR>

c l e
<xsl:for-each select="/ROWSET/ROW">
<TR><TD><xsl:value-of select="DEPARTMENT_ID"/></TD>

r a <TD><xsl:value-of select="LAST_NAME"/></TD>
<TD><xsl:value-of select="JOB_ID"/></TD>

O <TD><xsl:value-of select="SALARY"/></TD></TR>
</xsl:for-each>
</TABLE></BODY></HTML>
</xsl:template>
</xsl:stylesheet>
Oracle 10g: XML Fundamentals 14-13
Summary

In this lesson, you should have learned how to:


• Describe URI data type support in the Oracle
database
• Use the DBUri servlet to access database data and
present it as an XML document
• Transform the XML data, retrieved by the DBUri
servlet, by using an XSL stylesheet

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
Summary
U s
in Oracle Database10g. You discovered how to:
A I
In this lesson, you learned about the DBUri servlet and support for the UriType data types

O
• Use the DBUri Servlet to obtain the database data as an XML document

XSL stylesheet
l &
• Use the DBUri Servlet to transform the XML data into another document by using an

n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 14-14
Practice 14: Overview

This practice covers retrieving the database data by


using DBUri servlet.

n l y
Copyright © 2004, Oracle. All rights reserved.

e O
U s
A I
O
l &
n a
te r
I n
c le
ra
O
Oracle 10g: XML Fundamentals 14-15
Practice 14
The goal of the practice is to use the DBUri servlet.
1. Using the machine name and port provided by the instructor, retrieve the
DEPARTMENTS table by using the DBUri servlet with Internet Explorer.
Note: When prompted with a login dialog box, enter your assigned username oraX
and password oracle.
2. Modify the above question to retrieve the table in the text format. When prompted,
specify that you want to open the result by using WordPad.
3. Using the DBUri servlet, retrieve the department name department with
DEPARTMENT_ID value 50 in the XML format.
4. Modify the previous question to retrieve the department name in the text format.
5. Using DBUri servlet, retrieve the row for employee last names with the
DEPARTMENT_ID value 60 in the XML format. Use the rowsettag parameter with
the value ROWSET.
6. Using the DBUri servlet, retrieve the EMPLOYEES table and apply the stylesheet in
E:\labs\lab\lab_14_06.xsl to the output.
a. Using Windows Explorer, open the OracleXDB Web Folder that you created in
Practice 9. Navigate to the /home/ORAx folder that you created, where x is
your student number.
Note: If you previously closed the Explorer window, you will be prompted to log
in by using your database username and password.

b. Drag lab_14_06.xsl and drop the file into your /home/ORAx folder.
n y
Hint: Expand My Network Places in Explorer to locate the OracleXDB folder.
l
c. Make a DBUri servlet request to display the EMPLOYEES table data as HTML
O
by using the XSL stylesheet you copied to the /home/ORAx folder.
e
parameters.
U s
Hint: You will need to use the transform, contenttype, and rowsettag

A I
O
l &
n a
te r
I n
c l e
r a
O
Oracle 10g: XML Fundamentals 14-16

Вам также может понравиться