Located in the tut-install/javaeetutorial5/examples/stax/readnwrite/ directory, EventProducerConsumer.java demonstrates how to use a StAX parser simultaneously as both a producer and a consumer.
The StAX XMLEventWriter API extends from the XMLEventConsumer interface, and is referred to as an event consumer. By contrast, XMLEventReader is an event producer. StAX supports simultaneous reading and writing, such that it is possible to read from one XML stream sequentially and simultaneously write to another stream.
The Read-and-Write example shows how the StAX producer/consumer mechanism can be used to read and write simultaneously. This example also shows how a stream can be modified and how new events can be added dynamically and then written to a different stream.
The first step is to instantiate an event factory and then create an instance of an event producer/consumer:
XMLEventFactory m_eventFactory = XMLEventFactory.newInstance(); public EventProducerConsumer() { } ... try { EventProducerConsumer ms = new EventProducerConsumer(); XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader( new java.io.FileInputStream(args[0])); XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter( System.out);
The next step is to create an iterator to parse the stream:
while(reader.hasNext()) { XMLEvent event = (XMLEvent)reader.next(); if (event.getEventType() == event.CHARACTERS) { writer.add(ms.getNewCharactersEvent(event.asCharacters())); } else { writer.add(event); } } writer.flush();
The final step is to create a stream writer in the form of a new Character event:
Characters getNewCharactersEvent(Characters event) { if (event.getData().equalsIgnoreCase("Name1")) { return m_eventFactory.createCharacters( Calendar.getInstance().getTime().toString()); } //else return the same event else { return event; } }
When you run the Read-and-Write example, the EventProducerConsumer class is compiled, and the XML stream is parsed as events and written back to STDOUT. The output is the contents of the BookCatalog.xml file described in Example XML Document.
Follow these instructions to build and run the Read-and-Write example on your Application Server instance using the NetBeans IDE.
In NetBeans IDE, select File->Open Project.
In the Open Project dialog, navigate to the tut-install/javaeetutorial5/examples/stax/ directory.
Select the readnwrite folder.
Select the Open as Main Project check box.
Click Open Project.
In the Projects tab, right-click the readnwrite project and select Properties. The Project Properties dialog is displayed.
Enter the following in the Arguments field:
BookCatalog.xml |
Click OK.
Right-click the readnwrite project and select Run.
To compile and run the Read-and-Write example using Ant, in a terminal window, go to the tut-install/javaeetutorial5/examples/stax/readnwrite/ directory and type the following:
ant run-readnwrite |