Contents

Title and Copyright Information

Preface

Documentation Accessibility

Conventions

1 Introduction and Roadmap

Document Scope and Audience

Guide to This Document

Related Documentation

Samples for the XML Developer

XML Examples in the WebLogic Server Distribution

New and Changed XML Features in This Release

Summary of WebLogic Server XML Features

XML Document Parsers

Difference In Default Parsers Between Versions 8.1 and 9.1 of WebLogic Server

XML Document Transformer

Streaming API for XML (StAX) Implementation

WebLogic XPath API

JAXP Pluggability Layer Implementation

Java API for XML Registries Implementation

WebLogic Servlet Attributes

WebLogic XSLT JSP Tag Library

XML Registry For Configuring Parsers and Transformers

XML Registry for Configuring External Entity Resolution

Endorsed Standards Override Mechanism for DOM/SAX: Not Supported

Learning More About XML

2 XML Overview

What Is XML?

How Do You Describe an XML Document?

Why Use XML?

What Are XSL and XSLT?

What Are DOM and SAX?

SAX

DOM

What Is the Streaming API for XML (StAX)?

What Is JAXP?

JAXP Packages

New Feature of JAXP 1.2

Common Uses of XML and XSLT

Using XML and XSLT to Separate Content from Presentation

XML as a Message Format for Business-to-Business Communication

3 Developing XML Applications with WebLogic Server

Developing XML Applications: Main Steps

Parsing XML Documents

Parsing XML Documents Using JAXP in SAX Mode

Parsing XML Documents Using JAXP in DOM Mode

Parsing XML Documents in a Servlet

Using the org.xml.sax.DefaultHandler Attribute to Parse a Document

Using the org.w3c.dom.Document Attribute to Parse a Document

Validating and Non-Validating Parsers

Handling Entity Resolution While Parsing an XML Document

General Information About External Entities

Using the WebLogic Server Entity Resolution Features

Using Parsers Other Than the Default

Generating New XML Documents

Generating XML from a DOM Document Tree

Generating XML Documents in a JSP

Transforming XML Documents

Using JAXP to Transform XML Data

Example of Transforming an XML Document Using JAXP

Using the JSP Tag to Transform XML Data

XSLT JSP Tag Syntax

XSLT JSP Tag Usage

Transforming XML Documents Using an XSLT JSP Tag

Example of Using the XSLT JSP Tag in a JSP

Using Transformers Other Than the Default Transformer

4 Using the Streaming API for XML (StAX)

Overview of the Streaming API for XML

Description of the Cursor API

The XMLStreamReader Interface

The XMLStreamWriter Interface

Description of the Event Iterator API

Main Interfaces and Classes of StAX

Parsing XML With the XMLStreamReader Interface: Typical Steps

Example of Parsing XML Using StAX

Getting the XMLStreamReader Object

Determining the Specific XML Event Type

Getting the Full Name of an Element

Getting the Attributes of an Element

Getting the Namespaces of an Element

Getting Text Data

Getting Location Information

Closing the Input Stream

Generating XML Using the XMLStreamWriter Interface: Typical Steps

Example of Generating XML Using StAX

Getting the XMLStreamWriter Object

Adding the XML Declaration to the Output Stream

Adding Standard XML Events to the Output Stream

Adding Attributes and Namespace Declarations to a Start Element

Closing the Output Stream

Properties Defined for the XMLInputFactory Interface

Properties Defined for the XMLOutputFactory Interface

5 Using Advanced XML APIs

Using the Java API for XML Registries (JAXR) API

Using the WebLogic XPath API

Using the DOMXPath Class

Example of Using the DOMXPath Class

Main Steps When Using the DOMXPath Class

Using the StreamXPath Class

Example of Using the StreamXPath Class

Main Steps When Using the StreamXPath Class

6 XML Programming Best Practices

When to Use the DOM, SAX, and StAX APIs

Increasing Performance of XML Validation

When to Use XML Schemas or DTDs

Configuring External Entity Resolution for Maximum Performance

Using SAX InputSources

Improving Performance of Transformations

7 XML Programming Techniques

Transmitting XML Data Between A Java Client and WebLogic Server

Handling XML Documents in a JMS Application

Accessing External Entities That Do Not Have an HTTP Interface

8 XML Application Scoping

Overview of Application Scoping

The weblogic-application.xml File

xml

parser-factory

saxparser-factory

document-builder-factory

transformer-factory

entity-mapping

entity-mapping-name

public-id

system-id

entity-uri

when-to-cache

cache-timeout-interval

Configuring a Parser or Transformer for an Enterprise Application

Configuring an External Entity for an Enterprise Application

Configuring the External Entity Cache for an Enterprise Application

9 Administering WebLogic Server XML

Overview of Administering WebLogic Server XML

XML Administration Tasks

How the XML Registry Works

Parser Selection Within the XML Registry

XML Parser and Transformer Configuration Tasks

Configuring a Parser or Transformer Other Than the Default

Configuring a Parser for a Particular Document Type

External Entity Configuration Tasks

Configuring External Entity Resolution

Configuring the External Entity Cache

A XML Reference

XML APIs

Code Examples

Related WebLogic Server Documentation

Tutorials and Online Courses

Other XML Specifications and Information

B Using the WebLogic XML Streaming API (Deprecated)

Overview of the WebLogic XML Streaming API

Javadocs for the WebLogic XML Streaming API

Parsing an XML Document: Typical Steps

Example of Parsing an XML Document

Getting an XML Input Stream

Getting a Buffered XML Input Stream

Filtering the XML Stream

Creating a Custom Filter

Iterating Over the Stream

Determining the Specific XMLEvent Type

Getting the Attributes of an Element

Positioning the Stream

Getting a Substream

Marking and Resetting a Buffered XML Input Stream

Closing the Input Stream

Generating a New XML Document: Typical Steps

Example of Generating an XML Document

Creating an XML Output Stream

Adding Elements to the Output Stream

Adding Attributes to an Element on the Output Stream

Adding an Input Stream to an Output Stream

Printing an Output Stream

Closing the Output Stream

Oracle® Fusion Middleware

Programming XML for Oracle WebLogic Server

11g Release 1 (10.3.6)

E13724-04

November 2011

This document is a resource for software developers who design and develop applications that include XML processing.

Oracle Fusion Middleware Programming XML for Oracle WebLogic Server, 11g Release 1 (10.3.6)

E13724-04

Copyright © 2007, 2011, Oracle and/or its affiliates. All rights reserved.

This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.

The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.

If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle America, Inc., 500 Oracle Parkway, Redwood City, CA 94065.

This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group.

This software or hardware and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.

Preface

This preface describes the document accessibility features and conventions used in this guide—Programming XML for Oracle WebLogic Server.

Documentation Accessibility

For information about Oracle's commitment to accessibility, visit the Oracle Accessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc.

Access to Oracle Support

Oracle customers have access to electronic support through My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info or visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trs if you are hearing impaired.

Conventions

The following text conventions are used in this document:

Convention | Meaning
boldface | Boldface type indicates graphical user interface elements associated with an action, or terms defined in text or the glossary.
italic | Italic type indicates book titles, emphasis, or placeholder variables for which you supply particular values.
monospace | Monospace type indicates commands within a paragraph, URLs, code in examples, text that appears on the screen, or text that you enter.

1 Introduction and Roadmap

This section describes the contents and organization of this guide—Programming XML for Oracle WebLogic Server.

Document Scope and Audience

Guide to This Document

Related Documentation

New and Changed XML Features in This Release

Summary of WebLogic Server XML Features

Endorsed Standards Override Mechanism for DOM/SAX: Not Supported

Learning More About XML

Document Scope and Audience

This document is a resource for software developers who design and develop applications that include XML processing.

The topics in this document are relevant during the design and development phases of a software project. The document also includes topics that are useful in solving application problems that are discovered during test and pre-production phases of a project.

Although this document does include administration and monitoring information useful to developers who want to test their applications in a development environment, the document does not address production-phase administration, monitoring, or performance tuning topics XML topics. For links to WebLogic Server® documentation and resources for these topics, see Related Documentation.

It is assumed that the reader is familiar with Web technologies, XML, XSLT, the Java programming language, and the Servlet and JSP APIs of the Java EE specification. This document emphasizes the value-added features provided by WebLogic Server XML and key information about how to use WebLogic Server features and facilities to get an application that performs XML processing up and running.

Guide to This Document

This document is organized as follows:

This chapter, Chapter 1, "Introduction and Roadmap," introduces the organization of this guide and the features of WebLogic Server XML.

Chapter 2, "XML Overview," provides an overview of XML technology and the WebLogic Server XML subsystem.

Chapter 3, "Developing XML Applications with WebLogic Server," describes how to process XML documents from within a WebLogic Server application using XML APIs and tools. The main processing tasks include parsing an existing XML document, generating a new XML document, and transforming a XML document into another format.

Chapter 4, "Using the Streaming API for XML (StAX)," describes in detail how to use the Streaming API for XML (StAX) in your Java applications to parse and generate an XML document.

Chapter 5, "Using Advanced XML APIs," describes how to use additional XML APIs to do more advanced tasks, such as performing XPath matching against an XML document.

Chapter 6, "XML Programming Best Practices," describes some best practices to follow when creating Java applications that process XML documents.

Chapter 7, "XML Programming Techniques," describes specific programming techniques for tasks such as using message-driven beans and JMS queues with XML documents, and so on.

Chapter 8, "XML Application Scoping," describes how to configure parsers, transformers, and external entities for a particular Enterprise application.

Chapter 9, "Administering WebLogic Server XML," describes the Administration Console XML Registry and how to perform XML configuration tasks.

Appendix A, "XML Reference," provides pointers to specifications and application programming interfaces supported by the XML software.

Appendix B, "Using the WebLogic XML Streaming API (Deprecated)," describes how to use the deprecated WebLogic XML Streaming API. The topic is included in this guide for legacy reasons only; you should not use this API for new applications. Instead you should use StAX, described in Chapter 4, "Using the Streaming API for XML (StAX)."

Related Documentation

This document contains XML-specific design and development information.

For comprehensive guidelines for developing, deploying, and monitoring WebLogic Server applications, see the following documents:

Developing Applications for Oracle WebLogic Server is a guide to developing WebLogic Server components (such as Web applications and EJBs) and applications.

Getting Started With JAX-WS Web Services for Oracle WebLogic Server is a guide to developing Web Services that are deployed and run on WebLogic Server.

Deploying Applications to Oracle WebLogic Server is the primary source of information about deploying WebLogic Server applications.

For related information about XML outside the scope of this document, see links listed in Learning More About XML and Appendix A, "XML Reference."

Samples for the XML Developer

In addition to this document, Oracle provides a variety of code samples for XML developers. The examples and tutorials illustrate WebLogic Server XML in action, and provide practical instructions on how to perform key XML development tasks.

Oracle recommends that you run some or all of the XML examples before programming your own application that processes XML.

XML Examples in the WebLogic Server Distribution

WebLogic Server optionally installs API code examples in WL_HOME\samples\server\examples\src\examples, where WL_HOME is the top-level directory of your WebLogic Server installation. You can start the examples server, and obtain information about the samples and how to run them from the WebLogic Server Start menu.

New and Changed XML Features in This Release

For a comprehensive listing of the new WebLogic Server features introduced in this release, see What’s New in Oracle WebLogic Server.

Summary of WebLogic Server XML Features

WebLogic Server consolidates XML technologies applicable to WebLogic Server and XML applications based on WebLogic Server. The WebLogic Server XML subsystem allows customers to use standard parsers, the WebLogic FastParser, XSLT transformers, and DTDs and XML Schemas to process and convert XML files.

The following topics, which describe the features included in the WebLogic Server XML subsystem, are presented in this section:

XML Document Parsers

XML Document Transformer

Streaming API for XML (StAX) Implementation

WebLogic XPath API

JAXP Pluggability Layer Implementation

Java API for XML Registries Implementation

WebLogic Servlet Attributes

WebLogic XSLT JSP Tag Library

XML Registry For Configuring Parsers and Transformers

XML Registry for Configuring External Entity Resolution

XML Document Parsers

WebLogic Server uses, by default, the XML parser that is included in the JDK Version 5.0.

You can also use any other XML parser of your choice by using the Administration Console to configure it in the XML Registry. You can configure a single instance of WebLogic Server to use one parser for a particular application and use another parser for a different application.

For information about parsing XML documents, see Parsing XML Documents.

Difference In Default Parsers Between Versions 8.1 and 9.1 of WebLogic Server

The default parser in Versions 8.1and previous of WebLogic Server was one that was based on Apache's Xerces parser and whose package name started with weblogic.apache.xerces.*. In Version 9.1 of WebLogic Server, this parser has been deprecated. Instead, the default parser is the same one that is shipped in JDK 5.0.

For backward compatibility, the weblogic.apache.xerces.* parser is still available in Version 9.1 of WebLogic Server, although it is deprecated and Oracle highly recommends you do not use it since it will not be available in future versions. If, however, you need to temporarily continue using this parser, you must use the Administration Console to configure a parser other than the default for your WebLogic Server instance by updating, or creating, a new XML Registry and setting the default implementation classes for SAX and DOM parser factory interfaces, as indicated in Table 1-1.

Table 1-1 Default Implementation Classes for SAX and DOM Parser Factory Interfaces

Parser Factory Interface
Implementation Class

DOM (DocumentBuilderFactory)

weblogic.apache.xerces.jaxp.DocumentBuilderFactoryImpl

SAX (SAXParserFactory)

weblogic.apache.xerces.jaxp.SAXParserFactoryImpl

For information about creating an XML Registry, see Chapter 9, "Administering WebLogic Server XML."

XML Document Transformer

WebLogic Server uses, by default, the XML transformer that is included in the JDK Version 5.0.

You can also use any other XML transformer of your choice by using the Administration Console to configure it in the XML Registry. You can configure a single instance of WebLogic Server to use one transformer for a particular application and use another transformer for a different application.

For more information about transforming XML documents, see Transforming XML Documents.

Streaming API for XML (StAX) Implementation

WebLogic Server includes an implementation of the Streaming API for XML (StAX).

For more information, see Chapter 4, "Using the Streaming API for XML (StAX)."

WebLogic XPath API

The WebLogic XPath API contains all of the classes required to perform XPath matching against a document represented as a DOM, an XMLInputStream, or an XMLOutputStream.

For more information, see Using the WebLogic XPath API.

JAXP Pluggability Layer Implementation

Java API for XML Processing (JAXP) 1.2 is a Java-standard, parser-independent API for XML. For more information on JAXP, see What Is JAXP?.

Note:

WebLogic Server uses the XML Registry, accessed through the Administration Console, to plug in parsers and transformers. This is different from the JAXP 1.2 specification which specifies the use of system properties to plug in parsers and transformers.

Java API for XML Registries Implementation

The Java API for XML Registries (JAXR) API, described at http://java.sun.com/webservices/jaxr/, provides a uniform and standard Java API for accessing different kinds of registries, in particular XML registries used in Web Service applications.

For more information, see Using the Java API for XML Registries (JAXR) API.

WebLogic Servlet Attributes

WebLogic Server supports the following special Servlet attributes:

org.xml.sax.HandlerBase

org.xml.sax.helpers.DefaultHandler

org.w3c.dom.Document

Calling the setAttribute (for SAX parsing) and getAttribute (for DOM parsing) methods on a ServletRequest object with the preceding attributes will parse any given XML document.

For more information, see Parsing XML Documents in a Servlet.

WebLogic XSLT JSP Tag Library

The JSP tag library provides a simple tag that enables access to the default XSLT transformer from within a Java Server Page (JSP) running on WebLogic Server. Currently, this tag supports the default XSLT transformer only; you cannot use the tag to transform an XML document from within a JSP using a different transformer.

The JSP tag library is included in xmlx-tags.jar, which is installed when you install your WebLogic Server distribution.

For more information, see Using the JSP Tag to Transform XML Data.

XML Registry For Configuring Parsers and Transformers

The XML Registry simplifies administration and configuration tasks by separating these tasks from the XML application. Use the Administration Console to configure the parsers and transformers for an instance of WebLogic Server.

For more information, see XML Parser and Transformer Configuration Tasks.

XML Registry for Configuring External Entity Resolution

WebLogic XML supports external entity resolution through the XML Registry. For more information, see External Entity Configuration Tasks.

Endorsed Standards Override Mechanism for DOM/SAX: Not Supported

WebLogic Server does not support switching the server's DOM and SAX interfaces using the endorsed standards override mechanism.

An endorsed standard is a Java API defined through a standards process other than the Java Community Process (JCP). For more information, see Endorsed Standards Override Mechanism at http://download.oracle.com/javase/6/docs/technotes/guides/standards/.

Learning More About XML

To learn more about XML, see the following online courses and tutorials. Appendix A, "XML Reference," provides links to additional information.

A Technical Introduction to XML, available at http://www.xml.com/pub/a/98/10/guide0.html

XML Authoring Tutorial, available at http://www.xml.com/pub/r/32

Working with XML and Java, available at http://java.sun.com/xml/tutorial_intro.html

Tutorials for using the Java 2 platform and XML technology, available at http://developerlife.com/

XML, Java, and the Future of the Web, available at http://www.xml.com/pub/a/w3j/s3.bosak.html

Chapter 17 of The XML Bible: XSL Transformations, available at http://metalab.unc.edu/xml/books/bible/updates/14.html

XSL Tutorial by Miloslav Nic, available at http://zvon.vscht.cz/HTMLonly/XSLTutorial/Books/Book1/index.html

SAX 2.0: The Simple API for XML, available at http://www.saxproject.org/

Document Object Model (DOM), available at http://www.w3.org/DOM/

2 XML Overview

The following sections provide an overview of XML technology and the WebLogic Server XML subsystem:

What Is XML?

How Do You Describe an XML Document?

Why Use XML?

What Are XSL and XSLT?

What Are DOM and SAX?

What Is the Streaming API for XML (StAX)?

What Is JAXP?

Common Uses of XML and XSLT

What Is XML?

Extensible Markup Language (XML) is a markup language used to describe the content and structure of data in a document. It is a simplified version of Standard Generalized Markup Language (SGML). XML is an industry standard for delivering content on the Internet. Because it provides a facility to define new tags, XML is also extensible.

Like HTML, XML uses tags to describe content. However, rather than focusing on the presentation of content, the tags in XML describe the meaning and hierarchical structure of data. This functionality allows for the sophisticated data types that are required for efficient data interchange between different programs and systems. Further, because XML enables separation of content and presentation, the content, or data, is portable across heterogeneous systems.

The XML syntax uses matching start and end tags (such as <name> and </name>) to mark up information. Information delimited by tags is called an element. Every XML document has a single root element, which is the top-level element that contains all the other elements. Elements that are contained by other elements are often referred to as sub-elements. An element can optionally have attributes, structured as name-value pairs, that are part of the element and are used to further define it.

The following sample XML file describes the contents of an address book:

<?xml version="1.0"?>

<address_book>
  <person gender="f">
    <name>Jane Doe</name>
    <address>
      <street>123 Main St.</street>
      <city>San Francisco</city>
      <state>CA</state>
      <zip>94117</zip>
    </address>
    <phone area_code=415>555-1212</phone>
  </person>
  <person gender="m">
    <name>John Smith</name>
    <phone area_code=510>555-1234</phone>
    <email>johnsmith@somewhere.com</email>
  </person>
</address_book>

The root element of the XML file is address_book. The address book currently contains two entries in the form of person elements: Jane Doe and John Smith. Jane Doe's entry includes her address and phone number; John Smith's includes his phone and email address. Note that the structure of the XML document defines the phone element as storing the area code using the area_code attribute rather than a sub-element in the body of the element. Also note that not all sub-elements are required for the person element.

How Do You Describe an XML Document?

There are two ways to describe an XML document: XML Schemas and DTDs.

XML Schemas define the basic requirements for the structure of a particular XML document. A Schema describes the elements and attributes that are valid in an XML document, and the contexts in which they are valid. In other words, a Schema specifies which tags are allowed within certain other tags, and which tags and attributes are optional. Schemas are themselves XML files.

The schema specification is a product of the World Wide Web Consortium (W3C). For detailed information on XML schemas, see http://www.w3.org/TR/xmlschema-0/.

The following example shows a schema that describes the preceding address book sample XML document:

<xsd:schema xmlns:xsd="http://www.w3.org/1999/XMLSchema">

<xsd:complexType name="personType">
  <xsd:element   name="name"     type="xsd:string"/>
  <xsd:element   name="address"  type="addressType"/>
  <xsd:element   name="phone"    type="phoneType"/>
  <xsd:element   name="email"    type="xsd:string"/>
  <xsd:attribute name="gender"   type="xsd:string"/>
</xsd:complexType>

<xsd:complexType name="addressType">
  <xsd:element   name="street"  type="xsd:string"/>
  <xsd:element   name="city"    type="xsd:string"/>
  <xsd:element   name="state"   type="xsd:string"/>
  <xsd:element   name="zip"     type="xsd:string"/>
</xsd:complexType>

<xsd:simpleType name="phoneType">
  <xsd:restriction base="xsd:string"/>
  <xsd:attribute name="area_code" type="xsd:string"/>
</xsd:simpleType>

</xsd:schema>

You can also describe XML documents using Document Type Definition (DTD) files, a technology older than XML Schemas. DTDs are not XML files.

The following example shows a DTD that describes the preceding address book sample XML document:

<!DOCTYPE address_book [
<!ELEMENT person (name, address?, phone?, email?)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT address (street, city, state, zip)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT street (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
<!ATTLIST person gender CDATA #REQUIRED>
<!ATTLIST phone area_code CDATA #REQUIRED>
]>

An XML document can include a Schema or DTD as part of the document itself, reference an external Schema or DTD, or not include or reference a Schema or DTD at all. The following excerpt from an XML document shows how to reference an external DTD called address.dtd:

<?xml version=1.0?>
<!DOCTYPE address_book SYSTEM "address.dtd">
<address_book>
...

XML documents only need to be accompanied by Schema or DTD if they need to be validated by a parser or if they contain complex types. An XML document is considered valid if 1) it has an associated Schema or DTD, and 2) it complies with the constraints expressed in the associated Schema or DTD. If, however, an XML document only needs to be well-formed, then the document does not have to be accompanied by a Schema or DTD. A document is considered well-formed if it follows all the rules in the W3C Recommendation for XML 1.0. For the full XML 1.0 specification, see http://www.w3.org/XML/.

Why Use XML?

An industry typically uses data exchange methods that are meaningful and specific to that industry. With the advent of e-commerce, businesses conduct an increasing number of relationships with a variety of industries and, therefore, must develop expert knowledge of the various protocols used by those industries for electronic communication.

The extensibility of XML makes it a very effective tool for standardizing the format of data interchange among various industries. For example, when message brokers and workflow engines must coordinate transactions among multiple industries or departments within an enterprise, they can use XML to combine data from disparate sources into a format that is understandable by all parties.

What Are XSL and XSLT?

The Extensible Stylesheet Language (XSL) is a W3C standard for describing presentation rules that apply to XML documents. XSL includes both a transformation language, (XSLT), and a formatting language. These two languages function independently of each other. XSLT is an XML-based language and W3C specification that describes how to transform an XML document into another XML document, or into HTML, PDF, or some other document format.

An XSLT transformer accepts as input an XML document and an XSLT document. The template rules contained in an XSLT document include patterns that specify the XML tree to which the rule applies. The XSLT transformer scans the XML document for patterns that match the rule, and then it applies the template to the appropriate section of the original XML document.

What Are DOM and SAX?

DOM and SAX are two standard Java application programming interfaces (APIs) for parsing XML data. Both are supported by the WebLogic Server default parser. The two APIs differ in their approach to parsing, with each API having its strengths and weaknesses.

SAX

SAX stands for the Simple API for XML. It is a platform-independent language neutral standard interface for event-based XML parsing. SAX defines events that can occur as a parser is reading through an XML document, such as the start or the end of an element. Programmers provide handlers to deal with different events as the document is parsed.

Programmers that use the SAX API to parse XML documents have full control over what happens when these events occur and can, as a result, customize the parsing process extensively. For example, a programmer might decide to stop parsing an XML document as soon as the parser encounters an error that indicates that the document is invalid, rather than waiting until the entire document is parsed, thus improving performance.

The WebLogic Server default parser (the parser included in the JDK 5.0) supports SAX Version 2.0. Programmers who have created programs that use Version 1.0 of SAX to parse XML documents should read about the changes between the two versions and update their programs accordingly. For detailed information about the differences between the two versions, refer to http://www.saxproject.org/.

DOM

DOM stands for the Document Object Model. It is platform- and language-neutral interface that allows programs and scripts to access and update the content, structure, and style of XML documents dynamically. DOM reads an XML document into memory and represents it as a tree; each node of the tree represents a particular piece of data from the original XML document. Because the tree structure is a standard programming mechanism for representing data, traversing and manipulating the tree using Java is relatively easy, fast, and efficient. The main drawback, however, is that the entire XML document has to be read into memory for DOM to create the tree, which might decrease the performance of an application as the XML documents get larger.

The WebLogic Server default parser (the parser included in the JDK 5.0) supports DOM Level 2.0 Core. Programmers who have created programs that use Level 1.0 of DOM to parse XML documents should read about the changes between the two versions and update their programs accordingly. For detailed information about the differences, refer to http://www.w3.org/DOM/DOMTR.

What Is the Streaming API for XML (StAX)?

In addition to SAX and DOM, you can also parse and generate an XML document using the Streaming API for XML (StAX).

StAX is Java Community Process specification that describes a bi-directional API for reading and writing XML. StAX gives parsing control to the programmer by exposing a simple iterator-based API and an underlying stream of events; the API includes methods such as next() and hasNext() that allow the programmer to ask for the next event rather than handle the event in a callback. This gives the programmer more procedural control over the processing of the XML document.

Unlike DOM and SAX, StAX is not yet part of the Java API for XML Processing (JAXP).

Note:

Previous versions of WebLogic Server included a similar proprietary API called WebLogic XML Streaming API. This API was a basis for StAX. Although the WebLogic XML Streaming API is still accessible in this release of WebLogic Server, its functionality has been deprecated as of release 9.0 of WebLogic Server. Programmers should use StAX instead.

For detailed information about using StAX, see Chapter 4, "Using the Streaming API for XML (StAX)."

What Is JAXP?

The previous section discusses two APIs, SAX and DOM, that programmers can use to parse XML data. The Java API for XML Processing (JAXP) provides a means to get to these parsers. JAXP also defines a pluggability layer that allows programmers to use any compliant parser or transformer.

WebLogic Server implements JAXP to facilitate XML application development and the work required to move XML applications built on WebLogic Server to other Web application servers. JAXP was developed to make XML applications portable; it provides basic support for parsing and transforming XML documents through a standardized set of Java platform APIs. JAXP 1.2, included in the WebLogic Server distribution, is configured to use the default parser. Therefore, by default, XML applications built using WebLogic Server use JAXP.

The WebLogic Server distribution contains the interfaces and classes needed for JAXP 1.2. JAXP 1.2 contains explicit support for SAX Version 2 and DOM Level 2.

JAXP Packages

JAXP contains the following two packages:

javax.xml.parsers

javax.xml.transform

The javax.xml.parsers package contains the classes to parse XML data in SAX Version 2.0 and DOM Level 2.0 mode. To parse an XML document in SAX mode, a programmer first instantiates a new SaxParserFactory object with the newInstance() method. This method looks up the specific implementation of the parser to load based on a well-defined list of locations. The programmer then obtains a SaxParser instance from the SaxParserFactory and executes its parse() method, passing it the XML document to be parsed. Parsing an XML document in DOM mode is similar, except that the programmer uses the DocumentBuilder and DocumentBuilderFactory classes instead.

For detailed information on using JAXP to parse XML documents, see Parsing XML Documents.

The javax.xml.transform package contains classes to transform XML data, such as an XML document, a DOM tree, or SAX events, into a different format. The transformer classes work similarly to the parser classes. To transform an XML document, a programmer first instantiates a TransformerFactory object with the newInstance() method. This method looks up the specific implementation of the XSLT transformer to load based on a well-defined list of locations. The programmer then instantiates a new Transformer object based on a specific XSLT style sheet and executes its transform() method, passing it the XML object to transform. The XML object might be an XML file, a DOM tree, and so on.

For detailed information on using JAXP to transform XML objects, see Using JAXP to Transform XML Data.

New Feature of JAXP 1.2

Java EE 1.4 includes version 1.2 of JAXP, which is based on the 1.1 version, but adds support for W3C XML Schema. In particular, the 1.2 version specifies new property strings to enable XML Schema validation, specify the schema language being used, and the location of the particular XML Schema file that should be used when validating an XML file.

The following code snippet shows how to set Schema validation when using a SAX parser:

try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(true);
        SAXParser sp = spf.newSAXParser();
sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                       "http://www.w3.org/2001/XMLSchema");
sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                       "http://www.example.com/Report.xsd");
        DefaultHandler dh = new DefaultHandler();
        sp.parse("http://www.wombats.com/foo.xml", dh);
    } catch(SAXException se) {
        se.printStackTrace();
    }

For more information, see http://download.oracle.com/javase/6/docs/technotes/guides/xml/jaxp/index.html.

Common Uses of XML and XSLT

How you use XML and XSLT depends on your particular business needs.

Using XML and XSLT to Separate Content from Presentation

XML and XSLT are often used in applications that support multiple client types. For example, suppose you have a Web-based application that supports both browser-based clients and Wireless Application Protocol (WAP) clients. These clients understand different markup languages, HTML and Wireless Markup Language (WML), respectively, but your application must deliver content that is appropriate for both.

To accomplish this goal, you can write your application to first produce an XML document that represents the data it is sending to the client. Then the application can transform the XML document that represents the data into HTML or WML, depending on the client's browser type. Your application can determine the client browser type by examining the User-Agent request header of an HTTP request. Once the application knows the client browser type, it uses the appropriate XSLT style sheet to transform the document into the correct markup language. See the SnoopServlet example included in the examples/servlets directory of your WebLogic Server distribution for an example of how to access this type of header information.

This method of rendering the same XML document using different markup languages in respective client types helps concentrate the effort required to support multiple client types into the development of the appropriate XSLT style sheets. Additionally, it allows your application to adapt to other clients types easily, if necessary.

For additional information about XSLT, see Other XML Specifications and Information.

XML as a Message Format for Business-to-Business Communication

In a business-to-business (B2B) environment, Company A and Company B want to exchange information about e-commerce transactions in which both are involved. Company A is a major e-commerce site. Company B is a small affiliate that sells Company A's products to a niche group of customers. When Company B sends customers to Company A, Company B is compensated in two ways: it receives, from Company A, both money and information about other customers that make the same sort of purchases as those made by the customers referred by Company B. To exchange information, Company A and Company B must agree on a data format for information that is machine readable and that operates with systems from both companies easily. XML is the logical data format to use in this scenario, but selecting this format is only the first step. The companies must then agree on the format of the XML messages to be exchanged. Because Company A has a one-to-many relationship with its affiliates, Company A must define the format of the XML messages that will be exchanged.

To define the format of XML messages, or XML documents, Company A creates two document type definitions (DTDs): one that describes the information that A will provide about customers and one that describes the information that A wants to receive about a newly affiliated company. Company B must also create two DTDs: one to process the XML documents received from Company A and one to prepare an XML document in a format that can be processed by Company A.

3 Developing XML Applications with WebLogic Server

The following sections describe how to use the Java programming language and WebLogic Server to develop XML applications. It is assumed that you know how to use Java Servlets and Java Server Pages (JSPs) to write Java applications. For information about how to write servlet and JSP applications, see Developing Web Applications, Servlets, and JSPs for Oracle WebLogic Server.

Developing XML Applications: Main Steps

Parsing XML Documents

Generating New XML Documents

Transforming XML Documents

Developing XML Applications: Main Steps

Programmers using the WebLogic Server XML subsystem typically perform some or all of the following programming tasks when developing XML applications:

Parse an XML document.

The XML document can originate from a number of sources. For example, a programmer might develop a servlet to receive an XML document from a client, write an EJB to receive an XML document from a Servlet or another EJB, and so on. In each instance, the XML document may have to be parsed so that its data can be manipulated.

For more information on this task, refer to Parsing XML Documents.

Generate a new XML document.

After a servlet or EJB has received and parsed an XML document and possibly manipulated the data in some way, the Servlet or EJB might need to generate a new XML document to send back to the client or to pass on to another EJB.

For more information on this task, refer to Generating New XML Documents.

Transform XML data into another format.

After parsing an XML document or generating a new one, the Servlet or EJB may need to transform it into another format, such as HTML, WML, or plain text.

For more information on this task, refer to Using JAXP to Transform XML Data.

Parsing XML Documents

This section describes how to parse XML documents using JAXP in both DOM and SAX mode and how to parse XML documents from a servlet.

Note:

For detailed instructions on using the Streaming API for XML (StAX) to parse XML documents, see Chapter 4, "Using the Streaming API for XML (StAX)."

You use the Administration Console XML Registry to configure the following:

Per-document-type parsers, which supersede the default parser for the specified document type.

External entity resolution, or the process that an XML parser goes through when requested to find an external file in the course of parsing an XML document

For detailed information on how to use the Administration Console for these tasks, refer to Chapter 9, "Administering WebLogic Server XML."

Parsing XML Documents Using JAXP in SAX Mode

The following code example shows how to configure a SAX parser factory to create a validating parser. The example also shows how to register the MyHandler class with the parser. The MyHandler class can override any method of the DefaultHandler class to provide custom behavior for SAX parsing events or errors.

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

...
MyHandler handler = new MyHandler();
// MyHandler extends org.xml.sax.helpers.DefaultHandler.

  //Obtain an instance of SAXParserFactory.
  SAXParserFactory spf = SAXParserFactory.newInstance();
  //Specify a validating parser.
  spf.setValidating(true); // Requires loading the DTD.
  //Obtain an instance of a SAX parser from the factory.
  SAXParser sp = spf.newSAXParser();
  //Parse the documnt.
  sp.parse("http://server/file.xml", handler);
...

Note:

If you want to use a parser other than the default parser, you must use the WebLogic Server Administration Console to specify the parser in the XML Registry; otherwise the SaxParserFactory.newInstance method returns the default parser. For instructions about configuring WebLogic Server to use a parser other than the default parser, see Configuring a Parser or Transformer Other Than the Default.

Parsing XML Documents Using JAXP in DOM Mode

The following code example shows how to parse an XML document and create an org.w3c.dom.Document tree from a DocumentBuilder object:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

...
//Obtain an instance of DocumentBuilderFactory.
DocumentBuilderFactory dbf =
                 DocumentBuilderFactory.newInstance();
//Specify a validating parser.
dbf.setValidating(true); // Requires loading the DTD.
//Obtain an instance of a DocumentBuilder from the factory.
DocumentBuilder db = dbf.newDocumentBuilder();
//Parse the document.
Document doc = db.parse(inputFile);
...

Note:

If you want to use a parser other than the default parser, you must use the WebLogic Server Administration Console to specify it; otherwise the DocumentBuilderFactory.newInstance method returns the default parser. For instructions about configuring WebLogic Server to use a parser other than the default parser, see Configuring a Parser or Transformer Other Than the Default.

Parsing XML Documents in a Servlet

Support for the setAttribute and getAttribute methods was added to version 2.2 of the Java Servlet Specification. Attributes are objects associated with a request. The request object encapsulates all information from the client request. In the HTTP protocol, this information is transmitted from the client to the server by the HTTP headers and message body of the request.

With WebLogic Server, you can use the setAttribute and getAttribute methods to parse XML documents. Use the setAttribute method for SAX mode parsing and the getAttribute method for DOM mode parsing, as described in Using the org.xml.sax.DefaultHandler Attribute to Parse a Document and Using the org.w3c.dom.Document Attribute to Parse a Document.

Before you can use the setAttribute and getAttribute methods, however, you must configure a WebLogic Server servlet filter called weblogic.servlet.XMLParsingHelper (deployed by default on all WebLogic Server instances) as part of your Web application. Configure the servlet filter by adding the following elements to the web.xml deployment descriptor, located in the WEB-INF directory of your Web application:

<filter>
  <filter-name>XMLParsingHelper</filter-name>
  <filter-class>weblogic.servlet.XMLParsingHelper</filter-class>
</filter>

<filter-mapping>
  <filter-name>XMLParsingHelper</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
</filter-mapping>

For more information on servlet filters, see "Filters" in Developing Web Applications, Servlets, and JSPs for Oracle WebLogic Server.

Using the org.xml.sax.DefaultHandler Attribute to Parse a Document

The following code example shows how to use the setAttribute method:

import weblogic.servlet.XMLProcessingException;
import org.xml.sax.helpers.DefaultHandler;
...
public void doPost(HttpServletRequest request,
                             HttpServletResponse response)
   throws ServletException, IOException  {
   try {
      request.setAttribute("org.xml.sax.helpers.DefaultHandler",
                           new DefaultHandler());
    } catch(XMLProcessingException xpe) {
      System.out.println("Error in processing XML");
      xpe.printStackTrace();
      return;
    }
...

You can also use the org.xml.sax.HandlerBase attribute to parse an XML document, although it is deprecated:

request.setAttribute("org.xml.sax.HandlerBase",
                      new HandlerBase());

Note:

This code example shows a simple way to parse a document using SAX and the setAttribute method. This method of parsing a document is a WebLogic Server convenience feature, and it is not supported by other servlet vendors. Therefore, if you plan to run your application on other servlet platforms, do not use this feature.

Using the org.w3c.dom.Document Attribute to Parse a Document

The following code example shows how to use the getAttribute method.

import org.w3c.dom.Document;
import weblogic.servlet.XMLProcessingException;

...

public void doPost(HttpServletRequest request,
                            HttpServletResponse response)
throws ServletException, IOException  {

try {
   Document doc = request.getAttribute("org.w3c.dom.Document");
 } catch(XMLProcessingException xpe) {
   System.out.println("Error in processing XML");
   xpe.printStackTrace();
   return;
 }
...

Note:

This code example shows a simple way to parse a document using DOM and the getAttribute method. This method of parsing a document is a WebLogic Server convenience feature, and it is not supported by other servlet vendors. Therefore, if you plan to run your application on other servlet platforms, do not use this feature.

Validating and Non-Validating Parsers

As previously discussed, a well-formed document is one that is syntactically correct according to the rules outlined in the W3C Recommendation for XML 1.0. A valid document is one that follows the constraints specified by its DTD or schema.

A non-validating parser verifies that a document is well-formed, but does not verify that it is valid. To turn on validation while parsing a document (assuming you are using a validating parser), you must:

Set the SAXParserFactory.setValidating() method to true, as shown in the following example:

SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);

Ensure that the XML document you are parsing includes (either in-line or by reference) a DTD or a schema.

Handling Entity Resolution While Parsing an XML Document

This section provides general information about external entities; how they are identified and resolved by an XML parser; and the features provided by WebLogic Server to improve the performance of external entity resolution in your XML applications.

General Information About External Entities

External entities are chunks of text that are not literally part of an XML document, but are referenced inside the XML document. The actual text might reside anywhere - in another file on the same computer or even somewhere on the Web. While parsing a document, if the parser encounters an external entity reference, it fetches the referenced chunk of text, places the text into the XML document, then continues parsing. An example of an external entity is a DTD; rather than including the full text of the DTD in the XML document, the XML document has a reference to the DTD that is stored in a separate file.

There are two ways to identify an external entity: a system identifier and a public identifier. System identifiers use URIs to reference an external entity based on its location. Public identifiers use a publicly declared name to refer the information.

The following example shows how a public identifier is used to reference the DTD for the application.xml file that describes a Java EE application archive (*.ear file):

<!DOCTYPE application PUBLIC "-//Sun Microsystems,
Inc.//DTD J2EE Application 1.2//EN">

The following example shows a reference to an external DTD by a system identifier only:

<!DOCTYPE application SYSTEM "http://java.sun.com/j2ee/dtds/application_1_2.dtd">

Here is a reference that uses both the public and system identifier; note that the keyword SYSTEM is omitted:

<!DOCTYPE application
PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.2//EN"
"http://java.sun.com/j2ee/dtds/application_1_2.dtd">

Using the WebLogic Server Entity Resolution Features

Use the following WebLogic Server features to improve the performance of external entity resolution in your XML applications:

Permanently store a copy of an external entity on the computer that hosts the WebLogic Administration Server.

Specify that WebLogic Server automatically retrieve and cache an external entity that resides in an external repository that supports an HTTP interface, such as a URL. You can specify that WebLogic Server cache the entity either in memory or on disk and specify when the cached entry becomes stale, at which point WebLogic Server automatically updates the cached entry.

Using the retrieve-and-cache feature, you do not have to actually copy the external entity to the local computer. The XML application refers to the actual external entity only at specified time intervals, rather than each time the document is parsed, thus potentially greatly improving the performance of your application while also keeping as up to date with the latest external entity as desired.

You use the XML Registry to create entity resolution entries to identify where the external entry is located (locally or at a URL) and what the caching options are for entities on the Web. You identify the external entity entry using a system or public identifier. Then, in your XML document, when you reference this external entity, WebLogic Server fetches the local copy or the cached copy (whichever you have configured) when parsing the document.

For detailed information on creating external entity registries with the XML Registry, refer to External Entity Configuration Tasks.

Using Parsers Other Than the Default

If you use JAXP to parse your XML documents, the WebLogic Server XML Registry (which is configured through the Administration Console) offers the following options:

Accept the default parser as the server-wide parser.

Configure another parser of your choice (such as a different version of the Apache Xerces parser) as the server-wide parser.

Configure a parser for a particular XML document type, based on its system or public identifier, or its root element.

For instructions on how to use the XML Registry to configure parsing options, see XML Parser and Transformer Configuration Tasks.

Generating New XML Documents

This section describes how to generate XML documents from a DOM document tree and by using JSP.

Note:

For detailed instructions on using the Streaming API for XML (StAX) to generate XML documents, see Chapter 4, "Using the Streaming API for XML (StAX)."

Generating XML from a DOM Document Tree

You can use the javax.xml.transform.Transformer class to serialize a DOM object into an XML stream, as shown in the following example segment:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.*;

...

TransformerFactory trans_factory = TransformerFactory.newInstance();
Transformer xml_out = trans_factory.newTransformer();
Properties props = new Properties();
props.put("method", "xml");
xml_out.setOutputProperties(props);
xml_out.transform(new DOMSource(doc), new StreamResult(System.out));

In the example, the Transformer.transform() method does the work of converting a DOM object into an XML stream. The transform() method takes as input a javax.xml.transform.dom.DOMSource object, created from the DOM tree stored in the doc variable, and converts it into a javax.xml.transform.stream.StreamResult object and writes the resulting XML document to the standard output.

Generating XML Documents in a JSP

You typically use JSPs to generate HTML, but you can also use a JSP to generate an XML document.

Using JSPs to generate XML requires that you set the content type of the JSP page as follows:

<%@ page contentType="text/xml"%>
    ... XML document

The following code shows an example of how to use JSP to generate an XML document:

<?xml version="1.0">

<%@ page contentType="text/xml" import="java.text.DateFormat,java.util.Date" %>

<message>
  <text>
    Hello World.
  </text>
  <timestamp>
<%
out.print(DateFormat.getDateInstance().format(new Date()));
%>
  </timestamp>
</message>

For more information about using JSP to generate XML, see http://java.sun.com/products/jsp/html/JSPXML.html.

Transforming XML Documents

Transformation refers to converting an XML document (the source of the transformation) into another format, typically a different XML document, HTML, Wireless Markup Language (WML) (the result of the transformation.) This section describes how to transform XML documents using JAXP and from within a JSP using JSP tags.

Using JAXP to Transform XML Data

Version 1.2 of JAXP provides pluggable transformation, which means that you can use any JAXP-compliant transformer engine.

JAXP provides the following interfaces to transform XML data into a variety of formats:

javax.xml.transform

Contains the generic APIs for transforming documents. This package does not have any dependencies on SAX or DOM and makes the fewest possible assumptions about the format of the source and result.

javax.xml.transform.stream

Implements stream- and URI-specific transformation APIs. In particular, it defines the StreamSource and StreamResult classes that enable you to specify InputStreams and URLs as the source of a transformation and OutputStreams and URLs as the results, respectively.

javax.xml.transform.dom

Implements DOM-specific transformation APIs. In particular, it defines the DOMSource and DOMResult classes that enable you to specify a DOM tree as either the source or result, or both, of a transformation.

javax.xml.transform.sax

Implements SAX-specific transformation APIs. In particular, it defines the SAXSource and SAXResult classes that enable you to specify org.xml.sax.ContentHandler events as either the source or result, or both, of a transformation.

Transformation encompasses many possible combinations of inputs and outputs.

Example of Transforming an XML Document Using JAXP

The following example snippet shows how to use JAXP to transform myXMLdoc.xml into a different XML document using the mystylesheet.xsl stylesheet:

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;

Transformer trans;
TransformerFactory factory = TransformerFactory.newInstance();
String stylesheet = "file://stylesheets/mystylesheet.xsl";
String xml_doc = "file://xml_docs/myXMLdoc.xml";

trans = factory.newTransformer(new StreamSource(stylesheet));
trans.transform(new StreamSource(xml_doc),
                 new StreamResult(System.out));

For an example of how to transform a DOM document into an XML stream, see Using JAXP to Transform XML Data.

Using the JSP Tag to Transform XML Data

WebLogic Server provides a small JSP tag library for convenient access to an XSLT transformer from within a JSP. You can use this tag to transform XML documents into HTML, WML, and so on.

The JSP tag library consists of one main tag, x:xslt, and two subtags you can use within the x:xslt tag: x:stylesheet and x:xml.

Note:

The JSP tag library is provided for convenience only; the tag library is not required to access XSLT transformers from within a JSP.

XSLT JSP Tag Syntax

The XSLT JSP tag syntax is based on XML. A JSP tag consists of a start tag, an optional body, and a matching end tag. The start tag includes the element name and optional attributes.

The following syntax describes how to use the three XSLT JSP tags provided by WebLogic Server in a JSP. The attributes are optional, as are the subtags x:stylesheet and x:xml. The tables following the syntax describe the attributes of the x:xslt and x:stylesheet tags; the x:xml tag does not have any attributes.

<x:xslt  [xml="uri of XML file"]
         [media="media type to determine stylesheet"]
         [stylesheet="uri of stylesheet"]
    <x:xml>In-line XML goes here
    </x:xml>
    <x:stylesheet [media="media type to determine stylesheet"]
                  [uri="uri of stylesheet"]
    </x:stylesheet>
</x:xslt>

Table 3-1 describes the attributes of the x:xslt tag.

Table 3-1 x:xslt JSP Tag Attributes

x:xslt Tag Attribute
Required
Data Type
Description

xml

No

String

Specifies the location of the XML file that you want to transform. The location is relative to the document root of the Web application in which the tag is used.

media

No

String

Defines the document output type, such as HTML or WML, that determines which stylesheet to use when transforming the XML document.

This attribute can be used in conjunction with the media attribute of any enclosed x:stylesheet tags within the body of the x:xslt tag. The value of the media attribute of the x:xslt tag is compared to the value of the media attribute of any enclosed x:stylesheet tags. If the values are equal, then the stylesheet specified by the uri attribute of the x:stylesheet tag is applied to the XML document.

Note: It is an error to set both the media and stylesheet attributes within the same x:xslt tag.

stylesheet

No

String

Specifies the location of the stylesheet to use to transform the XML document. The location is relative to the document root of the Web application in which the tag is used.

Note: It is an error to set both the media and stylesheet attributes within the same x:xslt tag.

Table 3-2 describes the attributes of the x:stylesheet tag.

Table 3-2 x:stylesheet JSP Tag Attributes

x:stylesheet Tag Attribute
Required
Data Type
Description

media

No

String

Defines the document output type, such as HTML or WML, that determines which stylesheet to use when transforming the XML document.

Use this attribute in conjunction with the media attribute of enveloping x:xslt tag. The value of the media attribute of the x:xslt tag is compared to the value of the media attribute of the enclosed x:stylesheet tags. If the values are equal, then the stylesheet specified by the uri attribute of the x:stylesheet tag is applied to the XML document.

uri

No

String

Specifies the location of the stylesheet to use when the value of the media attribute matches the value of the media attribute of the enveloping x:xslt tag. The location is relative to the document root of the Web application in which the tag is used.

XSLT JSP Tag Usage

The x:xslt tag can be used with or without a body, and its attributes are optional. This section describes the rules that dictate how the tag behaves depending on whether you specify a body or one or more attributes.

If the x:xslt JSP tag is an empty tag (no body), the following statements apply:

If no attributes are set, the XML document is processed using the servlet path and the default media stylesheet. You specify the default media stylesheet in your XML file with the <?xml-stylesheet> processing instruction; the default stylesheet is the one that does not have a media attribute.

This type of processing allows you to register the JSP page that contains the tag extension as a file servlet that performs XSLT processing.

If only the media attribute is set, the XML document is processed using the servlet path and the specified media type. The value of the media type attribute of the x:xslt tag is compared to the value of the media attribute of any <?xml-stylesheet> processing instructions in your XML document; if any match then the corresponding stylesheet is applied. If none match then the default media stylesheet is used. The media type attribute is used to define the document output type (for example, XML, HTML, postscript, or WML). This feature enables you to organize stylesheets by document output type.

If only the xml attribute is set, the specified XML document is processed using the default media stylesheet.

If the media and xml attributes are set, the specified XML document is processed using the specified media type.

If the stylesheet attribute is defined, the XML document is processed using the specified stylesheet.

Note:

It is an error to set both the media and stylesheet attributes within the same x:xslt tag.

An XSLT JSP tag that has a body may contain <x:xml> tags and/or <x:stylesheet> tags. The following statements apply:

The <x:xml> tag allows you specify an XML document for inline processing. This tag has no attributes.

The <x:stylesheet> tag, when used without any attributes, allows you specify the default stylesheet inline.

Use the uri attribute of the <x:stylesheet> tag to specify the location of the default stylesheet.

If you want to specify different stylesheets for different media types, you can use multiple <x:stylesheet> tags with different values for the media attribute. You can specify a stylesheet for each media type in the body of the tag, or specify the location of the stylesheet with the uri attribute.

Transforming XML Documents Using an XSLT JSP Tag

To use an XSLT JSP tag to transform XML documents, perform the following steps:

Open the xmlx.zip file in the WL_HOME\server\ext directory; extract the xmlx-tags.jar file; and put it in the /lib directory of your Web application, where WL_HOME is the top-level directory in which you installed the WebLogic Server distribution.

Add a <taglib> entry to the web.xml file. For example:

<taglib>
  <taglib-uri>xmlx.tld</taglib-uri>
  <taglib-location>/WEB-INF/lib/xmlx-tags.jar</taglib-location>
</taglib>

To use the tags, add the following line to your JSP page:

<%@ taglib uri="xmlx.tld" prefix="x"%>

Configure the transformer. The following procedure shows a generic way to configure the transformer:

Enter the following code line to create an xslt.jsp file:

<%@ taglib uri="xmlx.tld" prefix="x"%><x:xslt/>

Register the xslt.jsp file in your web.xml file, as follows:

<servlet>
   <servlet-name>myxsltinterceptor</servlet-name>
   <jsp-file>xslt.jsp</jsp-file>
</servlet>
<servlet-mapping>
   <servlet-name>myxsltinterceptor</servlet-name>
   <url-pattern>/xslt/*</url-pattern>
</servlet-mapping>

Put your XML, DTD, and XSL documents or servlets in your Web application.

Add an xslt prefix to the pathname for the XML document (for example, change docs/fred.xml to xslt/docs/fred.xml) and then access the document. Because of the <url-pattern> entry in the web.xml file, WebLogic Server automatically runs the XSLT transformer on the XML document and sets the default stylesheet in the document.

To define media type, add code to the JSP to determine the media type for the XML document and the content type for the output.

Pass the media type into the xslt tag and then set the content type of the response object.

Note:

The other forms of the XSLT JSP tag are used when stylesheets are not specified in the XML document or your XML stylesheet can be generated inline.

Example of Using the XSLT JSP Tag in a JSP

The following snippet of code from a JSP shows how to use the XSLT JSP tag to transform XML into HTML or WML, depending on the type of client that is requesting the JSP. If the client is a browser, the JSP returns HTML; if the client is a wireless device, the JSP returns WML.

First the JSP uses the getHeader() method of the HttpServletRequest object to determine the type of client that is requesting the JSP and sets the myMedia variable to wml or html appropriately. If the JSP set the myMedia variable to html, then it applies the html.xsl stylesheet to the XML document contained in the content variable. Similarly, if the JSP set the myMedia variable to wml, then it applies the wml.xsl stylesheet.

<%
   String clientType = request.getHeader("User-Agent");
   // default to WML client
   String myMedia = "wml";

   // if client is an HTML browser

   if (clientType.indexOf("Mozilla") != -1) {
      myMedia = "http"
   }
%>

<x:xslt media="<%=myMedia%>">
  <x:xml><%=content%></x:xml>
  <x:stylesheet media="html" uri="html.xsl"/>
  <x:stylesheet media="wml"  uri="wml.xsl"/>
</x:xslt>

Using Transformers Other Than the Default Transformer

The WebLogic Server XML Registry (which you configure using the Administration Console) offers the following options:

Accept the default transformer as the server-wide transformer.

Configure a transformer other than the default transformer as the server-wide transformer. The transformer must be JAXP-compliant.

For instructions on how to use the XML Registry to configure transforming options, see Configuring a Parser or Transformer Other Than the Default.

4 Using the Streaming API for XML (StAX)

The following sections describe how to use the Streaming API for XML to parse and generate XML documents:

Overview of the Streaming API for XML

Parsing XML With the XMLStreamReader Interface: Typical Steps

Generating XML Using the XMLStreamWriter Interface: Typical Steps

Properties Defined for the XMLInputFactory Interface

Properties Defined for the XMLOutputFactory Interface

Overview of the Streaming API for XML

The Streaming API for XML (StAX), specified by JSR-173 at http://www.jcp.org/en/jsr/detail?id=173 of Java Community Process, provides an easy and intuitive means of parsing and generating XML documents. It is similar to the SAX API, but enables a procedural, stream-based handling of XML documents rather than requiring you to write SAX event handlers, which can get complicated when you work with complex XML documents. In other words, StAX gives you more control over parsing than the SAX.

When a program parses an XML document using SAX, the program must create event listeners that listen to parsing events as they occur; the program must react to events rather than ask for a specific event. By contrast, when you use StAX, you can methodically step through an XML document, ask for certain types of events (such as the start of an element), iterate over the attributes of an element, skip ahead in the document, stop processing at any time, get sub-elements of a particular element, and filter out elements as desired. Because you are asking for events rather than reacting to them, using the StAX is often referred to as pull parsing.

StAX includes two APIs, the cursor API and the event-iterator API, either of which can be used for reading and writing XML. The following sections describe each API and their particular strengths.

Description of the Cursor API

The basic function of the cursor API is to allow programmers to parse and generate XML as easily and efficiently as possible. Of the two APIs in StAX, this is the one that most programmers would use.

The cursor API iterates over a set of events, such as start elements, comments, and attributes, although the events may be unrealized. The cursor API has two main interfaces: XMLStreamReader for parsing XML and XMLStreamWriter for generating XML.

The XMLStreamReader Interface

The cursor API uses the XMLStreamReader interface to move a virtual cursor over an XML document and allow access to the data and underlying state through method calls such as hasNext(), next(), getEventType(), and getText(). The XMLStreamReader interface allows only forward, read-only access to the XML.

Use the XMLInputFactory class to create a new instance of the XMLStreamReader. You can set a variety of properties when you get a new reader; for details, see Properties Defined for the XMLInputFactory Interface.

When you use the next() method of the XMLStreamReader interface to parse XML, the reader gets the next parsing event and returns an integer that identifies the type of event just read. Parsing events correspond to sections of an XML document, such as the XML declaration, start and end element tags, character data, white space, comments, and processing instructions. The XMLStreamConstant interface specifies the event to which the integer returned by the next() method corresponds. You can also use the getEventType() method of XMLStreamReader to determine the event type.

The XMLStreamReader interface has numerous methods for getting at the specific data in the XML document. Some of these methods include:

getLocalName()—Returns the local name of the current event.

getPrefix()—Returns the prefix of the current event.

getAttributeXXX()—Set of methods that return information about the current attribute event.

getNamespaceXXX()—Set of methods that return information about the current namespace event.

getTextXXX()—Set of methods that return information about the current text event.

getPIData()—Returns the data section of the current processing instruction event.

Only certain methods are valid for each event type; the StAX processor throws a java.lang.IllegalStateException if you try to call a method on an invalid event type. For example, it is an error to try to call the getAttributeXXX() methods on a namespace event. See the StAX specification, at http://www.jcp.org/en/jsr/detail?id=173, for the complete list of events and their valid XMLStreamReader methods.

The XMLStreamWriter Interface

The cursor API uses the XMLStreamWriter interface to specify how to generate XML.

Use the XMLOutputFactory class to create a new instance of the XMLStreamWriter. You can set a property for repairing namespaces and prefixes when you get a new writer; for details, see Properties Defined for the XMLOutputFactory Interface.

The XMLStreamWriter interface defines a set of writeXXX() methods for writing standard parts of an XML document, such as:

writeStartElement()

writeEndDocument()

writeAttribute()

writeNamespace()

writeCData()

Each part of an XML document, including the attributes and the namespaces, must be explicitly written using these methods.

Use the flush() method to write any cached data to the output and the close() method to close the writer and free up any resources.

The XMLStreamWriter, when generating XML, does not check that the generated document is well-formed; it is the programmer's responsibility to create a well-formed XML document. To print the special characters &, <, and >, use the writeCharacters() method.

Description of the Event Iterator API

The event iterator API is a layer on top of the cursor API. It is easy to extend and facilitates pipelining. Pipelining refers to multiple XML-to-XML transformations. By using the event iterator API, programmers do not have to deserialize and serialize the XML at each stage of the pipeline; rather, only at each end of the pipeline and use the API methods such as nextEvent() to communicate at the middle stages. The event iterator API has two main interfaces: XMLEventReader for parsing XML and XMLEventWriter for generating XML.

Because the cursor API is the most commonly used API in StAX, this section does not describe in detail how to use the event iterator API, other than showing an example. For details about using this API, see the StAX specification http://www.jcp.org/en/jsr/detail?id=173.

The following example shows a simple program that uses the XMLEventReader interface of StAX to parse an XML document. The program takes a single parameter, an XML file, and uses it to create an XMLEventReader object. The program then uses the reader to iterate over and print the stream of events.

package examples.event;

import java.io.FileReader;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
import javax.xml.stream.util.*;
import javax.xml.namespace.QName;

/**
 * A simple example to iterate over events
 *
 * @author Copyright (c) 2002 by BEA Systems. All Rights Reserved.
 */

public class Parse {
  private static String filename = null;
  private static void printUsage() {
    System.out.println("usage: java examples.event.Parse <xmlfile>");
  }

  public static void main(String[] args) throws Exception {
    try {
      filename = args[0];
    } catch (ArrayIndexOutOfBoundsException aioobe){
      printUsage();
      System.exit(0);
    }

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader r =
      factory.createXMLEventReader(new FileReader(filename));
    while(r.hasNext()) {
      XMLEvent e = r.nextEvent();
      System.out.println("ID:"+e.hashCode()+"["+e+"]");
    }
  }
}

Main Interfaces and Classes of StAX

Table 4-1 describes the main interfaces and classes of the Streaming API for XML

Table 4-1 Main Interfaces and Classes of the Streaming API for XML

Interface or Class
Used in Cursor or Event Iterator API?
Description

XMLInputFactory class

Both

Factory class used to create an XMLStreamReader or XMLEventReader instance.

XMLOutputFactory class

Both

Factory class used to create an XMLStreamWriter or XMLEventWriter instance.

XMLEventFactory class

Event Iterator

Factory class used to create an XMLEvent instance.

XMLStreamReader interface

Cursor

Interface used to parse an XML document. Enables you to peek at the next event, get the next event, and check for more events.

XMLStreamWriter interface

Cursor

Interface used to generate an XML document. It provides a set of writeXXX() methods for generating specific parts of an XML document, such as start elements, attributes, and so on.

XMLEventReader interface

Event Iterator

Interface used to parse XML events. It enables you to peek at the next event, get the next event, and check for more events.

XMLEventWriter interface

Event Iterator

Interface used to generate XML. It uses the add() method to add XMLEvents to the output stream.

XMLEvent

Event Iterator

Base interface for handling events. All specific XML events extend from XMLEvent, such as StartElement, Attribute, and so on.

XMLStreamException exception

Both

Base exception for unexpected processing errors, such as lack of well-formed XML document structure.

Parsing XML With the XMLStreamReader Interface: Typical Steps

The following procedure describes the typical steps for using the XMLStreamReader interface of the StAX cursor API to parse an XML document. The procedure uses the example from Example of Parsing XML Using StAX in its description.

Import the javax.xml.stream.* classes.

Use the XMLInputFactory.newInstance() method to instantiate an XMLInputFactory, as shown in the following code excerpt:

XMLInputFactory xmlif = XMLInputFactory.newInstance();

See Properties Defined for the XMLInputFactory Interface for the list of properties you can set.

Use the XMLInputFactory.createXMLStreamReader() method to instantiate an XMLStreamReader object based on an XML document.

See Getting the XMLStreamReader Object for more details.

Parse the XML document, using the hasNext() and next() methods to step through the XML events, as shown in the following code excerpt:

while(xmlr.hasNext()){
      printEvent(xmlr);
      xmlr.next();

In the example, xmlr is the XMLStreamReader instance and the local printEvent() method (not part of the StAX API) determines the specific event type, as described in the next step.

While parsing the XML document, determine the current specific event type and take appropriate action. Event types include the start and end of an XML document, the start and end of an XML element, comments, entity references, and so on.

See Determining the Specific XML Event Type.

If the current event type is a start element or end element, optionally get its attributes.

See Getting the Attributes of an Element.

If the current event type is a start or end element, optionally get its namespaces.

See Getting the Namespaces of an Element.

If the current event type includes text data, such as a CDATA or comment, optionally get the actual data.

See Getting Text Data.

Optionally, get location information, such as the line number or column number, of the current event.

See Getting Location Information.

Close the stream.

See Closing the Input Stream.

Example of Parsing XML Using StAX

The following example shows a simple program that uses the XMLStreamReader interface of StAX to parse an XML document.

The program takes a single parameter, an XML file, and uses it to create an XMLStreamReader object. The program then uses the reader to iterate over the stream of events, determining the type of each event, such as the start of an XML element, the list of attributes of an element, a processing instruction, and so on. The program prints out information about these events, using internal methods to print out the list of attributes and namespaces when appropriate.

The code in bold is described in later sections.

package examples.basic;

import java.io.FileReader;
import java.util.Iterator;
import javax.xml.stream.*;
import javax.xml.namespace.QName;

/**
 * This is a simple parsing example that illustrates
 * the XMLStreamReader class.
 *
 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
 */

public class Parse {
  private static String filename = null;
  private static void printUsage() {
    System.out.println("usage: java examples.basic.Parse <xmlfile>");
  }

  public static void main(String[] args) throws Exception {
    try {
      filename = args[0];
    } catch (ArrayIndexOutOfBoundsException aioobe){
      printUsage();
      System.exit(0);
    }

    //
    // Get an input factory
    //
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    System.out.println("FACTORY: " + xmlif);

    //
    // Instantiate a reader
    //
    XMLStreamReader xmlr = xmlif.createXMLStreamReader(new FileReader(filename));
    System.out.println("READER:  " + xmlr + "\n");

    //
    // Parse the XML
    //
    while(xmlr.hasNext()){
      printEvent(xmlr);
      xmlr.next();
    }

    //
    // Close the reader
    //
    xmlr.close();

  }

  private static void printEvent(XMLStreamReader xmlr) {

    System.out.print("EVENT:["+xmlr.getLocation().getLineNumber()+"]["+
                     xmlr.getLocation().getColumnNumber()+"] ");

    System.out.print(" [");
    switch (xmlr.getEventType()) {

    case XMLStreamConstants.START_ELEMENT:
      System.out.print("<");
      printName(xmlr);
      printNamespaces(xmlr);
      printAttributes(xmlr);
      System.out.print(">");
      break;
    case XMLStreamConstants.END_ELEMENT:
      System.out.print("</");
      printName(xmlr);
      System.out.print(">");
      break;
    case XMLStreamConstants.SPACE:
    case XMLStreamConstants.CHARACTERS:
      int start = xmlr.getTextStart();
      int length = xmlr.getTextLength();
      System.out.print(new String(xmlr.getTextCharacters(),
                                  start,
                                  length));
      break;

    case XMLStreamConstants.PROCESSING_INSTRUCTION:
      System.out.print("<?");
      if (xmlr.hasText())
        System.out.print(xmlr.getText());
      System.out.print("?>");
      break;

    case XMLStreamConstants.CDATA:

5 Using Advanced XML APIs

The following sections provide information about using advanced XML APIs:

Using the Java API for XML Registries (JAXR) API

Using the WebLogic XPath API

Using the Java API for XML Registries (JAXR) API

The Java API for XML Registries (JAXR) API, at http://java.sun.com/webservices/jaxr/, provides a uniform and standard Java API for accessing different kinds of registries, in particular XML registries used in Web Service applications.

At an abstract level, a registry is a neutral third party that helps facilitate the collaboration between two parties that are engaged in a partnership. The registry is available to the two parties as a shared resource, typically in the form of a Web-based resource. A registry is a key component in any Web Services architecture because it provides the ability for parties to publish, discover, and use Web Services.

Registries provide the following functionality:

Electronic Yellow Pages

A registry can provide an independent online information exchange service that allows Web Service providers to advertise their product and Web Service consumers to discover these products.

The registry can classify these Web Services in arbitrary and flexible ways, such as the industry it belongs to, its geographic location, the product it sells, and so on.

Database of Relatively Static Data

A registry stores data and meta-data, similar to a database. The type of data it stores include:

Collaborative business process descriptions that describe in XML format a specific business protocol.

Parties in a collaborative business process.

XML Schemas that describe the XML documents exchanged during a collaborative business process.

Essentially, the registry allows applications to store relatively static data reliably and to share it easily with other applications.

A registry also provides a way to exchange dynamic content between parties, such as price changes, discounts, promotions, and so on.

WebLogic Server provides a full implementation of the JAXR specification. Using the JAXR API, you can create JAXR clients that access a registry, or you can create a registry yourself.

For more information on using the JAXR API, see the Java Web Services http://java.sun.com/webservices/jaxr/ Web site.

Using the WebLogic XPath API

The WebLogic XPath API contains all of the classes required to perform XPath matching against a document represented as a DOM, an XMLInputStream, or an XMLOutputStream. Use the API if you want to identify a subset of XML elements within an XML document that conform to a given pattern.

For additional API reference information about the WebLogic XPath API, see "weblogic.xml.xpath" in the Oracle WebLogic Server API Reference and http://java.sun.com/webservices/jaxr/ Javadoc.

Using the DOMXPath Class

This section describes how to use the DOMXPath class of the WebLogic XPath API to perform XPath matching against an XML document represented as a DOM. The section first provides an example and then a description of the main steps used in the example.

Example of Using the DOMXPath Class

The sample Java program at the end of this section uses the following XML document in its matching:

<?xml version='1.0' encoding='us-ascii'?>

<!-- "Purchaseorder". -->

<purchaseorder
    department="Sales"
    date="01-11-2001"
    raisedby="Pikachu"
    >
    <item
        ID="101">
        <title>Laptop</title>
        <quantity>5</quantity>
        <make>Dell</make>
    </item>
    <item
        ID="102">
        <title>Desktop</title>
        <quantity>15</quantity>
        <make>Dell</make>
    </item>
    <item
        ID="103">
        <title>Office Software</title>
        <quantity>10</quantity>
        <make>Microsoft</make>
    </item>
</purchaseorder>

The Java code example is as follows:

package examples.xml.xpath;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import weblogic.xml.xpath.DOMXPath;
import weblogic.xml.xpath.XPathException;
/**
 * This class provides a simple example of how to use the DOMXPath
 * API.
 *
 * @author Copyright (c) 2002 by BEA Systems, Inc. All Rights Reserved.
 */

public abstract class DOMXPathExample {

  public static void main(String[] ignored)

    throws XPathException, ParserConfigurationException,

           SAXException, IOException

  {

    // create a dom representation of the document

    String file = "purchaseorder.xml";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true); // doesn't matter for this example

    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse(file);

    // create some instances of DOMXPath to evaluate against the

    // document.

    DOMXPath totalItems = // count number of items

      new DOMXPath("count(purchaseorder/item)");

    DOMXPath atLeast10 =  // titles of items with quantity >= 10

      new DOMXPath("purchaseorder/item[quantity >= 10]/title");

    // evaluate them against the document

    double count = totalItems.evaluateAsNumber(doc);

    Set nodeset = atLeast10.evaluateAsNodeset(doc);

    // output results

    System.out.println(file+" contains "+count+" total items.");

    System.out.println("The following items have quantity >= 10:");

    if (nodeset != null) {

      Iterator i = nodeset.iterator();

      while(i.hasNext()) {

        Node node = (Node)i.next();

        System.out.println("  "+node.getNodeName()+

                           ": "+node.getFirstChild().getNodeValue());

      }

    }

    // note that at this point we are free to continue using evaluate

    // atLeast10 and totalItems against other documents

  }

}

Main Steps When Using the DOMXPath Class

The following procedure describes the main steps to use the DOMXPath class to perform XPath matching against an XML document represented as a DOM:

Create an org.w3c.dom.Document object from an XML document, as shown in the following code excerpt:

String file = "purchaseorder.xml";
DocumentBuilderFactory factory =
   DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);

Create a DOMXPath object to represent the XPath expression you want to evaluate against the DOM.

The following example shows an XPath expression that counts the items in a purchase order:

 DOMXPath totalItems =
      new DOMXPath("count(purchaseorder/item)");

The following example shows an XPath expression that returns the titles of items whose quantity is greater or equal to 10:

 DOMXPath atLeast10 =
      new DOMXPath("purchaseorder/item[quantity >= 10]/title");

Evaluate the XPath expression using one of the DOMXPath.evaluateAsXXX() methods, where XXX refers to the data type of the returned data, such as Boolean, Nodeset, Number, or String.

The following example shows how to use the evaluateAsNumber() method to evaluate the totalItems XPath expression:

double count = totalItems.evaluateAsNumber(doc);
System.out.println(file+" contains "+count+" total items.");

The following example shows how to use the evaluateAsNodeset() method to return a Set of org.w3c.dom.Nodes which you can iterate through in the standard way:

 Set nodeset = atLeast10.evaluateAsNodeset(doc);

System.out.println("The following items have quantity >= 10:");
  if (nodeset != null) {
     Iterator i = nodeset.iterator();
     while(i.hasNext()) {
       Node node = (Node)i.next();
       System.out.println("  "+node.getNodeName()+
                          ": "+node.getFirstChild().getNodeValue());
     }
  }

For additional API reference information about the WebLogic XPath API, see "weblogic.xml.xpath" in the Oracle WebLogic Server API Reference.

Using the StreamXPath Class

The example in this section shows how to use the StreamXPath class of the WebLogic XPath API to perform XPath matching against an XMLInputStream. The section first provides an example and then a description of the main steps used in the example. Although the example shows how to match only against an XMLInputStream, you can use similar code to match against an XMLOutputStream.

Example of Using the StreamXPath Class

The sample Java program at the end of this section uses the following XML document in its matching:

<?xml version='1.0' encoding='us-ascii'?>

<!-- "Stock Quotes". -->

<stock_quotes>
  <stock_quote symbol='BEAS'>
    <when>
      <date>01/27/2001</date>
      <time>3:40PM</time>
    </when>
    <price type="ask"     value="65.1875"/>
    <price type="open"    value="64.00"/>
    <price type="dayhigh" value="66.6875"/>
    <price type="daylow"  value="64.75"/>
    <change>+2.1875</change>
    <volume>7050200</volume>
  </stock_quote>
  <stock_quote symbol='MSFT'>
    <when>
      <date>01/27/2001</date>
      <time>3:40PM</time>
    </when>
    <price type="ask" value="55.6875"/>
    <price type="open"    value="50.25"/>
    <price type="dayhigh" value="56"/>
    <price type="daylow"  value="52.9375"/>
    <change>+5.25</change>
    <volume>64282200</volume>
  </stock_quote>
</stock_quotes>

The Java code for the example is as follows:

package examples.xml.xpath;

import java.io.File;
import weblogic.xml.stream.Attribute;
import weblogic.xml.stream.StartElement;
import weblogic.xml.stream.XMLEvent;
import weblogic.xml.stream.XMLInputStream;
import weblogic.xml.stream.XMLInputStreamFactory;
import weblogic.xml.stream.XMLStreamException;
import weblogic.xml.xpath.StreamXPath;
import weblogic.xml.xpath.XPathException;
import weblogic.xml.xpath.XPathStreamFactory;
import weblogic.xml.xpath.XPathStreamObserver;

/**
 * This class provides a simple example of how to use the StreamXPath
 * API.
 *
 * @author Copyright (c) 2002 by BEA Systems, Inc. All Rights Reserved.
 */

public abstract class StreamXPathExample {
  public static void main(String[] ignored)
    throws XPathException, XMLStreamException
  {
    // Create instances of StreamXPath for two xpaths we want to match
    // against this tream.

    StreamXPath symbols =
      new StreamXPath("stock_quotes/stock_quote");
    StreamXPath openingPrices =
      new StreamXPath("stock_quotes/stock_quote/price[@type='open']");

    // Create an XPathStreamFactory.

    XPathStreamFactory factory = new XPathStreamFactory();

    // Create and install two XPathStreamObservers.  In this case, we
    // just use to anonymous classes to print a message when a
    // callback is received.  Note that a given observer can observe
    // more than one xpath, and a given xpath can be observed by
    // mutliple observers.

    factory.install(symbols, new XPathStreamObserver () {
      public void observe(XMLEvent event) {
        System.out.println("Matched a quote: "+event);
      }

      public void observeAttribute(StartElement e, Attribute a) {} //ignore

      public void observeNamespace(StartElement e, Attribute a) {} //ignore

    });

    // Note that we get matches for both a start and an end elements,
    // even in the case of <price/> which is an empty element - this
    // is the behavior of the underlying streaming parser.
    factory.install(openingPrices, new XPathStreamObserver () {
      public void observe(XMLEvent event) {
        System.out.println("Matched an opening price: "+event);
      }
      public void observeAttribute(StartElement e, Attribute a) {} //ignore
      public void observeNamespace(StartElement e, Attribute a) {} //ignore
    });
    // get an XMLInputStream on the document
    String file = "stocks.xml";
    XMLInputStream sourceStream = XMLInputStreamFactory.newInstance().
      newInputStream(new File(file));
    // use the factory to create an XMLInputStream that will do xpath
    // matching against the source stream
    XMLInputStream matchingStream = factory.createStream(sourceStream);
    // now iterate through the stream
    System.out.println("Matching against xml stream from "+file);
    while(matchingStream.hasNext()) {
      // we don't do anything with the events in our example - the
      // XPathStreamObserver instances that we installed in the
      // factory will get callbacks for appropriate events
      XMLEvent event = matchingStream.next();
    }
  }
}

Main Steps When Using the StreamXPath Class

The following procedure describes the main steps to use the StreamXPath class to perform XPath matching against an XML document represented as an XMLInputStream:

Create a StreamXPath object to represent the XPath expression you want to evaluate against the XMLInputStream.

StreamXPath symbols =
   new StreamXPath("stock_quotes/stock_quote");

The following example shows an XPath expression that matches stock quotes using their opening price:

StreamXPath openingPrices = new   StreamXPath("stock_quotes/stock_quote/price[@type='open']");

Create an XPathStreamFactory. Use this factory class to specify the set of StreamXPath objects that you want to evaluate against an XMLInputStream and to create observers (using the XPathStreamObserver interface) used to register a callback whenever an XPath match occurs. The following example shows how to create the XPathStreamFactory:

XPathStreamFactory factory = new XPathStreamFactory();

Create and install the observers using the XPathStreamFactory.install() method, specifying the XPath expression with the first StreamXPath parameter, and an observer with the second XPathStreamObserver parameter. The following example shows how to use an anonymous class to implement the XPathStreamObserver interface. The implementation of the observe() method simply prints a message when a callback is received. In the example, the observeAttribute() and observeNamespace() methods do nothing.

factory.install(symbols, new XPathStreamObserver () {
  public void observe(XMLEvent event) {
    System.out.println("Matched a quote: "+event);
  }
  public void observeAttribute(StartElement e, Attribute a) {}
  public void observeNamespace(StartElement e, Attribute a) {}
 }
);

Create an XMLInputStream from an XML document:

String file = "stocks.xml";

XMLInputStream sourceStream =
    XMLInputStreamFactory.newInstance().newInputStream(new File(file));

Use the createStream() method of the XPathStreamFactory to create a new XMLInputStream that will perform XPath matching against the original XMLInputStream:

 XMLInputStream matchingStream =
    factory.createStream(sourceStream);

Iterate over the new XMLInputStream. During the iteration, if an XPath match occurs, the registered observer is notified:

while(matchingStream.hasNext()) {
  XMLEvent event = matchingStream.next();
}

For additional API reference information about the WebLogic XPath API, see "weblogic.xml.xpath" in the Oracle WebLogic Server API Reference.

6 XML Programming Best Practices

The following sections discuss best programming practices when creating Java applications that process XML data:

When to Use the DOM, SAX, and StAX APIs

Increasing Performance of XML Validation

When to Use XML Schemas or DTDs

Configuring External Entity Resolution for Maximum Performance

Using SAX InputSources

Improving Performance of Transformations

When to Use the DOM, SAX, and StAX APIs

You can parse an XML document with the DOM, SAX, or StAX APIs. This section describes the pros and cons of each API.

The DOM API is good for small documents, or those that contain under a thousand elements. Because DOM constructs a tree of your XML data, it is ideal for editing the structure of your XML document by adding or deleting elements.

The DOM API parses the entire XML document and converts it into a DOM tree before you can begin processing it. This cost might be beneficial if you know that you need to access the entire document. If you occasionally need to access only part of the XML document, the cost could decrease the performance of your application with no added benefit. In this case the SAX or StAX API is preferable.

The SAX API is the most lightweight of the APIs. It is ideal for parsing shallow documents (documents that do not contain much nesting of elements) with unique element names. SAX uses a callback structure; this means that programmers handle parsing events as the API is reading an XML document, which is a relatively efficient and quick way to parse.

However, the callback nature of SAX also means that it is not the best API to use if you want to modify the structure of your XML data. Additionally, programming your application to handle callbacks is not always straight-forward and intuitive.

The StAX API is based on SAX, so all the reasons for using SAX also apply to the StAX API. In addition, the StAX API is more intuitive to use than SAX, because programmers ask for events rather than react to them as they happen. The StAX API is also best if you plan to pass the entire XML document as a parameter; it is easier to pass an input stream than it is to pass SAX events. Finally, the StAX API was designed to be used when binding XML data to Java objects.

Increasing Performance of XML Validation

If the performance of your XML application decreases due to a parser validation issue, and you need to validate your XML documents, you might improve the performance of your application by writing your own customized code that validates the data as it is being received or parsed, rather than using the setValidating() method of the DocumentBuilderFactory or SaxParserFactory.

When you turn on validation while parsing an XML document with SAX or DOM, the parser might do more validation of the document than you really need, thus decreasing the overall performance of the application. Instead, consider choosing certain points during the parsing of the document when you want to check that the XML document is valid, and add your own Java code at those points.

For example, assume you are writing an application that uses the WebLogic XML Streaming API to processes an XML purchase order. Because you know that the first element of the document should be <purchase_order>, you can quickly verify that the document appears to be valid by pulling the first element off the stream and checking its name. This check does not ensure that the entire XML document is valid, of course, but you can continue checking for known elements as you pull elements from the stream. These quick checks are much faster than using the standard setValidating() methods.

When to Use XML Schemas or DTDs

There are two ways to describe the structure of an XML document: DTDs and XML Schemas.

The current trend is to use Schemas to describe XML documents. Schemas are much more expressive than DTDs because the set of available data types to describe XML elements is much richer and you can describe more specifically what is valid in an XML document. In addition, you can only use Schemas, and not DTDs, in SOAP messages. Because SOAP is the main messaging protocol used in Web services, consider using Schemas to describe any XML documents that might be used as either input or output parameters to Web services.

Still, DTDs have a few advantages. DTDs are more widely supported than Schemas, although that is changing rapidly. Because DTDs are less expressive than Schemas, they are easier to write and manage.

However, Oracle recommends that you use Schemas to describe your XML documents.

Configuring External Entity Resolution for Maximum Performance

Oracle highly recommends you store external entities locally whenever possible rather than always retrieving the entity over the network. Storage improves the performance of your applications because it is much faster to look up an entity on the same machine as WebLogic Server than it is to look it up over a network connection.

For detailed information on configuring external entity resolution for WebLogic Server, see External Entity Configuration Tasks.

Using SAX InputSources

When you use the SAX API to parse an XML document, you first create an InputSource object from the XML document and then pass the InputSource object to the parse() method. You can create the InputSource object from either a java.io.InputStream or java.io.Reader object based on your XML data.

Oracle recommends that you create an InputSource from a java.io.InputStream object whenever possible. When passed an InputStream object, the SAX parser auto-detects the character encoding of the XML data and automatically instantiates an InputStreamReader object for you, using the correct character encoding. In other words, the parser does all the character encoding work for you, which is more likely to be error-free at runtime than if you decide to specify the character encoding yourself.

Improving Performance of Transformations

XSLT is a language for transforming an XML document into a different format, such as another XML document, HTML, WML, and so on. To use XSLT, you create a stylesheet that defines how each element in the input XML document should be transformed in the output document.

Although XSLT is a powerful language, creating stylesheets for complex transformations can be very complicated. In addition, the actual transformation requires a lot of resources and might decrease the performance of your application.

Therefore, if your transformations are complex, consider writing your own transformation code in your application rather than using XSLT stylesheets. Also consider using the DOM API. First parse the XML document, manipulate the resulting DOM tree as needed, then write out the new document, using custom Java code to transform it into its final format.

7 XML Programming Techniques

The following sections provide information about specific XML programming techniques for developing a Java EE application that processes XML data:

Transmitting XML Data Between A Java Client and WebLogic Server

Handling XML Documents in a JMS Application

Accessing External Entities That Do Not Have an HTTP Interface

Transmitting XML Data Between A Java Client and WebLogic Server

In a typical Java EE application, a client application sends XML data to a servlet or a JSP that processes the XML data. The servlet or JSP then either sends the data on to another Java EE component, such as a JMS destination or an EJB, or sends the processed XML data back to the client in the form of another XML document.

To send XML data from a Java client to a WebLogic Server-hosted servlet or JSP which then returns the data to the client, use the java.net.URLConnection class. This class represents the communication link between an application and an URL, which in this case is the URL that invokes the servlet or JSP. Instances of the URLConnection class send the XML document using the HTTP POST method.

The following Java client program from the WebLogic XML examples shows how to transmit XML data between the program and a JSP:

import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
  public static void main(String[] args) throws Exception {
    if (args.length < 2) {
      System.out.println("Usage:  java examples.xml.Client URL Filename");
    }
    else {
      try {
        URL url = new URL(args[0]);
        String document = args[1];
        FileReader fr = new FileReader(document);
        char[] buffer = new char[1024*10];
        int bytes_read = 0;
        if ((bytes_read = fr.read(buffer)) != -1)
          {
            URLConnection urlc = url.openConnection();
            urlc.setRequestProperty("Content-Type","text/xml");
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            PrintWriter pw = new PrintWriter(urlc.getOutputStream());
            // send xml to jsp
            pw.write(buffer, 0, bytes_read);
            pw.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                      System.out.println(inputLine);
            in.close();
            }
          }
          catch (Exception e) {
          e.printStackTrace();
          }
       }
    }
}

The example shows how to open a URL connection to the JSP by using a URL from the argument list; obtain the output stream from the connection; and print the XML document provided in the argument list to the output stream, thus sending the XML data to the JSP. The example then shows how to use the getInputStream() method of the URLConnection class to read the XML data that the JSAP returns to the client application.

The following code segments from a sample JSP show how the JSP receives XML data from the client application, parses the XML document, and sends XML data back:

BufferedReader br = new BufferedReader(request.getReader());
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder db = fact.newDocumentBuilder();
Document doc = db.parse(new InputSource(br));
...
PrintWriter responseWriter = response.getWriter();
responseWriter.println("<?xml version='1.0'?>");

...

For detailed information on programming WebLogic servlets and JSPs, see Developing Web Applications, Servlets, and JSPs for Oracle WebLogic Server.

Handling XML Documents in a JMS Application

WebLogic Server provides the following extensions to some Java Message Service (JMS) classes to handle XML documents in a JMS application:

weblogic.jms.extensions.WLSession, which extends the JMS class javax.jms.Session

weblogic.jms.extensions.WLQueueSession, which extends the JMS class javax.jms.QueueSession

weblogic.jms.extensions.WLTopicSession, which extends the JMS class javax.jms.TopicSession

weblogic.jms.extensions.XMLMessage, which extends the JMS class javax.jms.TextMessage

If you use the XMLMessage class to send and receive XML documents in a JMS application, rather than the more generic TextMessage class, you can use XML-specific message selectors to filter unwanted messages. In particular, you can use the method JMS_BEA_SELECT to specify an XPath query to search for an XML fragment in the XML document. Based on the results of the query, a message consumer might decide not to receive the message, thus possibly reducing network traffic and improving performance of the JMS application.

To use the XMLMessage class to contain XML messages in a JMS application, you must create either a WLQueueSession or WLTopicSession object, depending on whether you want to use JMS queues or topics, rather than the generic QueueSession or TopicSession objects, after you have created a JMS Connection. Then use the createXMLMessage() method of the WLSession interface to create an XMLMessage object.

For detailed information on using XMLMessage objects in your JMS application, see Programming JMS for Oracle WebLogic Server.

Accessing External Entities That Do Not Have an HTTP Interface

WebLogic Server can retrieve and cache external entities that reside in external repositories, as long as they have an HTTP interface, such as a URL, that returns the entity. See External Entity Configuration Tasks for detailed information on using the XML Registry to configure external entities.

If you want to access an external entity that is stored in a repository that does not have an HTTP interface, you must create an interface. For example, assume you store the DTDs for your XML documents in a database table, with columns for the system id, public id, and text of the DTD. To access the DTD as an external entity from a WebLogic XML application, you could create a servlet that uses JDBC to access the DTDs in the database.

Because you invoke servlets with URLs, you now have an HTTP interface to the external entity. When you create the entity registry entry in the XML Registry, you specify the URL that invokes the servlet as the location of the external entity. When WebLogic Server is parsing an XML document that contains a reference to this external entity, it invokes the servlet, passing it the public and system id, which the servlet can internally use to query the database.

8 XML Application Scoping

The following sections describe how to configure parsers, transformers, external entities, and the external entity cache for a particular application:

Overview of Application Scoping

The weblogic-application.xml File

Configuring a Parser or Transformer for an Enterprise Application

Configuring an External Entity for an Enterprise Application

Configuring the External Entity Cache for an Enterprise Application

Overview of Application Scoping

Application scoping refers to configuring resources for a particular enterprise application rather than for an entire WebLogic Server configuration. In the case of XML, these resources include parser, transformer, external entity, and external entity cache configuration. The main advantage of application scoping is that it isolates the resources for a given application to the application itself. Using application scoping, you can configure different parsers for different applications, store the DTDs for an application within the EAR file or exploded enterprise directory, and so on.

Another advantage of using application scoping is that by associating the resources with the EAR file, you can run this EAR file on another instance of WebLogic Server without having to configure the resources for that server.

To configure XML resources for a particular application, you add information to the weblogic-application.xml deployment descriptor file located in the META-INF directory of the EAR file or exploded enterprise application directory.

Note:

You use the Administration Console to configure parser, transformer, and external entity resources for a WebLogic Server instance, as described in Chapter 9, "Administering WebLogic Server XML."

The weblogic-application.xml File

The weblogic-application.xml file is the WebLogic Server-specific deployment descriptor for an enterprise application. It contains configuration information about the XML, JDBC, and EJB resources used by an enterprise application. The standard Java EE deployment descriptor is called application.xml.

The following sample weblogic-application.xml file shows how to configure XML resources for an enterprise application; the body of the various elements are shown in bold:

<weblogic-application>
  ...
  <xml>
     <parser-factory>
        <saxparser-factory>
          com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
        </saxparser-factory>
        <document-builder-factory>
          com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
        </document-builder-factory>
        <transformer-factory>
         com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
        </transformer-factory>
     </parser-factory>
     <entity-mapping>
       <entity-mapping-name>My Mapping</entity-mapping-name>
       <public-id>-//BEA Systems, Inc.//DTD for cars//EN</public-id>
       <system-id>http://www.bea.com/dtds/car.dtd</system-id>
       <entity-uri>dtds/car.dtd</entity-uri>
     </entity-mapping>
  </xml>
</weblogic-application>

The main element for configuring XML resources is <xml>. Figure 8-1 describes the sub-elements of the <xml> element; the sections following this figure describe each element.

Figure 8-1 Sub-Elements of the <xml> Element in weblogic-application.xml

xml

The main element for configuring XML resources, such as parsers, transformers, external entities, and the external entity cache for an enterprise application.

parser-factory

The parent element for specifying a particular parser or transformer for an enterprise application.

saxparser-factory

Element that specifies the factory class to be used for SAX style parsing in this application. If this element is not specified, the default SAX parser factory specified for the WebLogic Server instance is used.

document-builder-factory

Element that specifies the factory class to be used for DOM style parsing in this application. If this element is not specified, the default DOM parser factory specified for the WebLogic Server instance is used.

transformer-factory

Element that specifies the factory class to be used when transforming documents using the javax.xml.transform packages in this application. If this element is not specified, the default XSLT transformer factory specified for the WebLogic Server instance is used.

entity-mapping

The parent element for mapping an entity declaration in an XML file to a local copy of the entity, such as a DTD or Schema.

entity-mapping-name

Element that specifies the name of the entity mapping declaration.

public-id

Element that specifies the public ID of the entity, such as:

 -//BEA Systems, Inc.//DTD for cars//EN.

system-id

Element that specifies the system ID of the entity, such as:

http://www.bea.com/dtds/car.dtd

entity-uri

Element that specifies the URI of the entity. The path is relative to the main directory of the EAR archive or the exploded directory.

For example, dtds/car.dtd indicates that there is a directory called dtds in the main EAR archive (parallel to the META-INF directory) and it contains a file called car.dtd.

when-to-cache

Element that specifies when you should cache the external entity. Valid values are:

cache-on-reference—WebLogic Server caches the external entity referenced by a URL the first time the entity is referenced in an XML document.

cache-at-initialization—WebLogic Server caches the entity when the server starts.

cache-never—WebLogic Server never caches the external entity.

The default value is cache-on-reference.

cache-timeout-interval

Element that specifies the number of seconds after which the cached external entity becomes stale, or out-of-date. WebLogic Server re-retrieves the external entity from the specified URL or pathname relative to the main directory of the EAR archive or exploded directory if the cached copy has been in the cache for longer than this interval.

The default value for this field is 120 seconds.

Configuring a Parser or Transformer for an Enterprise Application

You can specify that an XML application use a parser or transformer different from the default parser or transformer configured for WebLogic Server by updating the weblogic-application.xml file of the EAR file or exploded directory that contains the XML application.

To configure a parser or transformer, other than the default, for an enterprise application, follow these steps:

Use the <parser-factory> sub-element of the <xml> element to configure factory classes for both SAX and DOM style parsing and for XSLT transformations for the enterprise application, as shown in the following example:

     <parser-factory>
        <saxparser-factory>
          com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
        </saxparser-factory>
        <document-builder-factory>
          com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
        </document-builder-factory>
        <transformer-factory>
         com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
        </transformer-factory>
     </parser-factory>

The application corresponding to this weblogic-application.xml file uses the com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl factory class for SAX style parsing, the com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl factory class for DOM style parsing, and the com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl class for XSLT transformations.

If you want the parser or transformer classes to be local to the EAR archive, put the JAR file that contains the classes anywhere you want in the EAR file, then update the Class-Path variable in the META-INF/MANIFEST.MF file.

For example, if you put the parser or transformer classes in a JAR file called myparser.jar in the directory lib/xml, update the MANIFEST.MF file as shown:

Manifest-Version: 1.0
Created-By: 1.3.1_01 (Sun Microsystems Inc.)
Class-Path: lib/xml/myparser.jar

If you want to store the parser or transformer classes in a location other than the EAR archive, be sure that you update the WebLogic Server CLASSPATH variable to include the full pathname of the JAR file that contains the classes.

Configuring an External Entity for an Enterprise Application

You can store a local copy of an external entity, such as a DTD, in the EAR archive or exploded directory rather than always retrieving it from the Web.

To configure an external entity for an enterprise application:

Create the directory lib/xml/registry under the main directory of the EAR archive.

Copy the external entity, such as a DTD, to the directory.

Update the weblogic-application.xml file, using the <entity-mapping> sub-element of the <xml> element to map the name of the entity to entity declarations in any XML files processed by the application, as shown in the following example:

<entity-mapping>
  <entity-mapping-name>My Mapping</entity-mapping-name>
  <public-id>-//BEA Systems, Inc.//DTD for cars//EN</public-id>
  <system-id>http://www.bea.com/dtds/car.dtd</system-id>
  <entity-uri>dtds/car.dtd</entity-uri>
</entity-mapping>

In the example, a local copy of a DTD called car.dtd is stored in the lib/xml/registry/dtds directory under the main directory of the EAR archive or exploded directory. The public ID of the entity is -//BEA Systems, Inc.//DTD for cars//EN and the system id is http://www.bea.com/dtds/car.dtd. Whenever the application is parsing an XML file and it encounters an entity declaration using either one of the IDs, it will substitute the car.dtd file.

Note:

Specify an <entity-mapping> element for each entity declaration for which you want to map a local copy of the entity.

Configuring the External Entity Cache for an Enterprise Application

You can specify that WebLogic Server cache external entities that are referenced with a URL or a pathname relative to the main directory of the EAR archive, either at server-startup or when the entity is first referenced.

Caching the external entity saves the remote access time and provides a local backup in the event that the Administration Server cannot be accessed while an XML document is being parsed, due to the network or the Administration server being down.

You can configure the expiration date of a cached entity, at which point WebLogic Server re-retrieves the entity from the URL or directory of the EAR and re-caches it.

Use the <when-to-cache> and <cache-timeout-interval> subelements of the <entity-mapping> element to configure external entity caching for an enterprise application, as shown in the following example:

<entity-mapping>
  <entity-mapping-name>My Mapping</entity-mapping-name>
  <public-id>-//BEA Systems, Inc.//DTD for cars//EN</public-id>
  <system-id>http://www.bea.com/dtds/car.dtd</system-id>
  <entity-uri>dtds/car.dtd</entity-uri>
  <when-to-cache>cache-at-initialization</when-to-cache>
  <cache-timeout-interval>300</cache-timeout-interval>
</entity-mapping>

In the example, the car.dtd is stored in the lib/xml/registry/dtds directory under the main directory of the EAR archive or exploded directory. WebLogic Server caches a copy of the DTD in its memory when it first starts up, and then refreshes the cached copy if it is stored for longer than 300 seconds.

9 Administering WebLogic Server XML

The following sections describe XML administration with WebLogic Server:

Overview of Administering WebLogic Server XML

XML Parser and Transformer Configuration Tasks

External Entity Configuration Tasks

Overview of Administering WebLogic Server XML

You access the XML Registry through the Administration Console and use it to configure WebLogic Server for XML applications.

To invoke the Administration Console in your browser, enter the following URL:

http://host:port/console

where

host refers to the computer on which the WebLogic Administration Server is running.

port refers to the port number where WebLogic Administration Server is listening for connection requests. The default port number for WebLogic Administration Server is 7001.

XML Administration Tasks

You create, configure, and use the XML Registry using the Administration Console. Using the Administration Console XML Registry has several benefits:

Configuration of XML Registry changes take effect automatically at run time, provided you use JAXP in your XML applications.

When you make changes to the XML Registry, it is not necessary to change your XML application code.

Entity resolution is done locally. You can use the XML Registry either to define a local copy of an entity or to specify that WebLogic Server cache an entity from the Web for a specified duration and use the cached copy rather than the one out on the Web.

You can use the XML Registry to specify:

An alternative server-wide XML parser instead of the default parser.

An XML parser per document type.

An alternative server-wide transformer instead of the default transformer.

External entities that are to be resolved by using local copies of the entities. Once you specify these entities, the Administration Server stores local copies of them in the file system and automatically distributes them to the server's parser at parse time. This feature eliminates the need to construct and set SAX EntityResolvers.

External entities to be cached by WebLogic Server after retrieval from the Web. You specify how long these external entities should be cached before WebLogic Server re-retrieves them and when WebLogic should first retrieve the entities, either at application run time or when WebLogic Server starts.

These capabilities are for use on the server side only.

How the XML Registry Works

You can create as many XML Registries as you like; however, you can associate only one XML Registry with a particular instance of WebLogic Server.

If an instance of WebLogic Server does not have an XML Registry associated with it, then the default parser and transformer are used when parsing or transforming documents. The default parser and transformer are those included in the JDK Version 5.0.

Once you associate an XML Registry with an instance of WebLogic Server, all XML configuration options are available for XML applications that use that server.

You can make the following types of entries for a given XML registry:

Configure parsers and transformers.

Configure external entity resolution.

Note:

The XML Registry is case sensitive. For example, if you are configuring a parser for an XML document type whose root element is <CAR>, you must enter CAR in the Root Element Tag field and not car or Car.

Parser Selection Within the XML Registry

The XML Registry is automatically consulted whenever you use JAXP to parse or transform your XML applications. WebLogic Server follows an ordered lookup when determining which parser class to load:

Use the parser defined for a particular document type.

Use the alternative server-wide parser defined in the XML Registry associated with the WebLogic Server instance.

Use the default parser (the parser included in the JDK 5.0)

The process is also true for transformers, except for the first step, because you cannot define a transformer for a particular document type.

Additionally, when WebLogic Server starts, a SAX entity resolver is automatically set so that it can resolve entities that are declared in the registry. As a result, users are not required to modify their XML application code to control the parsers used, or to set the location of local copies of external entities. The parser being used and the location of the external entity is controlled by the XML Registry.

Note:

If you elect to use an API provided by a parser instead of JAXP, the XML Registry has no effect on the processing of XML documents. For this reason, it is highly recommended that you always use JAXP in your XML applications.

XML Parser and Transformer Configuration Tasks

By default, WebLogic Server is configured to use the default parser and transformer to parse and transform XML documents. The default parser and transformer are those included in the JDK 5.0. As long as you use the default, you do not have to perform any configuration tasks for your XML applications. If you want to use a parser or transformer other than the default, you must use the XML Registry to configure them, as described in the following sections.

Configuring a Parser or Transformer Other Than the Default

The following procedure first describes how to create an XML registry that defines SAX and DOM parsers and transformers. It then describes how to associate (or plug-in) the new XML Registry with an instance of WebLogic Server so that the server starts to use the new parsers and transformer.

Note:

You can plug-in only those parsers and transformers that are compatible with the default WebLogic Server parser transformer. The default parser and transformer are those that are included in the JDK 5.0.

Start the WebLogic Administration Server and invoke the Administration Console in your browser. See Overview of Administering WebLogic Server XML for information on invoking the Administration Console.

Follow the steps outlined in "Create an XML registry" in the Oracle WebLogic Server Administration Console Help.

Configuring a Parser for a Particular Document Type

When you configure a parser for a particular document type, you can use the document's system id, public id, or root element to identify the document type.

Note:

WebLogic Server searches only the first 1000 bytes of an XML document when attempting to identify its document type. If it does not find a DOCTYPE identifier in those first 1000 bytes, it stops searching the document and uses the parser configured for the WebLogic Server instance to parse the document.

To configure a parser for a particular document type, follow these steps:

Start the WebLogic Administration Server and invoke the Administration Console in your browser.

See Overview of Administering WebLogic Server XML for information on invoking the Administration Console.

Follow the steps outlined in "Associate a Parser to a Document Type" in the Oracle WebLogic Server Administration Console Help.

External Entity Configuration Tasks

Use the XML Registry to configure external entity resolution and to configure and monitor the external entity cache.

Configuring External Entity Resolution

You can configure external entity resolution with WebLogic Server in the following two ways:

Physically copy the entity files to a directory accessible by WebLogic Administration Server and specify that the Administration Server use the local copy whenever the external entity is referenced in an XML document.

Specify that a Managed Server cache external entities that are referenced with a URL or a pathname relative to the Administration Server, either at server-startup or when the entity is first referenced.

Caching the external entity in a Managed Server saves the remote access time and provides a local backup in the event that the Administration Server cannot be accessed while an XML document is being parsed, due to the network or the Administration Server being down.

You can configure the expiration date for a cached entity, at which point WebLogic Server re-retrieves the entity from the URL or Administration Server and re-caches it.

To configure external entity resolution, perform the following steps:

Start the WebLogic Administration Server and invoke the Administration Console in your browser.

See Overview of Administering WebLogic Server XML for information on invoking the Administration Console.

Follow the steps outlined in "Configure External Entity Resolution" in Oracle WebLogic Server Administration Console Help.

Configuring the External Entity Cache

You can configure the following properties of the external entity cache:

Size, in KB, of the cache memory. The default value for this property is 500 KB.

Size, in MB, of the persistent disk cache. The default value for this property is 5 MB.

Number of seconds after which external entities in the cache become stale after they have been cached by WebLogic Server. This is the default value for the entire server - you can override this value for specific external entities when you configure the entity. The default value for this property is 120 seconds (2 minutes).

To configure the external entity cache, follow these steps:

Start the WebLogic Administration Server and invoke the Administration Console in your browser.

See Overview of Administering WebLogic Server XML for information on invoking the Administration Console.

Follow the steps outlined in "Create an XML Entity Cache" in Oracle WebLogic Server Administration Console Help.

A XML Reference

The following sections provide links to additional information about the XML specifications, application programming interfaces (APIs), and tools supported by WebLogic Server:

XML APIs

Code Examples

Related WebLogic Server Documentation

Tutorials and Online Courses

Other XML Specifications and Information

XML APIs

SAX 2.0 API, at http://www.saxproject.org/

DOM (Document Object Model) Level 2 Specification, at http://www.w3.org/TR/DOM-Level-2/

JAXP API 1.2 specification, at http://download.oracle.com/javase/6/docs/technotes/guides/xml/index.html

Code Examples

XML code examples and supporting documentation are included in the WebLogic Server distribution at WL_HOME\samples\server\examples\src\examples\xml, where WL_HOME refers to the top-level WebLogic Server directory.

Related WebLogic Server Documentation

Getting Started With JAX-WS Web Services for Oracle WebLogic Server

Programming WebLogic Enterprise JavaBeans for Oracle WebLogic Server

Programming JMS for Oracle WebLogic Server

Developing Web Applications, Servlets, and JSPs for Oracle WebLogic Server

Tutorials and Online Courses

A Technical Introduction to XML, available at http://www.xml.com/pub/a/98/10/guide0.html

XML Authoring Tutorial, available at http://www.xml.com/pub/r/32

Working with XML and Java, available at http://java.sun.com/xml/tutorial_intro.html

Tutorials for using the Java 2 platform and XML technology available at http://developerlife.com

Developing XML Solutions with JavaServer Pages Technology, available at http://java.sun.com/products/jsp/html/JSPXML.html

XML, Java, and the Future of the Web, available at http://www.xml.com/pub/a/w3j/s3.bosak.html

Chapter 17 of the XML Bible: XSL Transformations, available at http://metalab.unc.edu/xml/books/bible/updates/14.html

XSL Tutorial by Miloslav Nic, available at http://zvon.vscht.cz/HTMLonly/XSLTutorial/Books/Book1/index.html

XML Schema Part 0: Primer, available at http://www.w3.org/TR/2000/CR-xmlschema-0-20001024/

Other XML Specifications and Information

XML 1.0 specification, available at http://www.w3.org/TR/REC-xml/

XMLSchema Part 1: Structures, available at http://www.w3.org/TR/xmlschema-1/

XML Schema Part 2: Datatypes, available at http://www.w3.org/TR/xmlschema-2

Namespaces in XML, available at http://www.w3.org/TR/REC-xml-names/

Extensible Stylesheet Language (XSL) 1.0 Specification, available at http://www.w3.org/TR/xsl/

JSR-000031 XML Data Binding Specification, available at http://jcp.org/en/jsr/detail?id=031

XML Path Language (XPath) Version 1.0 Specification, available at http://www.w3.org/TR/xpath

XML Linking Language (XLink) Specification, available at http://www.w3.org/TR/xlink

XML Pointer Language (XPointer) Specification, available at http://www.w3.org/TR/WD-xptr

W3C (World Wide Web Consortium) home page at http://www.w3c.org

XML.com home page at http://www.xml.com

XML FAQ page at http://www.ucc.ie/xml/

XML.org, The XML Industry Portal, available at http://www.xml.org/

B Using the WebLogic XML Streaming API (Deprecated)

Note:

The WebLogic XML Streaming API has been deprecated as of release 9.0 of WebLogic Server. You should instead use the Streaming API for XML (StAX), a standard specification from the Java Community Process. For details, see Chapter 4, "Using the Streaming API for XML (StAX)."

The following sections describe how to use the WebLogic XML Streaming API to parse and generate XML documents:

Overview of the WebLogic XML Streaming API

Javadocs for the WebLogic XML Streaming API

Parsing an XML Document: Typical Steps

Generating a New XML Document: Typical Steps

Overview of the WebLogic XML Streaming API

The WebLogic XML Streaming API provides an easy and intuitive way to parse and generate XML documents. It is similar to the SAX API, but enables a procedural, stream-based handling of XML documents rather than requiring you to write SAX event handlers, which can get complicated when you work with complex XML documents. In other words, the streaming API gives you more control over parsing than the SAX API.

When a program parses an XML document using SAX, the program must create event listeners that listen to parsing events as they occur; the program must react to events rather than ask for a specific event. By contrast, when you use the streaming API, you can methodically step through an XML document, ask for certain types of events (such as the start of an element), iterate over the attributes of an element, skip ahead in the document, stop processing at any time, get sub-elements of a particular element, and filter out elements as desired. Because you are asking for events rather than reacting to them, using the streaming API is often referred to as pull parsing.

You can parse many types of XML documents with the streaming API, such as XML files on the operating system, DOM trees, and sets of SAX events. You convert these XML documents into a stream of events, or an XMLInputStream, and then step through the stream, pulling events such as the start of an element, the end of the document, and so on, off the stack as needed.

The WebLogic Streaming API uses the WebLogic FastParser as its default parser.

For a complete example of parsing an XML document using the streaming API, see the WL_HOME\samples\server\examples\src\examples\xml\orderParser directory, where WL_HOME refers to the top-level WebLogic Server directory.

Table B-1 describes the main interfaces and classes of the WebLogic Streaming API.

Table B-1 Interfaces and Classes of the XML Streaming API

Interface or Class
Description

XMLInputStreamFactory

Factory used to create XMLInputStream objects for parsing XML documents.

XMLInputStream

Interface used to contain the input stream of events.

BufferedXMLInputStream

Extension of the XMLInputStream interface to allow marking and resetting of the stream.

XMLOutputStreamFactory

Factory used to create XMLOutputStream objects for generating XML documents.

XMLOutputStream

Interface used write events.

ElementFactory

Utility to create instances of the interfaces used in this API.

XMLEvent

Base interface for all types of events in an XML document, such as the start of an element, the end of an element, and so on.

StartElement

Most important of the XMLEvent sub-interfaces. Used to get information about a start element in an XML document.

AttributeIterator

Object used to iterate over the set of attributes of an element.

Attribute

Object that describes a particular attribute of an element.

Javadocs for the WebLogic XML Streaming API

The following Javadocs provide reference material for the WebLogic XML Streaming API features described in this chapter as well as additional features not explicitly documented:

"weblogic.xml.stream"

"weblogic.xml.stream.util"

Parsing an XML Document: Typical Steps

The following procedure describes the typical steps for using the WebLogic XML Streaming API to parse and manipulate an XML document.

The first two steps are required. The next steps you take depend on how you want to process the XML file.

Import the weblogic.xml.stream.* classes.

Get an XML stream of events from an XML file, a DOM tree, or a set of SAX events. You can also filter the XML stream to get only certain types of events, names of specific elements, and so on. See Getting an XML Input Stream.

Iterate over the stream, returning generic XMLEvent types. See Iterating Over the Stream.

For each generic XMLEvent type, determine the specific event type. Event types include the start of an XML document, the end of an element, an entity reference, and so on. See Determining the Specific XMLEvent Type.

Get the attributes of an element. See Getting the Attributes of an Element.

Position the stream by skipping over event, skipping to a particular event, and so on. See Positioning the Stream.

Get the children of an element. See Getting a Substream.

Close the stream. See Closing the Input Stream.

Example of Parsing an XML Document

The following program shows an example of using the XML Streaming API to parse an XML document.

The program takes a single parameter, an XML file, that it converts into an XML input stream. It then iterates over the stream, determining the type of each event, such as the start of an XML element, the end of the XML document, and so on. The program prints out information for three types of events: start elements, end elements, and the character data that forms the body of an element. The program does nothing when it encounters the other types of events, such as comments or start of the XML document.

Note:

The code in bold font is described in detail in the sections following the example.

package examples.xml.stream;
import weblogic.xml.stream.Attribute;
import weblogic.xml.stream.AttributeIterator;
import weblogic.xml.stream.ChangePrefixMapping;
import weblogic.xml.stream.CharacterData;
import weblogic.xml.stream.Comment;
import weblogic.xml.stream.XMLEvent;
import weblogic.xml.stream.EndDocument;
import weblogic.xml.stream.EndElement;
import weblogic.xml.stream.EntityReference;
import weblogic.xml.stream.ProcessingInstruction;
import weblogic.xml.stream.Space;
import weblogic.xml.stream.StartDocument;
import weblogic.xml.stream.StartPrefixMapping;
import weblogic.xml.stream.StartElement;
import weblogic.xml.stream.EndPrefixMapping;
import weblogic.xml.stream.XMLInputStream;
import weblogic.xml.stream.XMLInputStreamFactory;
import weblogic.xml.stream.XMLName;
import weblogic.xml.stream.XMLStreamException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ComplexParse {
  /**
   * Helper method to get a handle on a stream.
   * Takes in a name and returns a stream.  This
   * method usese the InputStreamFactory to create an
   * instance of an XMLInputStream
   * @param name The file to parse
   * @return XMLInputStream the stream to parse
   */
  public XMLInputStream getStream(String name)
    throws XMLStreamException, FileNotFoundException
  {
    XMLInputStreamFactory factory = XMLInputStreamFactory.newInstance();
    XMLInputStream stream = factory.newInputStream(new FileInputStream(name));
    return stream;
  }
  /**
   *  Determines the type of event, such as the start
   *  of an element, end of a document, and so on.  If the
   *  event is of type START_ELEMENT, END_ELEMENT, or
   *  CHARACTER_DATA, the method prints out appropriate info;
   *  otherwise, it does nothing.
   *  @param event The XML event that has been parsed
   */
  public void parse(XMLEvent event)
    throws XMLStreamException
  {
    switch(event.getType()) {
    case XMLEvent.START_ELEMENT:
      StartElement startElement = (StartElement) event;
      System.out.print("<" + startElement.getName().getQualifiedName() );
      AttributeIterator attributes = startElement.getAttributesAndNamespaces();
      while(attributes.hasNext()){
        Attribute attribute = attributes.next();
        System.out.print(" " + attribute.getName().getQualifiedName() +
                          "='" + attribute.getValue() + "'");
      }
      System.out.print(">");
      break;
    case XMLEvent.END_ELEMENT:
      System.out.print("</" + event.getName().getQualifiedName() +">");
      break;
    case XMLEvent.SPACE:
    case XMLEvent.CHARACTER_DATA:
      CharacterData characterData = (CharacterData) event;
      System.out.print(characterData.getContent());
      break;
    case XMLEvent.COMMENT:
      // Print comment
      break;
    case XMLEvent.PROCESSING_INSTRUCTION:
      // Print ProcessingInstruction
      break;
    case XMLEvent.START_DOCUMENT:
      // Print StartDocument
      break;
    case XMLEvent.END_DOCUMENT:
      // Print EndDocument
      break;
    case XMLEvent.START_PREFIX_MAPPING:
      // Print StartPrefixMapping
      break;
    case XMLEvent.END_PREFIX_MAPPING:
      // Print EndPrefixMapping
      break;
    case XMLEvent.CHANGE_PREFIX_MAPPING:
      // Print ChangePrefixMapping
      break;
    case XMLEvent.ENTITY_REFERENCE:
      // Print EntityReference
      break;
    case XMLEvent.NULL_ELEMENT:
      throw new XMLStreamException("Attempt to write a null event.");
    default:
      throw new XMLStreamException("Attempt to write unknown event
                                    ["+event.getType()+"]");
    }
  }
  /**
   * Helper method to iterate over a stream
   * @param name The file to parse
   */
  public void parse(XMLInputStream stream)
    throws XMLStreamException
  {
    while(stream.hasNext()) {
      XMLEvent event = stream.next();
      parse(event);
    }
    stream.close();
  }
  /** Main method.   Takes a single argument: an XML file
   *  that will be converted into an XML input stream.
   */
  public static void main(String args[])
    throws Exception
  {
    ComplexParse complexParse= new ComplexParse();
    complexParse.parse(complexParse.getStream(args[0]));
  }
}

Getting an XML Input Stream

You can use the XML Streaming API to convert a variety of objects, such as XML files, DOM trees, or SAX events, into a stream of events.

The following example shows how to create a stream of events from an XML file:

XMLInputStreamFactory factory = XMLInputStreamFactory.newInstance();
XMLInputStream stream = factory.newInputStream(new FileInputStream(name));

First you create a new instance of the XMLInputStreamFactory, then use the factory to create a new XMLInputStream from the XML file referred to in the name variable.

The following example shows how to create a stream from a DOM tree:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new java.io.File(file));
XMLInputStream stream = XMLInputStreamFactory.newInstance().newInputStream(doc);

Getting a Buffered XML Input Stream

After you finish iterating over an XMLInputStream object, you cannot access the stream again. If, however, you need to process the stream again, such as send it to another application or iterate over it again in some other way, use a BufferedXMLInputStream object rather than a plain XMlInputStream object.

Use the newBufferedInputStream() method of the XMLInputStreamFactory class to create a buffered XML input stream, as shown in the following example:

XMLInputStreamFactory factory = XMLInputStreamFactory.newInstance();
BufferedXMLInputStream bufstream =
    factory.newBufferedInputStream(factory.newInputStream(new
    FileInputStream(name)));

You can use the mark() and reset() methods of the BufferedXMLInputStream object to mark a particular spot in the stream, continue processing the stream, then reset the stream back to the marked spot. See Marking and Resetting a Buffered XML Input Stream for more information.

Filtering the XML Stream

Filtering an XML stream refers to creating a stream that contains only specified types of events. For example, you can create a stream that contains only start elements, end elements, and the character data that make up the body of an XML element. Another example is filtering an XML stream so that only elements with a specified name appear in the stream.

To filter an XML stream, you specify a filter class as the second parameter to the XMLInputStreamFactory.newInputStream() method. You specify the events that you want in the XML stream as parameters to the filter class. The following example shows how to use the TypeFilter class to specify that you want only start and end XML elements and character data in the resulting XML stream:

import weblogic.xml.stream.util.TypeFilter;
XMLInputStreamFactory factory = XMLInputStreamFactory.newInstance();
XMLInputStream stream = factory.newInputStream(new FileInputStream(name),
                        new TypeFilter(XMLEvent.START_ELEMENT |
                                       XMLEvent.END_ELEMENT |
                                       XMLEvent.CHARACTER_DATA));

Table B-2 describes the filters provided by the WebLogic XML Streaming API. They are part of the weblogic.xml.stream.util package.

Table B-2 Filters Provided by WebLogic XML Streaming API

Name of Filter
Description
Sample Usage

TypeFilter

Filter an XML stream based on specified event types, such as XMLEvent.START_ELEMENT, XMLEvent.END_ELEMENT, and so on. See Determining the Specific XMLEvent Type for a full list of event types.

TypeFilter takes an integer bitmask as input; you OR the values to create this bitmask, as shown in the sample.

new TypeFilter (XMLEvent.START_ELEMENT |
 XMLEvent.END_ELEMENT |
 XMLEvent.CHARACTER_DATA)

NameFilter

Filter an XML stream based on the name of an element in the XML document.

new NameFilter ("Book")

NameSpaceFilter

Filter an XML stream based on the specified namespace URI.

new NameSpaceFilter ("http://namespace.org")

NamespaceTypeFilter

Filter an XML stream based on specified event types and namespace URI. This filter combines the functionality of TypeFilter and NameSpaceFilter.

new NamespaceFilter ("http://namespace.org", XMLEvent.START_ELEMENT)

The example returns a stream where all start elements have the specified namespace.

Creating a Custom Filter

You can also create your own filter if the ones included in the API do not meet your needs.

Create a class that implements the ElementFilter interface and contains a method called accept(XMLEvent). This method tells the XMLInputStreamFactory.newInputStream() method whether to add a particular event to the stream or not, as shown in the following example:

package my.filters;

import weblogic.xml.stream.XMLName;
import weblogic.xml.stream.ElementFilter;
import weblogic.xml.stream.events.NullEvent;

public class SuperDooperFilter implements ElementFilter {

  protected String name;

  public SuperDooperFilter(String name)
  {
    this.name = name;
  }

  public boolean accept(XMLEvent e) {
    if (name.equals(e.getName().getLocalName()))
      return true;
    return false;
  }
}

In your XML application, be sure to import the new filter class:

import my.filters.SuperDooperFilter

Specify the filter as the second parameter to the newInputStream() method, passing to the filter class the types of events you want to appear in the XML stream in whatever format required by your filter class:

XMLInputStreamFactory factory = XMLInputStreamFactory.newInstance();
XMLInputStream stream = factory.newInputStream(new FileInputStream(name),
                        new SuperDooperFilter(param));

Iterating Over the Stream

Once you have a stream of events, the next step is to methodically step through it using the XMLInputStream.next() and XMLInputStream.hasNext() methods, as shown in the following example:

while(stream.hasNext()) {
  XMLEvent event = stream.next();
  System.out.print(event);
}

Determining the Specific XMLEvent Type

The XMLInputStream.next() method returns an object of type XMLEvent. XMLEvent has subinterfaces that further classify what this event might be, such as the start of the XML document, the end of an element, an entity reference, and so on. The XMLEvent interface also contains corresponding fields, or constants, as well as a set of methods that you can use to identify the actual event. Figure B-1 shows the hierarchy of the XMLEvent interface and its subinterfaces.

Figure B-1 Hierarchy of the XMLEvent Interface and Its SubInterfaces

Table B-3 lists the subclasses and fields of the XMLEvent class that you can use to identify a particular event while parsing the XML stream

Table B-3 Subclasses and Fields of the XMLEvent Class

XMLEvent Subclass
Field of the XMLEvent Class used to Identify Subclass
Method used to Identify Subclass
Description of the Subclass Event

ChangePrefixMapping

CHANGE_PREFIX_MAPPING

isChangePrefixMapping

Signals that a prefix mapping has changed from an old namespace to a new namespace.

CharacterData

CHARACTER_DATA

isCharacterData

Signals that the returned XMLEvent object contains the character data from the body of the element.

Comment

COMMENT

isComment

Signals that the returned XMLEvent object contains an XML comment.

EndDocument

END_DOCUMENT

isEndDocument

Signals the end of the XML document.

EndElement

END_ELEMENT

isEndElement

Signals the end of an element in the XML document.

EndPrefixMapping

END_PREFIX_MAPPING

isEndPrefixMapping

Signals that a prefix mapping has gone out of scope.

EntityReference

ENTITY_REFERENCE

isEntityReference

Signals that the returned XMLEvent object contains an entity reference.

ProcessingInstruction

PROCESSING_INSTRUCTION

isProcessingInstruction

Signals that the returned XMLEvent object contains a processing instruction.

Space

SPACE

isSpace

Signals that the returned XMLEvent object contains whitespace.

StartDocument

START_DOCUMENT

isStartDocument

Signals the start of an XML document.

StartElement

START_ELEMENT

isStartElement

Signals the start of a element in the XML document.

StartPrefixMapping

START_PREFIX_MAPPING

isStartPrefixMapping

Signals that a prefix mapping has started its scope.

The following example shows how to use the Java case statement to determine the particular type of event that was returned by the XMLInputStream.next() method. For simplicity, the example simply prints that an event has been found; later sections show further processing of the event.

    switch(event.getType()) {
    case XMLEvent.START_ELEMENT:
      // Start of an element
      System.out.println ("Start Element\n");
      break;

    case XMLEvent.END_ELEMENT:
      // End of an element
      System.out.println ("End Element\n");
      break;

    case XMLEvent.PROCESSING_INSTRUCTION:
      // Processing Instruction
      System.out.println ("Processing instruction\n");
      break;

    case XMLEvent.SPACE:
      // Whitespace
      System.out.println ("White space\n");
      break;

    case XMLEvent.CHARACTER_DATA:
      // Character data
      System.out.println ("Character data\n");
      break;

    case XMLEvent.COMMENT:
      // Comment
      System.out.println ("Comment\n");
      break;

    case XMLEvent.START_DOCUMENT:
      // Start of the XML document
      System.out.println ("Start Document\n");
      break;

    case XMLEvent.END_DOCUMENT:
      // End of the XML Document
      System.out.println ("End Document\n");
      break;

    case XMLEvent.START_PREFIX_MAPPING:
      // The start of a prefix mapping scope
      System.out.println ("Start prefix mapping\n");
      break;

    case XMLEvent.END_PREFIX_MAPPING:
      // The end of a prefix mapping scope
      System.out.println ("End prefix mapping\n");
      break;

    case XMLEvent.CHANGE_PREFIX_MAPPING:
      // Prefix mapping has changed namespaces
      System.out.println ("Change prefix mapping\n");
      break;

    case XMLEvent.ENTITY_REFERENCE:
      // An entity reference
      System.out.println ("Entity reference\n");
      break;
    default:

      throw new XMLStreamException("Attempt to parse unknown event
                                    [" + event.getType() + "]");
    }

Getting the Attributes of an Element

To get the attributes of an element in an XML document, you must first cast the XMLEvent object that was returned by the XMLInputStream.next() method to a StartElement object.

Because you do not know how many attributes an element might have, you must first create an AttributeIterator object to contain the entire list of attributes, and then iterate over the list until there are no more attributes. The following example describes how to do this as part of the START_ELEMENT case of the switch statement shown in Iterating Over the Stream:

case XMLEvent.START_ELEMENT:

    StartElement startElement = (StartElement) event;
    System.out.print("<" + startElement.getName().getQualifiedName() );
    AttributeIterator attributes = startElement.getAttributesAndNamespaces();
    while(attributes.hasNext()){
      Attribute attribute = attributes.next();
      System.out.print(" " + attribute.getName().getQualifiedName() +
                        "='" + attribute.getValue() + "'");
    }
    System.out.print(">");
    break;

The example first creates a StartElement object by casting the returned XMLEvent to StartElement. It then creates an AttributeIterator object using the method StartElement.getAttributesAndNamespaces(), and iterates over the attributes using the AttributeIterator.hasNext() method. For each Attribute, it uses the Attributes.getName().getQualifiedName() and Attribute.getValue() methods to return the name and value of the attribute.

You can also use the getNamespace() and getAttributes() methods to return just the namespaces or attributes on their own.

Positioning the Stream

Table B-4 describes the methods of the XMLInputStream interface that you can use to skip ahead to specific locations in the stream.

Table B-4 Methods Used to Position the Input Stream

Method of XMLInputStream
Description

skip()

Positions the input stream to the next stream event.

Note: The next event might not necessarily be an actual element in the XML file; for example, it could be a comment or white space.

skip(int)

Positions the input stream to the next event of this type.

Examples of event types are XMLEvent.START_ELEMENT and XMLEvent.END_DOCUMENT. Refer to Table B-3 for the full list of event types.

skip(XMLName)

Positions the input stream to the next event of this name.

skip(XMLName, int)

Positions the input stream to the next event of this name and type.

skipElement()

Skips to the next element (does not skip to the sub-elements of the current element).

peek()

Checks the next event without actually reading it from the stream.

The following example shows how you can modify the basic code for iterating over an input stream to skip over the character data in the body of an XML element:

    while(stream.hasNext()) {
      XMLEvent peek = stream.peek();
      if (peek.getType() == XMLEvent.CHARACTER_DATA ) {
        stream.skip();
        continue;
      }
      XMLEvent event = stream.next();
      parse(event);
    }

The example shows how to use the XMLInputStream.peek() method to determine the next event on the stream. If the type of event is XMLEvent.CHARACTER_DATA, then skip the event and go to the next one.

Getting a Substream

Use the XMLInputStream.getSubStream() method to get a copy of the next element, including all its subelements. The getSubstream() method returns an XMLInputStream object. Your position in the parent stream (or the stream from which you called getSubStream()) does not move. In the parent stream, if you want to skip the element you just got with getSubStream(), use the skipElement() method.

The getSubStream() method keeps a count of the START_ELEMENT and END_ELEMENT events it encounters, and as soon as the number is equal (or in other words, as soon as it finds the complete next element) it stops and returns the resulting substream as an XMLInputStream object.

For example, assume that you are using the XML Streaming API to parse the following XML document, but you are only interested in the substream delineated by the <content> and </content> tags:

<book>
  <title>The History of the World</title>
  <author>Juliet Shackell</author>
  <publisher>CrazyDays Publishing</publisher>
  <content>
      <chapter title='Just a Speck of Dust'>
        <synopsis>The world as a speck of dust</synopsis>
        <para>Once the world was just a speck of dust...</para>
      </chapter>
      <chapter title='Life Appears'>
        <synopsis>Move over dust, here comes life.</synopsis>
        <para>Happily, the dust got a companion: life...</para>
      </chapter>
   </content>
</book>

The following code fragment shows how you can skip to the <content> start element tag, get the substream, and parse it using a separate ComplexParse object:

     if (stream.skip( ElementFactory.createXMLName("content")))
       {
          ComplexParse complexParse = new ComplexParse();
          complexParse.parse(stream.getSubStream());
       }

When you call this method on the previous XML document, you get the following output:

<content>
      <chapter title='Just a Speck of Dust'>
        <synopsis>The world as a speck of dust</synopsis>
        <para>Once the world was just a speck of dust...</para>
      </chapter>
      <chapter title='Life Appears'>
        <synopsis>Move over dust, here comes life.</synopsis>
        <para>Happily, the dust got a companion: life...</para>
      </chapter>
</content>

Marking and Resetting a Buffered XML Input Stream

If you are using a BufferedXMLInputStream object, you can use the mark() and reset() methods to mark the stream at a particular spot, process the stream, and then subsequently reset the stream back to the marked spot. These methods are useful if you want to further manipulate the stream after initially iterating over it.

Note:

If you read a buffered stream without marking it, you cannot access what you've just read. In other words, just because the stream is buffered, it does not automatically mean you can reread it. You must mark it first.

The following example shows a typical use of the BufferedXMLInputStream object:

    XMLInputStreamFactory factory = XMLInputStreamFactory.newInstance();
    BufferedXMLInputStream bufstream =
    factory.newBufferedInputStream(factory.newInputStream(new
                FileInputStream(name)));

    // mark the start of the stream
    bufstream.mark();

    // process it locally
    bufferedParse.parse(bufstream);

    // reset the stream to the mark
    bufstream.reset();

    // send stream off to another application
    ComplexParse complexParse =  new ComplexParse();
    complexParse.parse(bufstream);

Closing the Input Stream

It is good programming practice to explicitly close the XML input stream when you are finished with it. To close an input stream, use the XMLInputStream.close() method, as shown in the following example:

// close the input stream
input.close();

Generating a New XML Document: Typical Steps

The following procedure describes the typical steps for using the WebLogic XML Streaming API to generate a new XML document.

The first two steps are required. The next steps you take depend on how you want to generate the XML file.

Import the weblogic.xml.stream.* classes.

Create an XML output stream to which to write the XML document. See Creating an XML Output Stream.

Add events to the XML output stream. See Adding Elements to the Output Stream.

Add attributes to the XML output stream. See Adding Attributes to an Element on the Output Stream.

Add an input stream to the output stream. See Adding an Input Stream to an Output Stream.

Print the output stream. See Printing an Output Stream.

Close the output stream. See Closing the Output Stream.

Example of Generating an XML Document

The following program shows an example of using the XML Streaming API to generate an XML document.

The program first creates an output stream based on a PrintWriter object, then adds elements to the output stream to create a simple XML purchase order, described in the comments of the program. The program also shows how to add an input stream based on a separate XML file to the output stream.

Note:

The topics following the example describe it in more detail.

package examples.xml.stream;

import weblogic.xml.stream.XMLInputStream;
import weblogic.xml.stream.XMLOutputStream;
import weblogic.xml.stream.XMLInputStreamFactory;
import weblogic.xml.stream.XMLName;
import weblogic.xml.stream.XMLEvent;
import weblogic.xml.stream.StartElement;
import weblogic.xml.stream.EndElement;
import weblogic.xml.stream.Attribute;
import weblogic.xml.stream.ElementFactory;
import weblogic.xml.stream.XMLStreamException;
import weblogic.xml.stream.XMLOutputStreamFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

/**
 * Program that prints out a very simple purchase order that looks
 * like the following:
 *
 * <purchase_order>
 *  <name>Juliet Shackell</name>
 *  <item id="1234" quantity="2">Fabulous Chair</item>
 *  <!-- this is a comment-->
 *  <another_file>
 *    This comes from another file called "another_file.xml"
 *  </another_file>
 * </purchase_order>
 *
 * In the preceding XML file, the <another_file> element is actually another
 * XML file that is passed as an argument to the program, converted into an
 * XMLInputStream, then added to the output stream.
 */
public class PrintPurchaseOrder {

  /**
   * Helper method to get a handle on a stream.
   * Takes in a name and returns a stream.  This
   * method uses the InputStreamFactory to create an
   * instance of an XMLInputStream
   * @param name The file to parse
   * @return XMLInputStream the stream to parse
   */
  public XMLInputStream getInputStream(String name)
    throws XMLStreamException, FileNotFoundException
  {
    XMLInputStreamFactory factory = XMLInputStreamFactory.newInstance();
    XMLInputStream stream = factory.newInputStream(new FileInputStream(name));
    return stream;
  }
  public static void main(String args[])
    throws Exception
  {
    PrintPurchaseOrder printer = new PrintPurchaseOrder();
    //
    // Create an output stream.
    //
    XMLOutputStreamFactory factory = XMLOutputStreamFactory.newInstance();
    XMLOutputStream output = factory.newOutputStream(new
                                        PrintWriter(System.out,true));
   // add the <purchase_order> root element
   output.add(ElementFactory.createStartElement("purchase_order"));
   output.add(ElementFactory.createCharacterData("\n"));

   // add the <name> element
   output.add(ElementFactory.createStartElement("name"));
   output.add(ElementFactory.createCharacterData("Juliet Shackell"));
   output.add(ElementFactory.createEndElement("name"));
   output.add(ElementFactory.createCharacterData("\n"));

   // add the <item> element along with the id and quantity attributes
   output.add(ElementFactory.createStartElement("item"));
   output.add(ElementFactory.createAttribute("id","1234"));
   output.add(ElementFactory.createAttribute("quantity","2"));
   output.add(ElementFactory.createCharacterData("Fabulous Chair"));
   output.add(ElementFactory.createEndElement("item"));
   output.add(ElementFactory.createCharacterData("\n"));

    // add a comment
   output.add("<!-- this is a comment-->");
   output.add(ElementFactory.createCharacterData("\n"));

   // create an input stream from each XML file argument then add it to the output
   for (int i=0; i < args.length; i++)
   //
   // Get an input stream and add it to the output stream
   //
   output.add(printer.getInputStream(args[i]));

    // Finally, end the root "purchase_order" element
   output.add(ElementFactory.createEndElement("purchase_order"));
   output.add(ElementFactory.createCharacterData("\n"));

    //
    // Print the results to the screen
    //
    output.flush();

   // Close the output streams
   output.close();
  }
}

The preceding program produces the following output:

<purchase_order>
  <name>Juliet Shackell</name>
  <item id="1234" quantity="2">Fabulous Chair</item>
  <!-- this is a comment-->
  <another_file>
     This is from another file.
  </another_file>
</purchase_order>

Creating an XML Output Stream

One of the first steps in generating an XML document using the Weblogic XML Streaming API is to create an output stream which holds the document as it is being built. Creating an XML output stream is similar to creating an input stream: you first create an instance of the XMLOutputStreamFactory and then create an output stream with the XMLOutputStreamFactory.newOutputStream() method, as shown in the following example:

            XMLOutputStreamFactory factory = XMLOutputStreamFactory.newInstance();
    XMLOutputStream output = factory.newOutputStream(new
                              PrintWriter(System.out,true));

The following example shows how to create an XMLOutputStream based on a DOM tree:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    XMLOutputStream out =
         XMLOutputStreamFactory.newInstance().newOutputStream(doc);

You can use the XMLOutputStreamFactory.newOutputStream() method to create an output stream based on the following four Java objects, depending on what the final form of the XML document will be (such as a file on the operating system, a DOM tree, and so on):

java.io.OutputStream

java.io.Writer

org.xml.sax.ContentHandler

org.w3c.dom.Document

Adding Elements to the Output Stream

Use the XMLOutputStream.add(XMLEvent) method to add elements to the output stream. Use the ElementFactory to create the particular element.

The ElementFactory interface includes methods to create each type of element; the general format is ElementFactory.createXXX() where XXX refers to the particular element, such as createStartElement(), createCharacterData(), and so on. You can create most elements by passing the name as a String or as an XMLName.

Tip:

The XMLOutputStream does not validate your XML.

Note:

Each time you create a start element, you must explicitly also create an end element at some point. The same rule applies to creating a start document.

For example, assume you want to create the following snippet of XML:

<name>Juliet Shackell</name>

The Java code to add this element to an output stream is as follows:

   output.add(ElementFactory.createStartElement("name"));
   output.add(ElementFactory.createCharacterData("Juliet Shackell"));
   output.add(ElementFactory.createEndElement("name"));
   output.add(ElementFactory.createCharacterData("\n"));

The final createCharacterData() method adds a newline character to the output stream. This is optional, but useful if you want to create human-readable XML.

Adding Attributes to an Element on the Output Stream

Use the XMLOutputStream.add(Attribute) to add attributes to an element you have just created. Use the ElementFactory.createAttribute() method to create a particular attribute.

For example, assume you want to create the following snippet of XML:

<item id="1234" quantity="2">Fabulous Chair</item>

The Java code to add this element to an output stream is as follows:

   output.add(ElementFactory.createStartElement("item"));
   output.add(ElementFactory.createAttribute("id","1234"));
   output.add(ElementFactory.createAttribute("quantity","2"));
   output.add(ElementFactory.createCharacterData("Fabulous Chair"));
   output.add(ElementFactory.createEndElement("item"));
   output.add(ElementFactory.createCharacterData("\n"));

Note:

Be sure you add attributes to an element after you create the start element but before you create the corresponding end element. Otherwise, although your code will compile successfully, you will get a runtime error when you try to run the program. For example, the following code returns an error because the attributes are added to the <item> element after the element has been explicitly ended:

output.add(ElementFactory.createStartElement("item"));
output.add(ElementFactory.createEndElement("item"));
output.add(ElementFactory.createAttribute("id","1234"));
output.add(ElementFactory.createAttribute("quantity","2"));
output.add(ElementFactory.createCharacterData("Fabulous Chair"));
output.add(ElementFactory.createCharacterData("\n"));

Adding an Input Stream to an Output Stream

When creating an XML output stream, you might want to add an existing XML document, such as an XML file or a DOM tree, to the output stream. To do this, you must first convert the XML document to an XML input stream, then use XMLOutputStream.add(XMLInputStream) method to add the input stream to the output stream.

The following example first shows a method called getInputStream() that creates an XML input stream from an XML file and then how to use the method to add the created input stream to an output stream:

  /**
   * Helper method to get a handle on a stream.
   * Takes in a name and returns a stream.  This
   * method uses the InputStreamFactory to create an
   * instance of an XMLInputStream
   * @param name The file to parse
   * @return XMLInputStream the stream to parse
   */

  public XMLInputStream getInputStream(String name)
    throws XMLStreamException, FileNotFoundException
  {
    XMLInputStreamFactory factory = XMLInputStreamFactory.newInstance();
    XMLInputStream stream = factory.newInputStream(new FileInputStream(name));
    return stream;
  }

....

   // create an input stream from each XML file argument then add it to the output
   for (int i=0; i < args.length; i++)
   //
   // Get an input stream and add it to the output stream
   //
   output.add(printer.getInputStream(args[i]));

Printing an Output Stream

Use the XMLOutputStream.flush() method to print out the XML output stream to whatever object you created it from. For example, if you created an XML output stream from a PrintWriter object, then the flush() method prints the stream to the standard output.

Note:

If you are writing to an XMLOutputStream based on a DOM tree, you must execute the flush() method before you can manipulate the DOM.

The following example shows how to print an output stream:

    //
    // Print the results to the screen
    //
    output.flush();

Closing the Output Stream

It is good programming practice to explicitly close the XML output stream when you are finished with it. To close an output stream, use the XMLOutputStream.close() method, as shown in the following example:

// close the output stream
output.close();

This figure shows the hierarchy of the XMLEvent interface and its subinterfaces.

This figure describes the sub-elements of the <xml> element. The sections following this figure describe each element.

Oracle Legal Notices

Copyright Notice

Copyright © 1994-2010, Oracle and/or its affiliates. All rights reserved.

License Restrictions Warranty/Consequential Damages Disclaimer

This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.

Warranty Disclaimer

The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.

Restricted Rights Notice

If this software or related documentation is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065.

Hazardous Applications Notice

This software is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications which may create a risk of personal injury. If you use this software in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of this software. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software in dangerous applications.

Trademark Notice

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Third-Party Content, Products, and Services Disclaimer

This software and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.