| |
33. 8. 1. 实现EventFilter , StreamFilter |
|
import java.io.File;
import java.io.FileInputStream;
import javax.xml.stream.EventFilter;
import javax.xml.stream.StreamFilter;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
public class EventFilterExample {
public static void main(String[] args) throws Exception {
File file = new File("text.xml");
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventReader reader = inputFactory.createXMLEventReader(new FileInputStream(file));
System.out.println("Unfiltered Count = " + countEvents(reader));
reader = inputFactory.createXMLEventReader(new FileInputStream(file));
EventFilter filter = new ElementOnlyFilter();
reader = inputFactory.createFilteredReader(reader, filter);
System.out.println("Filtered Count = " + countEvents(reader));
}
private static int countEvents(XMLEventReader reader) throws XMLStreamException {
int counter = 0;
while (reader.hasNext()) {
reader.next();
counter++;
}
return counter;
}
}
class ElementOnlyFilter implements EventFilter, StreamFilter {
public boolean accept(XMLEvent event) {
return accept(event.getEventType());
}
public boolean accept(XMLStreamReader reader) {
return accept(reader.getEventType());
}
private boolean accept(int eventType) {
return eventType == XMLStreamConstants.START_ELEMENT
|| eventType == XMLStreamConstants.END_ELEMENT;
}
}
|
|
33. 8. StreamFilter | | 33. 8. 1. | 实现EventFilter , StreamFilter | | |
|