Skip Headers

Oracle® XML DB Developer's Guide
10g Release 1 (10.1)

Part Number B10790-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Master Index
Master Index
Go to Feedback page
Feedback

Go to previous page
Previous
Go to next page
Next
View PDF

10 PL/SQL API for XMLType

This chapter describes the use of the APIs for XMLType in PL/SQL.

This chapter contains these topics:

Introducing PL/SQL APIs for XMLType

This chapter describes the PL/SQL Application Program Interfaces (APIs) for XMLType. These include the following:

PL/SQL APIs For XMLType Features

The PL/SQL APIs for XMLTypeallow you to perform the following tasks:

Lazy XML Loading (Lazy Manifestation)

Because XMLType provides an in-memory or virtual Document Object Model (DOM), it can use a memory conserving process called lazy XML loading, also sometimes referred to as lazy manifestation. This process optimizes memory usage by only loading rows of data when they are requested. It throws away previously-referenced sections of the document if memory usage grows too large. Lazy XML loading supports highly scalable applications that have many concurrent users needing to access large XML documents.

XMLType Datatype Now Supports XML Schema

The XMLType datatype has been enhanced in this release to include support for XML schemas. You can create an XML schema and annotate it with XML to object- relational mappings. To take advantage of the PL/SQL DOM API, first create an XML schema and register it. Then when you create XMLType tables and columns, you can specify that these conform to the XML schema you defined and registered with Oracle XML DB.

XMLType Supports Data in Different Character Sets.

XMLType instances can now be created from data encoded in any Oracle-supported character sets by using the PL/SQL XMLType constructor or the createXML() methods. The source XML data must be supplied using either BFILE or BLOB datatype. The encoding of the data is specified through the csid argument. When this argument is zero then the encoding of the source data is determined from the XML prolog as specified in Appendix F of the XML 1.0 Reference.

In addition, a new getBlobVal() method is provided to retrieve the XML contents in the requested character set.

With PL/SQL APIs for XMLType You Can Modify and Store XML Elements

While typical XML parsers give read access to XML data in a standard way, they do not provide a way to modify and store individual XML elements.


What are Elements?

An element is the basic logical unit of an XML document and acts as a container for other elements such as children, data, attributes, and their values. Elements are identified by start-tags, as in <name>, and end-tags, as in </name>, or in the case of empty elements, <name/>.


What is a DOM Parser?

An embedded DOM parser accepts an XML-formatted document and constructs an in-memory DOM tree based on the document structure. It then checks whether or not the document is well-formed and optionally whether it complies with a specific Document Type Definition (DTD). A DTD is a set of rules that define the allowable structure of an XML document. DTDs are text files that derive their format from SGML and can either be included in an XML document by using the DOCTYPE element or by using an external file through a DOCTYPE reference. A DOM parser also provides methods for traversing the DOM tree and return data from it.

If you use the PL/SQL DOM API, then you can use the NamedNodeMap methods to retrieve elements from an XML file.


Server-Side Support

PL/SQL APIs for XMLType support processing on the server side only. Support for client-side processing is not provided in this release.

PL/SQL DOM API for XMLType (DBMS_XMLDOM)

This section describes PL/SQL DOM API for XMLType. This is the DBMS_XMLDOM PL/SQL API.

Introducing W3C Document Object Model (DOM) Recommendation

Skip this section if you are already familiar with the generic DOM specifications recommended by the World Wide Web Consortium (W3C).

The Document Object Model (DOM) recommended by the W3C is a universal API to the structure of XML documents. It was originally developed to formalize Dynamic HTML, which allows animation, interaction and dynamic updating of Web pages. DOM provides a language and platform-neutral object model for Web pages and XML document structures in general. The DOM describes language and platform-independent interfaces to access and to operate on XML components and elements. It expresses the structure of an XML document in a universal, content-neutral way. Applications can be written to dynamically delete, add, and edit the content, attributes, and style of XML documents. Additionally, the DOM makes it possible to write applications that work properly on all browsers and servers and on all platforms.

A brief summary of the state of the DOM Recommendations is provided in this section for your convenience.

W3C DOM Extensions Not Supported in This Release

The only extensions to the W3C DOM API not supported in this release are those relating to client-side file system input and output, and character set conversions. This type of procedural processing is available through the SAX interface.

Supported W3C DOM Recommendations

All Oracle XML DB APIs for accessing and manipulating XML comply with standard XML processing requirements as approved by the W3C. PL/SQL DOM supports Levels 1 and 2 from the W3C DOM specifications.

  • In Oracle9i release 1 (9.0.1), the XDK for PL/SQL implemented DOM Level 1.0 and parts of DOM Level 2.0.

  • In Oracle9i release 2 (9.2) and Oracle Database 10g release 1 (10.1), the PL/SQL API for XMLType implements DOM Levels 1.0 and Level 2.0 Core, and is fully integrated in the database through extensions to the XMLType API.

The following briefly describe each level:

  • DOM Level 1.0. The first formal Level of the DOM specifications, completed in October 1998. Level 1.0 defines support for XML 1.0 and HTML.

  • DOM Level 2.0. Completed in November 2000, Level 2.0 extends Level 1.0 with support for XML 1.0 with namespaces and adds support for Cascading Style Sheets (CSS) and events (user-interface events and tree manipulation events), and enhances tree manipulations (tree ranges and traversal mechanisms). CSS are a simple mechanism for adding style (fonts, colors, spacing, and so on) to Web documents.

  • DOM Level 3.0. Currently under development, Level 3.0 will extend Level 2.0 by finishing support for XML 1.0 with namespaces (alignment with the XML Infoset and support for XML Base) and will extend the user interface events (keyboard). It will also add support for abstract schemas (for DTDs and XML schema), and the ability to load and save a document or an abstract schema. It is exploring further mixed markup vocabularies and the implications on the DOM API (Embedded DOM), and it will support XPath.

Difference Between DOM and SAX

The generic APIs for XML can be classified in two main categories:

  • Tree-based. The DOM is the primary generic tree-based API for XML.

  • Event-based. SAX (Simple API for XML) is the primary generic event-based programming interface between an XML parser and an XML application.

The DOM works by creating objects. These objects have child objects and properties, and the child objects have child objects and properties, and so on. Objects are referenced either by moving down the object hierarchy or by explicitly giving an HTML element an ID attribute. For example:

<img src="employee_jdoe.gif" ID="0123jdoe">

Examples of structural manipulations are:

  • Reordering elements

  • Adding or deleting elements

  • Adding or deleting attributes

  • Renaming elements

PL/SQL DOM API for XMLType (DBMS_XMLDOM): Features

The default action for the PL/SQL DOM API for XMLType (DBMS_XMLDOM) is as follows:

  • Produces a parse tree that can be accessed by DOM APIs.

  • The parser is validating if a DTD is found; otherwise, it is non-validating.

  • An application error is raised if parsing fails.

  • The types and methods described in this document are made available by the PL/SQL package DBMS_XMLPARSER.

DTD validation follows the same rules that are exposed for the XML Parser available through the XDK in Oracle9i release 1(9.0.1). The only difference is that the validation occurs when the object document is manifested. For example, if lazy manifestation is used, then the document will be validated when it is used.

Oracle XML DB extends the Oracle XML development platform beyond SQL support for XML text and storage and retrieval of XML data. In this release, you can operate on XMLType instances using the DOM in PL/SQL and Java. Thus, you can directly manipulate individual XML elements and data using the language best suited for your application or plug-in.

This release has updated the PL/SQL DOM API to exploit a C-based representation of XML in the server and to operate on XML schema-based XML instances. Oracle XML DB PL/SQL DOM API for XMLType and Java DOM API for XMLType comply with the W3C DOM Recommendations to define and implement structured storage of XML in relational or object-relational columns and as in-memory instances of XMLType. See "Using PL/SQL DOM API for XMLType: Preparing XML Data", for a description of W3C DOM Recommendations.


XML Schema Support

PL/SQL DOM API for XMLType introduces XML schema support. Oracle XML DB uses annotations within an XML schema as metadata to determine both an XML document structure and its mapping to a database schema.


Note:

For backward compatibility and for flexibility, the PL/SQL DOM supports both XML schema-based documents and non- schema-based documents.

When an XML schema is registered with Oracle XML DB, the PL/SQL DOM API for XMLType builds an in-memory tree representation of the XML document as a hierarchy of node objects, each with its own specialized interfaces. Most node object types can have child node types, which in turn implement additional, more specialized interfaces. Some node types can have child nodes of various types, while some node types can only be leaf nodes and cannot have children nodes under them in the document structure.

Enhanced Performance

Additionally, Oracle XML DB uses the DOM to provide a standard way to translate data from multiple back-end data sources into XML and vice versa. This eliminates the requirement to use separate XML translation techniques for the different data sources in your environment. Applications needing to exchange XML data can use one native XML database to cache XML documents. Thus, Oracle XML DB can speed up application performance by acting as an intermediate cache between your Web applications and your back-end data sources, whether in relational databases or in disparate file systems.

Designing End-to-End Applications Using XDK and Oracle XML DB

When you build applications based on Oracle XML DB, you do not need the additional components in the XDKs. However, you can mix and match XDK components with Oracle XML DB to deploy a full suite of XML-enabled applications that run end-to-end. For example, you can use features in XDK for:

  • Simple API for XML (SAX) interface processing. SAX is an XML standard interface provided by XML parsers and used by procedural and event-based applications.

  • DOM interface processing for structural and recursive object-based processing.

Oracle XDKs contain the basic building blocks for creating applications that run on the client, in a browser or plug-in, for example, for reading, manipulating, transforming and viewing XML documents. To provide a broad variety of deployment options, Oracle XDKs are also available for Java, Java beans, C, C++, and PL/SQL. Unlike many shareware and trial XML components, Oracle XDKs are fully supported and come with a commercial redistribution license.

Oracle XDK for Java consists of these components:

  • XML Parsers: Supports Java, C, C++ and PL/SQL, the components create and parse XML using industry standard DOM and SAX interfaces.

  • XSLT Processor: Transforms or renders XML into other text-based formats such as HTML.

  • XML Schema Processor: Supports Java, C, and C++, allows use of XML simple and complex datatypes.

  • XML Class Generator: Automatically generates Java and C++ classes from DTDs and Schemas to send XML data from Web forms or applications. Class generators accept an input file and creates a set of output classes that have corresponding functionality. In the case of the XML Class Generator, the input file is a DTD and the output is a series of classes that can be used to create XML documents conforming with the DTD.

  • XML Transviewer Java Beans: Displays and transforms XML documents and data using Java components.

  • XML SQL Utility: Supports Java, generates XML documents, DTDs and Schemas from SQL queries.

  • TransXUtility. Loads data encapsulated in XML into the database with additional functionality useful for installations.

  • XSQL Servlet: Combines XML, SQL, and XSLT in the server to deliver dynamic web content.

Using PL/SQL DOM API for XMLType: Preparing XML Data

To take advantage of the Oracle XML DB DOM APIs, you must follow a few processes to allow Oracle XML DB to develop a data model from your XML data. This is true for any language, although PL/SQL is the focus of this chapter. The process you use depends on the state of your data and your application requirements.

To prepare data for using PL/SQL DOM APIs in Oracle XML DB, you must:

  1. Create a standard XML schema if you do not already use one. Annotate the XML schema with definitions for the SQL objects defined in your relational or object-relational database.

  2. Register your XML schema to generate the necessary database mappings.

You can then:

  • Use XMLType views to wrap existing relational or object-relational data in XML formats. This enables an XML structure to be created that can be accessed by your application. See also "Wrapping Existing Data into XML with XMLType Views" .

  • Insert XML documents (and fragments) into XMLType columns.

  • Use Oracle XML DB DOM PL/SQL and Java APIs to access and manipulate XML data stored in XMLType columns and tables.

Creating and registering a standard XML schema allows your compliant XML documents to be inserted into the database where they can be decomposed, parsed, and stored in object-relational columns that can be accessed by your application.

Generating an XML Schema Mapping to SQL Object Types

An XML schema must be registered before it can be used or referenced in any context. When you register an XML schema, elements and attributes declared within it get mapped to separate attributes within the corresponding SQL object types within the database schema.

After the registration process is completed, XML documents conforming to this XML schema, and referencing it with its URL within the document, can be handled by Oracle XML DB. Tables and columns for storing the conforming documents can be created for root XML elements defined by this schema.


See Also:

Chapter 5, " XML Schema Storage and Query: The Basics" for more information and examples

An XML schema is registered by using the DBMS_XMLSCHEMA package and by specifying the schema document and its URL (also known as schema location). The URL used here is a name that uniquely identifies the registered schema within the database and need not be the physical URL where the schema document is located.

Additionally, the target namespace of the schema is another URL (different from the schema location URL) that specifies an abstract namespace within which the elements and types get declared. An instance of an XML document should specify both the namespace of the root element and the location (URL) of the schema that defines this element.

When instances of documents are inserted into Oracle XML DB using path-based protocols like HTTP or FTP, the XML schema to which the document conforms is registered implicitly, if its name and location are specified and if it has not been previously registered.

DOM Fidelity for XML Schema Mapping

While elements and attributes declared within the XML schema get mapped to separate attributes within the corresponding SQL object type, some encoded information in an XML document is not represented directly. In order to guarantee that the returned XML document is identical to the original document for purposes of DOM traversals (referred to as DOM fidelity), a binary attribute called SYS_XDBPD$ is added to all generated SQL object types. This attribute stores all pieces of information that cannot be stored in any of the other attributes, thereby ensuring DOM fidelity for XML documents stored in Oracle XML DB.

Data handled by SYS_XDBPD$ that is not represented in the XML schema mapping include:

  • Comments

  • Namespace declaration

  • Prefix information


    Note:

    In this document, the SYS_XDBPD$ attribute has been omitted in many examples for simplicity. However, the attribute is always present in SQL object types generated by the schema-registration process.

Wrapping Existing Data into XML with XMLType Views

To make existing relational and object-relational data available to your XML applications, you create XMLType views, which provide a mechanism for wrapping the existing data into XML formats. This exposes elements and entities, that can then be accessed using the PL/SQL DOM APIs.

You register an XML schema containing annotations that represent the bi-directional mapping from XML to SQL object types. Oracle XML DB can then create an XMLType view conforming to this XML schema.

PL/SQL DOM API for XMLType (DBMS_XMLDOM) Methods

Table 10-1 lists the PL/SQL DOM API for XMLType (DBMS_XMLDOM) methods supported in this release. Character data (CDATA) refers to the section in an XML document used to indicate the text that should not be parsed. This allows for the inclusion of characters that would otherwise have special functions, such as &, <, , and so on. CDATA sections can be used in the content of an element or in attributes.

Non-Supported DBMS_XMLDOM Methods in This Release

The following DBMS_XMLDOM methods are not supported in this release:

  • hasFeature

  • getDocType

  • setDocType

  • writeExternalDTDToFile

  • writeExternalDTDToBuffer

  • writeExternalDTDToClob

Table 10-1 lists additional methods supported in this release.

Table 10-1 Summary of DBMS_XMLDOM Methods

Group/Method Description

Node methods

--
isNull()
Tests if the node is NULL.
makeAttr()
Casts the node to an Attribute.
makeCDataSection()
Casts the node to a CDataSection.
makeCharacterData()
Casts the node to CharacterData.
makeComment()
Casts the node to a Comment.
makeDocumentFragment()
Casts the node to a DocumentFragment.
makeDocumentType()
Casts the node to a Document Type.
makeElement()
Casts the node to an Element.
makeEntity()
Casts the node to an Entity.
makeEntityReference()
Casts the node to an EntityReference.
makeNotation()
Casts the node to a Notation.
makeProcessingInstruction()
Casts the node to a DOMProcessingInstruction.
makeText()
Casts the node to a DOMText.
makeDocument()
Casts the node to a DOMDocument.
writeToFile()
Writes the contents of the node to a file.
writeToBuffer()
Writes the contents of the node to a buffer.
writeToClob()
Writes the contents of the node to a clob.
getNodeName()
Retrieves the Name of the Node.
getNodeValue()
Retrieves the Value of the Node.
setNodeValue()
Sets the Value of the Node.
getNodeType()
Retrieves the Type of the node.
getParentNode()
Retrieves the parent of the node.
getChildNodes()
Retrieves the children of the node.
getFirstChild()
Retrieves the first child of the node.
getLastChild()
Retrieves the last child of the node.
getPreviousSibling()
Retrieves the previous sibling of the node.
getNextSibling()
Retrieves the next sibling of the node.
getAttributes()
Retrieves the attributes of the node.
getOwnerDocument()
Retrieves the owner document of the node.
insertBefore()
Inserts a child before the reference child.
replaceChild()
Replaces the old child with a new child.
removeChild()
Removes a specified child from a node.
appendChild()
Appends a new child to the node.
hasChildNodes()
Tests if the node has child nodes.
cloneNode()
Clones the node.

Named node map methods

--
isNull()
Tests if the NodeMap is NULL.
getNamedItem()
Retrieves the item specified by the name.
setNamedItem()
Sets the item in the map specified by the name.
removeNamedItem()
Removes the item specified by name.
item()
Retrieves the item given the index in the map.
getLength()
Retrieves the number of items in the map.

Node list methods

--
isNull()
Tests if the Nodelist is NULL.
item()
Retrieves the item given the index in the nodelist.
getLength()
Retrieves the number of items in the list.

Attr methods

--
isNull()
Tests if the Attribute Node is NULL.
makeNode()
Casts the Attribute to a node.
getQualifiedName()
Retrieves the Qualified Name of the attribute.
getNamespace()
Retrieves the NS URI of the attribute.
getLocalName()
Retrieves the local name of the attribute.
getExpandedName()
Retrieves the expanded name of the attribute.
getName()
Retrieves the name of the attribute.
getSpecifiied()
Tests if attribute was specified in the owning element.
getValue()
Retrieves the value of the attribute.
setValue()
Sets the value of the attribute.

CData section methods

--
isNull()isNull()
Tests if the CDataSection is NULL.
makeNode()makeNode()
Casts the CDatasection to a node.

Character data methods

--
isNull()
Tests if the CharacterData is NULL.
makeNode()
Casts the CharacterData to a node.
getData()
Retrieves the data of the node.
setData()
Sets the data to the node.
getLength()
Retrieves the length of the data.
substringData()
Retrieves the substring of the data.
appendData()
Appends the given data to the node data.
insertData()
Inserts the data in the node at the given offSets.
deleteData()
Deletes the data from the given offSets.
replaceData()
Replaces the data from the given offSets.

Comment methods

--
isNull()
Tests if the comment is NULL.
makeNode()
Casts the Comment to a node.

DOM implementation methods

--
isNull()
Tests if the DOMImplementation node is NULL.
hasFeature()
Tests if the DOM implements a given feature. [Not supported in this release]

Document fragment methods

--
isNull()
Tests if the DocumentFragment is NULL.
makeNode()
Casts the Document Fragment to a node.

Document type methods

--
isNull()
Tests if the Document Type is NULL.
makeNode()
Casts the document type to a node.
findEntity()
Finds the specified entity in the document type.
findNotation()
Finds the specified notation in the document type.
getPublicId()
Retrieves the public ID of the document type.
getSystemId()
Retrieves the system ID of the document type.
writeExternalDTDToFile()
Writes the Document Type Definition to a file.
writeExternalDTDToBuffer()
Writes the Document Type Definition to a buffer.
writeExternalDTDToClob()
Writes the Document Type Definition to a clob.
getName()
Retrieves the name of the Document type.
getEntities()
Retrieves the nodemap of entities in the Document type.
getNotations()
Retrieves the nodemap of the notations in the Document type.

Element methods

--
isNull()
Tests if the Element is NULL.
makeNode()
Casts the Element to a node.
getQualifiedName()
Retrieves the qualified name of the element.
getNamespace()
Retrieves the NS URI of the element.
getLocalName()
Retrieves the local name of the element.
getExpandedName()
Retrieves the expanded name of the element.
getChildrenByTagName()
Retrieves the children of the element by tag name.
getElementsByTagName()
Retrieves the elements in the subtree by element.
resolveNamespacePrefix()
Resolve the prefix to a namespace uri.
getTagName()
Retrieves the Tag name of the element.
getAttribute()
Retrieves the attribute node specified by the name.
setAttribute()
Sets the attribute specified by the name.
removeAttribute()
Removes the attribute specified by the name.
getAttributeNode()
Retrieves the attribute node specified by the name.
setAttributeNode()
Sets the attribute node in the element.
removeAttributeNode()
Removes the attribute node in the element.
normalize()
Normalizes the text children of the element.

Entity methods

--
isNull()
Tests if the Entity is NULL.
makeNode()
Casts the Entity to a node.
getPublicId()
Retrieves the public Id of the entity.
getSystemId()
Retrieves the system Id of the entity.
getNotationName()
Retrieves the notation name of the entity.

Entity reference methods

--
isNull()
Tests if the entity reference is NULL.
makeNode()
Casts the Entity reference to NULL.

Notation methods

--
isNull()
Tests if the notation is NULL.
makeNode()
Casts the notation to a node.
getPublicId()
Retrieves the public Id of the notation.
getSystemId()
Retrieves the system Id of the notation.

Processing instruction methods

--
isNull()
Tests if the processing instruction is NULL.
makeNode()
Casts the Processing instruction to a node.
getData()
Retrieves the data of the processing instruction.
getTarget()
Retrieves the target of the processing instruction.
setData()
Sets the data of the processing instruction.

Text methods

--
isNull()
Tests if the text is NULL.
makeNode()
Casts the text to a node.
splitText()
Splits the contents of the text node into 2 text nodes.

Document methods

--
isNull()
Tests if the document is NULL.
makeNode()
Casts the document to a node.
newDOMDocument()
Creates a new document.
freeDocument()
Frees the document.
getVersion()
Retrieves the version of the document.
setVersion()
Sets the version of the document.
getCharset()
Retrieves the Character set of the document.
setCharset()
Sets the Character set of the document.
getStandalone()
Retrieves if the document is specified as standalone.
setStandalone()
Sets the document standalone.
writeToFile()
Writes the document to a file.
writeToBuffer()
Writes the document to a buffer.
writeToClob()
Writes the document to a clob.
writeExternalDTDToFile()
Writes the DTD of the document to a file. [Not supported in this release]
writeExternalDTDToBuffer()
Writes the DTD of the document to a buffer. [Not supported in this release]
writeExternalDTDToClob()
Writes the DTD of the document to a clob. [Not supported in this release]
getDoctype()
Retrieves the DTD of the document.
getImplementation()
Retrieves the DOM implementation.
getDocumentElement()
Retrieves the root element of the document.
createElement()
Creates a new element.
createDocumentFragment()
Creates a new document fragment.
createTextNode()
Creates a Text node.
createComment()
Creates a comment node.
createCDATASection()
Creates a CDatasection node.
createProcessingInstruction()
Creates a processing instruction.
createAttribute()
Creates an attribute.
createEntityReference()
Creates an Entity reference.
getElementsByTagName()
Retrieves the elements in the by tag name.
adoptNode()
FUNCTION adoptNode(doc DOMdocument,
 adoptednode domnode)RETURN DOMNode;
Adopts the given node: removes it from its owner document and adds it to the given document.
createDocument()
FUNCTION createDocument (namspaceURI IN
 VARCHAR2, qualifiedName IN VARCHAR2, 
doctype IN DOMType) RETURN DocDocument;
getPrefix()
FUNCTION getPrefix(n DOMNode) RETURN
 VARCHAR2;
setPrefix()
PROCEDURE setPrefix (n DOMNode) RETURN
 VARCHAR2;
hasAttributes()
FUNCTION hasAttributes (n DOMNode) RETURN
 BOOLEAN;
getNamedItem()
FUNCTION getNamedItem (nnm DOMNamedNodeMap,
 name IN VARCHAR2, ns IN VARCHAR2) RETURN
 DOMNode;
setNamedItem()
FUNCTION getNamedItem (nnm DOMNamedNodeMap,
 arg IN DOMNode, ns IN VARCHAR2) RETURN
 DOMNode;
removeNamedItem()
FUNCTION removeNamedItem (nnm
 DOMNamesNodeMap, name in VARCHAR2, ns IN
 VARCHAR2) RETURN DOMNode;
getOwnerElement()
FUNCTION getOwnerElement (a DOMAttr) RETURN
 DOMElement;
getAttribute()
FUNCTION getAttribute (elem DOMElement, name
 IN VARCHAR2, ns IN VARCHAR2) RETURN
 VARCHAR2;
hasAttribute()
FUNCTION hasAttribute (elem DOMElement, name
 IN VARCHAR2)  RETURN BOOLEAN;
hasAttribute()
FUNCTION hasAttribute (elem DOMElement, name
 IN VARCHAR2, ns IN VARCHAR2)  RETURN
 BOOLEAN;
setAttribute()
PROCEDURE setAttribute (elem DOMElement, name
 IN VARCHAR2, newvalue IN VARCHAR2, ns IN
 VARCHAR2);
removeAttribute()
PROCEDURE removeAttribute (elem DOMElement,
 name IN VARCHAR2, ns IN VARCHAR2);
getAttributeNode()
FUNCTION getAttributeNode(elem DOMElement,
 name IN VARCHAR2, ns IN VARCHAR2) RETURN
 DOMAttr;
setAttributeNode()
FUNCTION setAttributeNode(elem DOMElement,
 newAttr IN DOMAttr, ns IN VARCHAR2) RETURN
 DOMAttr;
createElement()
FUNCTION createElement (doc DOMDocument,
 tagname IN VARCHAR2, ns IN VARCHAR2) RETURN
 DOMElement;
createAttribute()
FUNCTION createAttribute (doc DOMDocument,
 name IN VARCHAR2, ns IN VARCHAR2) RETURN
 DOMAttr;

PL/SQL DOM API for XMLType (DBMS_XMLDOM) Exceptions

The following lists the PL/SQL DOM API for XMLType (DBMS_XMLDOM) exceptions. For more information, see Oracle XML Developer's Kit Programmer's Guide.

The exceptions have not changed since the prior release:

  • INDEX_SIZE_ERR

  • DOMSTRING_SIZE_ERR

  • HIERARCHY_REQUEST_ERR

  • WRONG_DOCUMENT_ERR

  • INVALID_CHARACTER_ERR

  • NO_DATA_ALLOWED_ERR

  • NO_MODIFICATION_ALLOWED_ERR

  • NOT_FOUND_ERR

  • NOT_SUPPORTED_ERR

  • INUSE_ATTRIBUTE_ERR

PL/SQL DOM API for XMLType: Node Types

In the DOM specification, the term "document" is used to describe a container for many different kinds of information or data, which the DOM objectifies. The DOM specifies the way elements within an XML document container are used to create an object-based tree structure and to define and expose interfaces to manage and use the objects stored in XML documents. Additionally, the DOM supports storage of documents in diverse systems.

When a request such as getNodeType(myNode) is given, it returns myNodeType, which is the node type supported by the parent node. These constants represent the different types that a node can adopt:

  • ELEMENT_NODE

  • ATTRIBUTE_NODE

  • TEXT_NODE

  • CDATA_SECTION_NODE

  • ENTITY_REFERENCE_NODE

  • ENTITY_NODE

  • PROCESSING_INSTRUCTION_NODE

  • COMMENT_NODE

  • DOCUMENT_NODE

  • DOCUMENT_TYPE_NODE

  • DOCUMENT_FRAGMENT_NODE

  • NOTATION_NODE

Table 10-2 shows the node types for XML and HTML and the allowed corresponding children node types.

Table 10-2 XML and HTML DOM Node Types and Corresponding Children Node Types

Node Type Children Node Types
Document
Element (maximum of one), ProcessingInstruction, Comment, DocumentType (maximum of one)
DocumentFragment
Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
DocumentType
No children
EntityReference
Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
Element
Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
Attr
Text, EntityReference
ProcessingInstruction
No children
Comment
No children
Text
No children
CDATASection
No children
Entity
Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
Notation
No children

Oracle XML DB DOM API for XMLType also specifies these interfaces:

  • A NodeList interface to handle ordered lists of Nodes, for example:

    • The children of a Node

    • Elements returned by the getElementsByTagName method of the element interface

  • A NamedNodeMap interface to handle unordered sets of nodes, referenced by their name attribute, such as the attributes of an element.

Working with Schema-Based XML Instances

Oracle Database has several extensions for character-set conversion and input and output to and from a file system. PL/SQL API for XMLType is optimized to operate on XML schema-based XML instances. Function newDOMDocument() constructs a DOM document handle, given an XMLType value.

A typical usage scenario would be for a PL/SQL application to:

  1. Fetch or construct an XMLType instance

  2. Construct a DOMDocument node over the XMLType instance

  3. Use the DOM API to access and manipulate the XML data


    Note:

    For DOMDocument, node types represent handles to XML fragments but do not represent the data itself.

    For example, if you copy a node value, DOMDocument clones the handle to the same underlying data. Any data modified by one of the handles is visible when accessed by the other handle. The XMLType value from which the DOMDocument handle is constructed is the actual data, and reflects the results of all DOM operations on it.


DOM NodeList and NamesNodeMap Objects

NodeList and NamedNodeMap objects in the DOM are active; that is, changes to the underlying document structure are reflected in all relevant NodeList and NamedNodeMap objects.

For example, if a DOM user gets a NodeList object containing the children of an element, and then subsequently adds more children to that element (or removes children, or modifies them), then those changes are automatically propagated in the NodeList, without additional action from the user. Likewise, changes to a node in the tree are propagated throughout all references to that node in NodeList and NamedNodeMap objects.

The interfaces: Text, Comment, and CDATASection, all inherit from the CharacterData interface.

PL/SQL DOM API for XMLType (DBMS_XMLDOM): Calling Sequence

Figure 10-1 illustrates the PL/SQL DOM API for XMLType (DBMS_XMLDOM) calling sequence.

You can create a DOM document (DOMDocument) from an existing XMLType or as an empty document.

  1. The newDOMDocument procedure processes the XMLTYpe or empty document. This creates a DOMDocument.

  2. You can use the DOM API methods such as createElement, createText, createAttribute, and createComment, and so on, to traverse and extend the DOM tree. See Table 10-1 for a full list of available methods.

  3. The results of these methods (DOMElement, DOMText, and so on) can also be passed to makeNode to obtain the DOMNode interface.

Figure 10-1 PL/SQL DOM API for XMLType: Calling Sequence

Description of adxdb014.gif follows
Description of the illustration adxdb014.gif

PL/SQL DOM API for XMLType Examples

Example 10-1 Creating and Manipulating a DOM Document

This example illustrates how to create a DOMDocument handle for an example element PERSON:

-- This example illustrates how to create a DOMDocument handle for an example
 element PERSON:
declare 
  var       XMLType; 
  doc       dbms_xmldom.DOMDocument; 
  ndoc      dbms_xmldom.DOMNode; 
  docelem   dbms_xmldom.DOMElement;
  node      dbms_xmldom.DOMNode; 
  childnode dbms_xmldom.DOMNode; 
  nodelist  dbms_xmldom.DOMNodelist;
  buf       varchar2(2000);
begin 
   var := xmltype('<PERSON> <NAME> ramesh </NAME> </PERSON>');

   -- Create DOMDocument handle:
   doc     := dbms_xmldom.newDOMDocument(var); 
   ndoc    := dbms_xmldom.makeNode(doc);

   dbms_xmldom.writetobuffer(ndoc, buf);
   dbms_output.put_line('Before:'||buf);

   docelem := dbms_xmldom.getDocumentElement( doc );

   -- Access element:
   nodelist := dbms_xmldom.getElementsByTagName(docelem, 'NAME');
   node := dbms_xmldom.item(nodelist, 0);
   childnode := dbms_xmldom.getFirstChild(node);

   -- Manipulate:
   dbms_xmldom.setNodeValue(childnode, 'raj');

   dbms_xmldom.writetobuffer(ndoc, buf);
   dbms_output.put_line('After:'||buf);
end;
/

Example 10-2 Creating a DOM Document Using sys.xmltype

This example creates a DOM document from an XMLType value:

declare
 doc  dbms_xmldom.DOMDocument;
  
 buf   varchar2(32767);
  
begin
  -- new document
  doc := dbms_xmldom.newDOMDocument(sys.xmltype('<person> <name>Scott</name>
  </person>'));
  dbms_xmldom.writeToBuffer(doc, buf);
  dbms_output.put_line(buf);
end;
/

Example 10-3 Creating an Element Node

-- This example creates an element node starting from an empty DOM document:
declare
 doc            dbms_xmldom.DOMDocument;
 elem           dbms_xmldom.DOMElement;
 nelem          dbms_xmldom.DOMNode;
begin
    -- new document
       doc := dbms_xmldom.newDOMDocument;
    
    -- create a element node
       elem := dbms_xmldom.createElement(doc, 'ELEM');
   
    -- make node
       nelem := dbms_xmldom.makeNode(elem);
       dbms_output.put_line('Node name = '||dbms_xmldom.getNodeName(nelem));
       dbms_output.put_line('Node value = '||
                            dbms_xmldom.getNodeValue(nelem));
       dbms_output.put_line('Node type = '||dbms_xmldom.getNodeType(nelem));
end;
/

PL/SQL Parser API for XMLType (DBMS_XMLPARSER)

XML documents are made up of storage units, called entities, that contain either parsed or unparsed data. Parsed data is made up of characters, some of which form character data and some of which form markup. Markup encodes a description of the document storage layout and logical structure. XML provides a mechanism for imposing constraints on the storage layout and logical structure.

A software module called an XML parser or processor reads XML documents and provides access to their content and structure. An XML parser usually does its work on behalf of another module, typically the application.

PL/SQL Parser API for XMLType: Features

In general, PL/SQL Parser API for XMLType (DBMS_XMLPARSER) performs the following tasks:

  • Builds a result tree that can be accessed by PL/SQL APIs

  • Raises an error if the parsing fails

Table 10-3 lists the PL/SQL Parser API for XMLType (DBMS_XMLPARSER) methods.

Table 10-3 DBMS_XMLPARSER Methods

Method Arguments, Return Values, and Results
parse
Argument: (url VARCHAR2)

Result: Parses XML stored in the given URL or file and returns the built DOM Document

newParser
Returns: A new parser instance
parse
Argument: (p Parser, url VARCHAR2)

Result: Parses XML stored in the given URL or file

parseBuffer
Argument: (p Parser, doc VARCHAR2)

Result: Parses XML stored in the given buffer

parseClob
Argument: (p Parser, doc CLOB)

Result: Parses XML stored in the given CLOB

parseDTD
Argument: (p Parser, url VARCHAR2, root VARCHAR2)

Result: Parses XML stored in the given URL or file

parseDTDBuffer
Argument: (p Parser, dtd VARCHAR2, root VARCHAR2)

Result: Parses XML stored in the given buffer

parseDTDClob
Argument: (p Parser, dtd CLOB, root VARCHAR2)

Result: Parses XML stored in the given clob

setBaseDir
Argument: (p Parser, dir VARCHAR2)

Result: Sets base directory used to resolve relative URLs

showWarnings
Argument: (p Parser, yes BOOLEAN)

Result: Turns warnings on or off

setErrorLog
Argument: (p Parser, fileName VARCHAR2)

Result: Sets errors to be sent to the specified file

setPreserveWhitespace
Argument: (p Parser, yes BOOLEAN)

Result: Sets white space preserve mode

setValidationMode
Argument: (p Parser, yes BOOLEAN)

Result: Sets validation mode

getValidationMode
Argument: (p Parser)

Result: Gets validation mode

setDoctype
[Not supported.]

Argument: (p Parser, dtd DOMDocumentType)

Result: Sets DTD

getDoctype
[Not supported.]

Argument: (p Parser)

Result: Gets DTD

getDocument
Argument: (p Parser)

Result: Gets DOM document

freeParser
Argument: (p Parser)

Result: Frees a Parser object


PL/SQL Parser API for XMLType (DBMS_XMLPARSER): Calling Sequence

Figure 10-2 illustrates the PL/SQL Parser for XMLType (DBMS_XMLPARSER) calling sequence:

  1. newParser method can be used to construct a Parser instance.

  2. XML documents can then be parsed using the Parser with methods such as parseBuffer, parseClob, parse(URI), and so on. See Table 10-3 for a full list of Parser methods.

  3. An error is raised if the input is not a valid XML document.

  4. To use the PL/SQL DOM API for XMLType on the parsed XML document instance, you must call getDocument on the Parser to obtain a DOMDocument interface.

Figure 10-2 PL/SQL Parser API for XMLType: Calling Sequence

Description of adxdb015.gif follows
Description of the illustration adxdb015.gif

PL/SQL Parser API for XMLType Example

Example 10-4 Parsing an XML Document

This example parses a simple XML document and enables DOM APIs to be used.

declare
 indoc       VARCHAR2(2000);
 indomdoc    dbms_xmldom.domdocument;
 innode      dbms_xmldom.domnode;
 myParser    dbms_xmlparser.Parser;
begin
   indoc   := '<emp><name> Scott </name></emp>';
   myParser := dbms_xmlparser.newParser;
   dbms_xmlparser.parseBuffer(myParser, indoc);
   indomdoc   := dbms_xmlparser.getDocument(myParser);
   innode     := dbms_xmldom.makeNode(indomdoc);
-- DOM APIs can be used here
end;
/

PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR)

W3C XSL Recommendation describes rules for transforming a source tree into a result tree. A transformation expressed in eXtensible Stylesheet Language Transformation (XSLT) is called an XSL style sheet. The transformation specified is achieved by associating patterns with templates defined in the XSLT style sheet. A template is instantiated to create part of the result tree.

Enabling Transformations and Conversions with XSLT

The Oracle XML DB PL/SQL DOM API for XMLType also supports eXtensible Stylesheet Language Transformation (XSLT). This enables transformation from one XML document to another, or conversion into HTML, PDF, or other formats. XSLT is also widely used to convert XML to HTML for browser display.

The embedded XSLT processor follows eXtensible Stylesheet Language (XSL) statements and traverses the DOM tree structure for XML data residing in XMLType. Oracle XML DB applications do not require a separate parser as did the prior release XML Parser for PL/SQL. However, applications requiring external processing can still use the XML Parser for PL/SQL first to expose the document structure.


Note:

The PL/SQL package DBMS_XSLPROCESSOR provides a convenient and efficient way of applying a single style sheet to multiple documents. The performance of this package will be better than transform() because the style sheet will be parsed only once.


Note:

The XML Parser for PL/SQL in Oracle XDK parses an XML document (or a standalone DTD) so that the XML document can be processed by an application, typically running on the client. PL/SQL APIs for XMLType are used for applications that run on the server and are natively integrated in the database. Benefits include performance improvements and enhanced access and manipulation options.

PL/SQL XSLT Processor for XMLType: Features

PL/SQL XSLT Processor for XMLType (DBMS_XSLPROCESSOR) is the Oracle XML DB implementation of the XSL processor. This follows the W3C XSLT final recommendation (REC-xslt-19991116). It includes the required action of an XSL processor in terms of how it must read XSLT style sheets and the transformations it must achieve.

The types and methods of PL/SQL XSLT Processor are made available by the PL/SQL package, DBMS_XSLPROCESSOR.

PL/SQL XSLT Processor API (DBMS_XSLPROCESSOR): Methods

The methods in PL/SQL XSLT Processor API (DBMS_XSLPROCESSOR) use two PL/SQL types specific to the XSL Processor implementation. These are the Processor type and the Stylesheet type.

Table 10-4 lists PL/SQL XSLT Processor (DBMS_XSLPROCESSOR) methods.


Note:

There is no space between the method declaration and the arguments, for example: processXSL(p Processor, ss Stylesheet, xmldoc DOMDocument)

Table 10-4 DBMS_XSLPROCESSOR Methods

Method Argument or Return Values or Result
newProcessor
Returns: a new processor instance
processXSL
Argument: (p Processor, ss Stylesheet, xmldoc DOMDocument)

Result: Transforms input XML document using given DOMDocument and style sheet

processXSL
Argument: (p Processor, ss Stylesheet, xmldoc DOMDocumentFragment)

Result: Transforms input XML document using the given DOMDocumentFragment and style sheet

showWarnings
Argument: (p Processor, yes BOOLEAN)

Result: Turn warnings on or off

setErrorLog
Argument: (p Processor, Filename VARCHAR2)

Result: Sets errors to be sent to the specified file

NewStylesheet
Argument: (Input VARCHAR2, Reference VARCHAR2)

Result: Sets errors to be sent to the specified file

transformNode
Argument: (n DOMNode, ss Stylesheet)

Result: Transforms a node in a DOM tree using the given style sheet

selectNodes
Argument: (n DOMNode, pattern VARCHAR2)

Result: Selects nodes from a DOM tree that match the given pattern

selectSingleNodes
Argument: (n DOMNode, pattern VARCHAR2)

Result: Selects the first node from the tree that matches the given pattern

valueOf
Argument: (n DOMNode, pattern VARCHAR2)

Result: Retrieves the value of the first node from the tree that matches the given pattern

setParam
Argument: (ss Stylesheet, name VARCHAR2, value VARCHAR2)

Result: Sets a top level paramter in the given style sheet

removeParam
Argument: (ss Stylesheet, name VARCHAR2)

Result: Removes a top-level style-sheet parameter

ResetParams
Argument: (ss Stylesheet)

Result: Resets the top-level style-sheet parameters

freeStylesheet
Argument: (ss Stylesheet)

Result: Frees the given Stylesheet object

freeProcessor
Argument: (p Processor)

Result: Frees the given Processor object


PL/SQL Parser API for XMLType (DBMS_XSLPROCESSOR): Calling Sequence

Figure 10-3 illustrates the XSLT Processor for XMLType (DBMS_XSLPROCESSOR) calling sequence:

  1. An XSLT Processor can be constructed using the method newProcessor.

  2. To build a Stylesheet from a DOM document, use method newStylesheet.

  3. Optionally, you can set parameters to the Stylesheet using the call setParams.

  4. The XSLT processing can then be executed with the call processXSL using the processor and Stylesheet created in Steps 1 - 3.

  5. Pass the XML document to be transformed to the call processXSL.

  6. The resulting DOMDocumentFragment interface can be operated on using the PL/SQL DOM API for XMLType.

Figure 10-3 PL/SQL XSLT Processor for XMLType: Calling Sequence

Description of adxdb016.gif follows
Description of the illustration adxdb016.gif

PL/SQL XSLT Processor for XMLType Example

Example 10-5 Transforming an XML Document Using an XSL Style Sheet

This example transforms an XML document by using the processXSL() call. Expect the following output (XML with tags ordered based on tag name):

<emp>
   <empno>1</empno>
   <fname>robert</fname>
   <job>engineer</job>
   <lname>smith</lname>
   <sal>1000</sal>
</emp>

declare
 indoc       VARCHAR2(2000);
 xsldoc      VARCHAR2(2000);
 myParser    dbms_xmlparser.Parser;
 indomdoc    dbms_xmldom.domdocument;
 xsltdomdoc  dbms_xmldom.domdocument;
 xsl         dbms_xslprocessor.stylesheet;
 outdomdocf  dbms_xmldom.domdocumentfragment;
 outnode     dbms_xmldom.domnode;
 proc        dbms_xslprocessor.processor;
 buf         varchar2(2000);
begin
   indoc      := '<emp><empno> 1</empno> <fname> robert </fname> <lname>
 smith</lname> <sal>1000</sal> <job> engineer </job> </emp>';
   xsldoc     := 
   '<?xml version="1.0"?> 
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output encoding="utf-8"/>
      <!-- alphabetizes an xml tree -->
      <xsl:template match="*">
        <xsl:copy>
         <xsl:apply-templates select="*|text()">
         <xsl:sort select="name(.)" data-type="text" order="ascending"/>
         </xsl:apply-templates>
        </xsl:copy>
      </xsl:template>
      <xsl:template match="text()">
        <xsl:value-of select="normalize-space(.)"/>
      </xsl:template>
    </xsl:stylesheet>';
   
   myParser := dbms_xmlparser.newParser;
   dbms_xmlparser.parseBuffer(myParser, indoc);
   indomdoc   := dbms_xmlparser.getDocument(myParser);
   dbms_xmlparser.parseBuffer(myParser, xsldoc);
   xsltdomdoc := dbms_xmlparser.getDocument(myParser);
   xsl        := dbms_xslprocessor.newstylesheet(xsltdomdoc, '');
   proc       := dbms_xslprocessor.newProcessor;

   --apply stylesheet to DOM document   
   outdomdocf := dbms_xslprocessor.processxsl(proc, xsl, indomdoc);
   outnode    := dbms_xmldom.makenode(outdomdocf); 
-- PL/SQL DOM API for XMLType can be used here
   dbms_xmldom.writetobuffer(outnode, buf);
   dbms_output.put_line(buf);
end;
/