Skip Headers

Oracle9i XML Database Developer's Guide - Oracle XML DB
Release 2 (9.2)

Part Number A96620-02
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 Go to next page
View PDF

8
PL/SQL API for XMLType

This chapter describes the use of the APIs for XMLType in PL/SQL. It contains the following sections:

Introducing PL/SQL APIs for XMLType

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

Backward Compatibility with XDK for PL/SQL, Oracle9i Release 1 (9.0.1)

This release maintains support for the XDK for PL/SQL:

to ensure backward compatibility. Therefore, most applications written for Oracle9i Release 1 (9.0.1) XML Parser for PL/SQL and XSLT Processor for PL/SQL instances will need no changes. In this release, new applications built with the updated PL/SQL DOM and the extensions to XMLType API do not need the XDK's XML Parser for PL/SQL and XSLT Processor for PL/SQL.

See Also:

Oracle9i XML Developer's Kits Guide - XDK

If Your Application Uses Character-Set Conversions and File Systems

Applications that extensively use character-set conversions and file system interaction require some changes. The changes needed are due to the UTL_FILE package limitations, such as read/write to files in the UTL_FILE_DIR specified at database start-up.


Note:

In this release, the PL/SQL packages DBMS_XMLDOM, DBMS_XMLPARSER, and DBMS_XSLPROCESSOR, replace the previous XDK packages XMLDOM, XMLPARSER, and XSLPROCESSOR.


Differences Between PL/SQL API for XMLType and XDK for PL/SQL

This section explains differences between PL/SQL APIs native to Oracle XML DB and PL/SQL APIs available in XML Developer's Kits (XDK).

PL/SQL APIs For XMLType 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 as they are requested. It throws away previously-referenced sections of the document if memory usage grows too large. Lazy XML loading supports highly scalable applications that have many concurrent users needing to access large XML documents.

XMLType Datatype Now Supports XML Schema

The XMLType datatype has been enhanced in this release to include support for XML schemas. You can create an XML schema and annotate it with XML to object- relational mappings. To take advantage of the PL/SQL DOM API, 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.

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's structure. It then checks whether or not the document is well-formed and optionally whether it complies with a specific Document Type Definition (DTD). A DOM parser also provides methods for traversing the DOM tree and return data from it.

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

Server-Side Support

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

PL/SQL DOM API for XMLType (DBMS_XMLDOM)

Introducing W3C Document Object Model (DOM) Recommendation

Skip this section if you are already familiar with the generic DOM 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.

The following briefly describe each level:

Difference Between DOM and SAX

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

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:

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

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

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

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

This release has updated the PL/SQL DOM API to exploit a C-based representation of XML in the server and to operate on XML schema-based XML instances. Oracle XML DB PL/SQL DOM API for XMLType and Java DOM API for XMLType comply with the W3C DOM Recommendations to define and implement structured storage of XML in relational or object-relational columns and as in-memory instances of XMLType. See "Using PL/SQL DOM API for XMLType: Preparing XML Data", 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's 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 need to use separate XML translation techniques for the different data sources in your environment. Applications needing to exchange XML data can use one native XML database to cache XML documents. Thus, Oracle XML DB can speed up application performance by acting as an intermediate cache between your Web applications and your back-end data sources, whether in relational databases or in disparate file systems.

See Also:

Chapter 9, "Java API for XMLType"

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:

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:

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:

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, "Structured Mapping of XMLType" 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.

See Also:

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:

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.

See Also:

Chapter 11, "XMLType Views"

PL/SQL DOM API for XMLType (DBMS_XMLDOM) Methods

Table 8-1 lists the PL/SQL DOM API for XMLType (DBMS_XMLDOM) methods supported in Release 2 (9.2.0.1).

Non-Supported DBMS_XMLDOM Methods in Release 2 (9.2.0.2)

The following DBMS_XMLDOM methods are not supported in Release 2 (9.2.0.2):

Table 8-2 lists additional methods supported in Release 2 (9.2.0.2).

Table 8-1 Summary of Release 2 (9.2.0.1) DBMS_XMLDOM Methods  
Group/Method Description

Node methods

--

isNull()

Tests if the node is NULL.

makeAttr()

Casts the node to an Attribute.

makeCDataSection()

Casts the node to a CDataSection.

makeCharacterData()

Casts the node to CharacterData.

makeComment()

Casts the node to a Comment.

makeDocumentFragment()

Casts the node to a DocumentFragment.

makeDocumentType()

Casts the node to a Document Type.

makeElement()

Casts the node to an Element.

makeEntity()

Casts the node to an Entity.

makeEntityReference()

Casts the node to an EntityReference.

makeNotation()

Casts the node to a Notation.

makeProcessingInstruction()

Casts the node to a DOMProcessingInstruction.

makeText()

Casts the node to a DOMText.

makeDocument()

Casts the node to a DOMDocument.

writeToFile()

Writes the contents of the node to a 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.

C data section methods

--

isNull()isNull()

Tests if the CDataSection is NULL.

makeNode()makeNode()

Casts the CDatasection to a node.

Character data methods

--

isNull()

Tests if the CharacterData is NULL.

makeNode()

Casts the CharacterData to a node.

getData()

Retrieves the data of the node.

setData()

Sets the data to the node.

getLength()

Retrieves the length of the data.

substringData()

Retrieves the substring of the data.

appendData()

Appends the given data to the node data.

insertData()

Inserts the data in the node at the given offSets.

deleteData()

Deletes the data from the given offSets.

replaceData()

Replaces the data from the given offSets.

Comment methods

--

isNull()

Tests if the comment is NULL.

makeNode()

Casts the Comment to a node.

DOM implementation methods

--

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. [Not supported in this release]

Entity methods

--

isNull()

Tests if the Entity is NULL.

makeNode()

Casts the Entity to a node.

getPublicId()

Retrieves the public Id of the entity.

getSystemId()

Retrieves the system Id of the entity.

getNotationName()

Retrieves the notation name of the entity.

Entity reference methods

--

isNull()

Tests if the entity reference is NULL.

makeNode()

Casts the Entity reference to NULL.

Notation methods

--

isNull()

Tests if the notation is NULL.

makeNode()

Casts the notation to a node.

getPublicId()

Retrieves the public Id of the notation.

getSystemId()

Retrieves the system Id of the notation.

Processing instruction methods

--

isNull()

Tests if the processing instruction is NULL.

makeNode()

Casts the Processing instruction to a node.

getData()

Retrieves the data of the processing instruction.

getTarget()

Retrieves the target of the processing instruction.

setData()

Sets the data of the processing instruction.

Text methods

--

isNull()

Tests if the text is NULL.

makeNode()

Casts the text to a node.

splitText()

Splits the contents of the text node into 2 text nodes.

Document methods

--

isNull()

Tests if the document is NULL.

makeNode()

Casts the document to a node.

newDOMDocument()

Creates a new document.

freeDocument()

Frees the document.

getVersion()

Retrieves the version of the document. [Not supported in this release]

setVersion()

Sets the version of the document. [Not supported in this release]

getCharset()

Retrieves the Character set of the document. [Not supported in this release]

setCharset()

Sets the Character set of the document. [Not supported in this release]

getStandalone()

Retrieves if the document is specified as standalone. [Not supported in this release]

setStandalone()

Sets the document standalone. [Not supported in this release]

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.

Table 8-2 DBMS_XMLDOM Methods Added in Release 2 (9.2.0.2) 
Method Syntax

createDocument

FUNCTION createDocument (namspaceURI IN VARCHAR2, qualifiedName IN VARCHAR2, doctype IN DOMType :=NULL) REURN 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 further information, see Oracle9i XML Developer's Kits Guide - XDK.

The exceptions have not changed since the prior release:

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:

Table 8-3 shows the node types for XML and HTML and the allowed corresponding children node types.

Table 8-3 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:

Working with XML Schema-Based XML Instances

This release introduces several extensions for character-set conversion and input and output to and from a file system. As stated earlier in this chapter, applications written against the PL/SQL Parser APIs in the previous release continue to work, but require some modifications that are described in the following sections.

PL/SQL API for XMLType is optimized to operate on XML schema-based XML instances.

A new function is provided, newDOMDocument that constructs a DOM Document handle given an XMLType value.

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

  1. Fetch or construct an XMLType instance
  2. Construct a DOMDocument node over the XMLType instance
  3. Use the DOM API to access and manipulate the XML data


    Note:

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

    For example, if you copy a node value, DOMDocument simply clones the handle to the same underlying data. Any data 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 live; 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), those changes are automatically propagated in the NodeList, without further 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 8-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 8-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 8-1 PL/SQL DOM API for XMLType: Calling Sequence

Text description of adxdb014.gif follows
Text description of the illustration adxdb014.gif


PL/SQL DOM API for XMLType Examples

Example 8-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 8-2 Creating a DOM Document Using sys.xmltype

This example creates a DOM document from an XMLType:

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

Example 8-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(dbms_xmldom.getNodeName(nelem));
       dbms_output.put_line(dbms_xmldom.getNodeValue(nelem));
       dbms_output.put_line(dbms_xmldom.getNodeType(nelem));
end;
/

PL/SQL Parser API for XMLType (DBMS_XMLPARSER)

XML documents are made up of storage units, called entities, that contain either parsed or unparsed data. Parsed data is made up of characters, some of which form character data and some of which form markup. Markup encodes a description of the document's storage layout and logical structure. XML provides a 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:

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

Table 8-4 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

Argument: (p Parser, dtd DOMDocumentType)

Result: Sets DTD

getDoctype

Argument: (p Parser)

Result: Gets DTD

getDocument

Argument: (p Parser)

Result: Gets DOM document

freeParser

Argument: (p Parser)

Result: Frees a Parser object

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

Figure 8-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 8-4 for a full list of Parser methods.
  3. An error is raised if the input is not a valid XML document.
  4. To use the PL/SQL DOM API for XMLType on the parsed XML document instance, you need to call getDocument on the Parser to obtain a DOMDocument interface.

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

Text description of adxdb015.gif follows
Text description of the illustration adxdb015.gif


PL/SQL Parser API for XMLType Example

Example 8-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 stylesheet. The transformation specified is achieved by associating patterns with templates defined in the XSL stylesheet. A template is instantiated to create part of the result tree.

Enabling Transformations and Conversions with XSLT

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

The embedded XSLT processor follows eXtensible Stylesheet Language (XSL) statements and traverses the DOM tree structure for XML data residing in XMLType. Oracle XML DB applications do not require a separate parser as did the prior release's 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 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.


See Also:

Appendix D, "XSLT Primer"

PL/SQL XSLT Processor for XMLType: Features

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

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 8-5 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 8-5 DBMS_XSLPROCESSOR Methods  
Method Argument or Return Values or Result

newProcessor

Returns: a new processor instance

processXSL

Argument: (p Processor, ss Stylesheet, xmldoc DOMDocument)

Result: Transforms input XML document using given DOMDocument and stylesheet

processXSL

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

Result: Transforms input XML document using given DOMDocumentFragment and stylesheet

showWarnings

Argument: (p Processor, yes BOOLEAN)

Result: Turn warnings on or off

setErrorLog

Argument: (p Processor, Filename VARCHAR2)

Result: Sets errors to be sent to the 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 stylesheet

selectNodes

Argument: (n DOMNode, pattern VARCHAR2)

Result: Selects nodes from a DOM tree which 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 stylesheet

removeParam

Argument: (ss Stylesheet, name VARCHAR2)

Result: Removes a top level stylesheet parameter

ResetParams

Argument: (ss Stylesheet)

Result: Resets the top-level stylesheet parameters

freeStylesheet

Argument: (ss Stylesheet)

Result: Frees a Stylesheet object

freeProcessor

Argument: (p Processor)

Result: Frees a Processor object

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

Figure 8-2 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 8-3 PL/SQL XSLT Processor for XMLType: Calling Sequence

Text description of adxdb016.gif follows
Text description of the illustration adxdb016.gif


PL/SQL XSLT Processor for XMLType Example

Example 8-5 Transforming an XML Document Using an XSL Stylesheet

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

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

declare
 indoc       VARCHAR2(2000);
 xsldoc      VARCHAR2(2000);
 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;
/