Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

Why StAX?

Streaming versus DOM

Pull Parsing versus Push Parsing

StAX Use Cases

Comparing StAX to Other JAXP APIs

StAX API

Cursor API

Iterator API

Iterator Event Types

Example of Event Mapping

Choosing between Cursor and Iterator APIs

Development Goals

Comparing Cursor and Iterator APIs

Using StAX

StAX Factory Classes

XMLInputFactory Class

XMLOutputFactory Class

XMLEventFactory Class

Resources, Namespaces, and Errors

Resource Resolution

Attributes and Namespaces

Error Reporting and Exception Handling

Reading XML Streams

UsingXMLStreamReader

UsingXMLEventReader

Writing XML Streams

UsingXMLStreamWriter

UsingXMLEventWriter

Sun's Streaming XML Parser Implementation

Reporting CDATA Events

Streaming XML Parser Factories Implementation

Example Code

Example Code Organization

Example XML Document

Cursor Example

Stepping through Events

Returning String Representations

Building and Running the Cursor Example Using NetBeans IDE

Building and Running the Cursor Example Using Ant

Cursor-to-Event Example

Instantiating anXMLEventAllocator

Creating an Event Iterator

Creating the Allocator Method

Building and Running the Cursor-to-Event Example Using NetBeans IDE

Building and Running the Cursor-to-Event Example Using Ant

Event Example

Creating an Input Factory

Creating an Event Reader

Creating an Event Iterator

Getting the Event Stream

Returning the Output

Building and Running the Event Example Using NetBeans IDE

Building and Running the Event Example Using Ant

Filter Example

Implementing theStreamFilter Class

Creating an Input Factory

Creating the Filter

Capturing the Event Stream

Filtering the Stream

Returning the Output

Building and Running the Filter Example Using NetBeans IDE

Building and Running the Filter Example Using Ant

Read-and-Write Example

Creating an Event Producer/Consumer

Creating an Iterator

Creating a Writer

Returning the Output

Building and Running the Read-and-Write Example Using NetBeans IDE

Building and Running the Read-and-Write Example Using Ant

Writer Example

Creating the Output Factory

Creating a Stream Writer

Writing the Stream

Returning the Output

Building and Running the Writer Example Using NetBeans IDE

Building and Running the Writer Example Using Ant

Further Information about StAX

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Using StAX

In general, StAX programmers create XML stream readers, writers, and events by usingtheXMLInputFactory,XMLOutputFactory, andXMLEventFactory classes. Configuration is done by setting properties onthe factories, whereby implementation-specific settings can be passed to the underlying implementation usingthesetProperty method on the factories. Similarly, implementation-specific settings can be queried usingthegetProperty factory method.

TheXMLInputFactory,XMLOutputFactory, andXMLEventFactory classes are described below, followed by discussions of resourceallocation, namespace and attribute management, error handling, and then finally reading and writingstreams using the cursor and iterator APIs.

StAX Factory Classes

The StAX factory classes.XMLInputFactory,XMLOutputFactory, andXMLEventFactory, let you define and configureimplementation instances of XML stream reader, stream writer, and event classes.

XMLInputFactory Class

TheXMLInputFactory class lets you configure implementation instances of XML stream reader processorscreated by the factory. New instances of the abstract classXMLInputFactory are created bycalling thenewInstance method on the class. The static methodXMLInputFactory.newInstance is thenused to create a new factory instance.

Deriving from JAXP, theXMLInputFactory.newInstance method determines the specificXMLInputFactory implementation class to loadby using the following lookup procedure:

  1. Use thejavax.xml.stream.XMLInputFactory system property.

  2. Use thelib/xml.stream.properties file in the J2SE Java Runtime Environment (JRE) directory.

  3. Use the Services API, if available, to determine the classname by looking in theMETA-INF/services/javax.xml.stream.XMLInputFactory files in JAR files available to the JRE.

  4. Use the platform defaultXMLInputFactory instance.

After getting a reference to an appropriateXMLInputFactory, an application can use thefactory to configure and create stream instances.Table 18-4 lists the properties supported byXMLInputFactory. See the StAX specification for a more detailed listing.

Table 18-4javax.xml.stream.XMLInputFactory Properties

Property

Description

isValidating

Turns on implementation-specific validation.

isCoalescing

(Required)Requires the processor to coalesce adjacent character data.

isNamespaceAware

Turns off namespace support. All implementationsmust support namespaces. Support for non-namespace-aware documents is optional.

isReplacingEntityReferences

(Required) Requires the processor toreplace internal entity references with their replacement value and report them as characters orthe set of events that describe the entity.

isSupportingExternalEntities

(Required) Requires the processor toresolve external parsed entities.

reporter

(Required) Sets and gets the implementation of theXMLReporter interface.

resolver

(Required) Setsand gets the implementation of theXMLResolver interface.

allocator

(Required) Sets and gets the implementationof theXMLEventAllocator interface.

XMLOutputFactory Class

New instances of the abstract classXMLOutputFactory are created by calling thenewInstancemethod on the class. The static methodXMLOutputFactory.newInstance is then used to create anew factory instance. The algorithm used to obtain the instance is the sameas forXMLInputFactory but references thejavax.xml.stream.XMLOutputFactory system property.

XMLOutputFactory supports only one property,javax.xml.stream.isRepairingNamespaces. This property is required, and its purposeis to create default prefixes and associate them with Namespace URIs. See theStAX specification for more information.

XMLEventFactory Class

New instances of the abstract classXMLEventFactory are created by calling thenewInstancemethod on the class. The static methodXMLEventFactory.newInstance is then used to create anew factory instance. This factory references thejavax.xml.stream.XMLEventFactory property to instantiate thefactory. The algorithm used to obtain the instance is the same as forXMLInputFactory andXMLOutputFactory but references thejavax.xml.stream.XMLEventFactory system property.

There are no default properties forXMLEventFactory.

Resources, Namespaces, and Errors

The StAX specification handles resource resolution, attributes and namespace, and errors and exceptionsas described below.

Resource Resolution

TheXMLResolver interface provides a means to set the method that resolves resourcesduring XML processing. An application sets the interface onXMLInputFactory, which then setsthe interface on all processors created by that factory instance.

Attributes and Namespaces

Attributes are reported by a StAX processor using lookup methods and strings inthe cursor interface, andAttribute andNamespace events in the iterator interface.Note here that namespaces are treated as attributes, although namespaces are reported separatelyfrom attributes in both the cursor and iterator APIs. Note also that namespaceprocessing is optional for StAX processors. See the StAX specification for complete information aboutnamespace binding and optional namespace processing.

Error Reporting and Exception Handling

All fatal errors are reported by way of thejavax.xml.stream.XMLStreamException interface. Allnonfatal errors and warnings are reported using thejavax.xml.stream.XMLReporter interface.

Reading XML Streams

As described earlier in this chapter, the way you read XML streamswith a StAX processor, and what you get back, vary significantly depending onwhether you are using the StAX cursor API or the event iterator API.The following two sections describe how to read XML streams with each ofthese APIs.

UsingXMLStreamReader

TheXMLStreamReader interface in the StAX cursor API lets you read XML streamsor documents in a forward direction only, one item in the infoset ata time. The following methods are available for pulling data from the streamor skipping unwanted events:

  • Get the value of an attribute

  • Read XML content

  • Determine whether an element has content or is empty

  • Get indexed access to a collection of attributes

  • Get indexed access to a collection of namespaces

  • Get the name of the current event (if applicable)

  • Get the content of the current event (if applicable)

Instances ofXMLStreamReader have at any one time a single current event onwhich its methods operate. When you create an instance ofXMLStreamReader on astream, the initial current event is theSTART_DOCUMENT state. TheXMLStreamReader.next method canthen be used to step to the next event in the stream.

Reading Properties, Attributes, and Namespaces

TheXMLStreamReader.next method loads the properties of the next event in the stream.You can then access those properties by calling theXMLStreamReader.getLocalName andXMLStreamReader.getText methods.

When theXMLStreamReader cursor is over aStartElement event, it reads thename and any attributes for the event, including the namespace. All attributes foran event can be accessed using an index value, and can also belooked up by namespace URI and local name. Note, however, that only thenamespaces declared on the currentStartEvent are available; previously declared namespaces are notmaintained, and redeclared namespaces are not removed.

XMLStreamReader Methods

XMLStreamReader provides the following methods for retrieving information about namespaces and attributes:

int getAttributeCount();String getAttributeNamespace(int index);String getAttributeLocalName(int index);String getAttributePrefix(int index);String getAttributeType(int index);String getAttributeValue(int index);String getAttributeValue(String namespaceUri, String localName);boolean isAttributeSpecified(int index);

Namespaces can also be accessed using three additional methods:

int getNamespaceCount();String getNamespacePrefix(int index);String getNamespaceURI(int index);
Instantiating anXMLStreamReader

This example, taken from the StAX specification, shows how to instantiate an inputfactory, create a reader, and iterate over the elements of an XML stream:

XMLInputFactory f = XMLInputFactory.newInstance();XMLStreamReader r = f.createXMLStreamReader( ... );while(r.hasNext()) {    r.next();}
UsingXMLEventReader

TheXMLEventReader API in the StAX event iterator API provides the means tomap events in an XML stream to allocated event objects that can befreely reused, and the API itself can be extended to handle custom events.

XMLEventReader provides four methods for iteratively parsing XML streams:

  • next: Returns the next event in the stream

  • nextEvent: Returns the next typed XMLEvent

  • hasNext: Returns true if there are more events to process in the stream

  • peek: Returns the event but does not iterate to the next event

For example, the following code snippet illustrates theXMLEventReader method declarations:

package javax.xml.stream;import java.util.Iterator;public interface XMLEventReader extends Iterator {    public Object next();    public XMLEvent nextEvent() throws XMLStreamException;    public boolean hasNext();    public XMLEvent peek() throws XMLStreamException;    ...}

To read all events on a stream and then print them, youcould use the following:

while(stream.hasNext()) {    XMLEvent event = stream.nextEvent();    System.out.print(event);}
Reading Attributes

You can access attributes from their associatedjavax.xml.stream.StartElement, as follows:

public interface StartElement extends XMLEvent {    public Attribute getAttributeByName(QName name);    public Iterator getAttributes();}

You can use thegetAttributes method on theStartElement interface to useanIterator over all the attributes declared on thatStartElement.

Reading Namespaces

Similar to reading attributes, namespaces are read using anIterator created bycalling thegetNamespaces method on theStartElement interface. Only the namespace for the currentStartElement is returned, and an application can get the current namespace context byusingStartElement.getNamespaceContext.

Writing XML Streams

StAX is a bidirectional API, and both the cursor and event iterator APIshave their own set of interfaces for writing XML streams. As withthe interfaces for reading streams, there are significant differences between the writer APIs forcursor and event iterator. The following sections describe how to write XML streamsusing each of these APIs.

UsingXMLStreamWriter

TheXMLStreamWriter interface in the StAX cursor API lets applications write back toan XML stream or create entirely new streams. XMLStreamWriter has methods that letyou:

  • Write well-formed XML

  • Flush or close the output

  • Write qualified names

Note thatXMLStreamWriter implementations are not required to perform well-formedness or validity checkson input. While some implementations may perform strict error checking, others may not.The rules you implement are applied to properties defined in theXMLOutputFactory class.

ThewriteCharacters method is used to escape characters such as&,<,>, and". Binding prefixes can be handled by either passing the actual value forthe prefix, by using thesetPrefix method, or by setting the property fordefaulting namespace declarations.

The following example, taken from the StAX specification, shows how to instantiate anoutput factory, create a writer, and write XML output:

XMLOutputFactory output = XMLOutputFactory.newInstance();XMLStreamWriter writer = output.createXMLStreamWriter( ... );writer.writeStartDocument();writer.setPrefix("c","http://c");writer.setDefaultNamespace("http://c");writer.writeStartElement("http://c","a");writer.writeAttribute("b","blah");writer.writeNamespace("c","http://c");writer.writeDefaultNamespace("http://c");writer.setPrefix("d","http://c");writer.writeEmptyElement("http://c","d");writer.writeAttribute("http://c","chris","fry");writer.writeNamespace("d","http://c");writer.writeCharacters("Jean Arp");writer.writeEndElement();writer.flush();

This code generates the following XML (new lines are non-normative):

<?xml version=’1.0’ encoding=’utf-8’?><a b="blah" xmlns:c="http://c" xmlns="http://c"><d:d d:chris="fry" xmlns:d="http://c"/>Jean Arp</a>
UsingXMLEventWriter

TheXMLEventWriter interface in the StAX event iterator API lets applications write backto an XML stream or create entirely new streams. This API can beextended, but the main API is as follows:

public interface XMLEventWriter {    public void flush() throws XMLStreamException;    public void close() throws XMLStreamException;    public void add(XMLEvent e) throws XMLStreamException;    // ... other methods not shown.}

Instances ofXMLEventWriter are created by an instance ofXMLOutputFactory. Stream events areadded iteratively, and an event cannot be modified after it has been addedto an event writer instance.

Attributes, Escaping Characters, Binding Prefixes

StAX implementations are required to buffer the lastStartElement until an event otherthanAttribute orNamespace is added or encountered in the stream. This meansthat when you add anAttribute or aNamespace to a stream,it is appended the currentStartElement event.

You can use theCharacters method to escape characters like&,<,>, and".

ThesetPrefix(...) method can be used to explicitly bind a prefix for useduring output, and thegetPrefix(...) method can be used to get the currentprefix. Note that by default,XMLEventWriter adds namespace bindings to its internalnamespace map. Prefixes go out of scope after the correspondingEndElement for the eventin which they are bound.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp