2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 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 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes Pull Parsing versus Push Parsing Comparing StAX to Other JAXP APIs Choosing between Cursor and Iterator APIs Comparing Cursor and Iterator APIs Sun's Streaming XML Parser Implementation Streaming XML Parser Factories Implementation Returning String Representations Building and Running the Cursor Example Using NetBeans IDE Building and Running the Cursor Example Using Ant Instantiating anXMLEventAllocator Building and Running the Cursor-to-Event Example Using NetBeans IDE Building and Running the Cursor-to-Event Example Using Ant Building and Running the Event Example Using NetBeans IDE Building and Running the Event Example Using Ant Implementing theStreamFilter Class Building and Running the Filter Example Using NetBeans IDE Building and Running the Filter Example Using Ant Creating an Event Producer/Consumer Building and Running the Read-and-Write Example Using NetBeans IDE Building and Running the Read-and-Write Example Using Ant 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 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 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 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Using StAXIn 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 ClassesThe StAX factory classes.XMLInputFactory,XMLOutputFactory, andXMLEventFactory, let you define and configureimplementation instances of XML stream reader, stream writer, and event classes. XMLInputFactory ClassTheXMLInputFactory 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:
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
XMLOutputFactory ClassNew 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 ClassNew 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 ErrorsThe StAX specification handles resource resolution, attributes and namespace, and errors and exceptionsas described below. Resource ResolutionTheXMLResolver 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 NamespacesAttributes 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 HandlingAll 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 StreamsAs 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. UsingXMLStreamReaderTheXMLStreamReader 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:
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 NamespacesTheXMLStreamReader.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 MethodsXMLStreamReader 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 anXMLStreamReaderThis 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();}UsingXMLEventReaderTheXMLEventReader 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:
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 AttributesYou 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 NamespacesSimilar 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 StreamsStAX 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. UsingXMLStreamWriterTheXMLStreamWriter interface in the StAX cursor API lets applications write back toan XML stream or create entirely new streams. XMLStreamWriter has methods that letyou:
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> UsingXMLEventWriterTheXMLEventWriter 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 PrefixesStAX 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. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |