XMLEventReader and XMLEventWriter for Stax XML parser : Stream Parser « XML « Java Tutorial






import java.util.Calendar;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.XMLEvent;


class StaxEvent {
    XMLEventFactory m_eventFactory = XMLEventFactory.newInstance();

    public static void main(String[] args) throws Exception {
            StaxEvent ms = new StaxEvent();

            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(new java.io.FileInputStream("yourXML.xml"));
            XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(System.out);

            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();
    }

    private Characters getNewCharactersEvent(Characters event) {
        if (event.getData().equalsIgnoreCase("Name1")) {
            return m_eventFactory.createCharacters(Calendar.getInstance().getTime().toString());
        } else {
            return event;
        }
    }
}








33.8.Stream Parser
33.8.1.StAX is a technology similar to SAX.
33.8.2.XMLEventReader Demo
33.8.3.XMLStreamWriter Demo
33.8.4.Using XMLEventFactory to create xml document
33.8.5.Streaming XML Parser: Stax Event
33.8.6.Streaming XML Parser: Stax Event Filter
33.8.7.XMLEventReader and XMLEventWriter for Stax XML parser
33.8.8.Using XMLStreamWriter to create XML file
33.8.9.STAX cursor
33.8.10.Catch XMLStreamException
33.8.11.Get information as an XMLEvent object when using cursor approach
33.8.12.Stax XML iterator read
33.8.13.Stax XML cursor read
33.8.14.Read Xml from StreamSource
33.8.15.Validate Stax