StaxEvent.java Source code

Java tutorial

Introduction

Here is the source code for StaxEvent.java

Source

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