Java Reference
In-Depth Information
Filtering Data in an XML Stream
Problem
You want to maximize efficiency while reading an XML file by filtering the StAX event
stream to leave out events you're not interested in.
Solution
For data streams, just implement the javax.xml.stream.StreamFilter interface and pass
it to the XMLStreamReader constructor along with your file input stream. Wrap your
XMLStreamReader with a FilteredReader . For event streams, wrap your XMLEventReader
with an EventFilter implementation. You might recognize the Decorator design pattern at
work here, as is typical of the standard Java I/O libraries.
The previous StAX cursor example was fine, but could be more efficient. It captured a consid-
erable number of events you weren't interested in receiving. You can use a filter to improve
the performance and clarity of your applications by instructing the parser to make available
only those events you're interested in hearing about.
When working with cursors, all you have to do is implement the StreamFilter interface's
accept method. Then construct your XMLStreamReader with it. When working with an
EventReader , all you have to do is implement the EventFilter interface's accept method.
Example 3-4 shows how it's done.
Example3-4.StaxFiltered.java
package com.sc.ch02.stax;
import static java.lang.System.out;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.stream.*;
import javax.xml.stream.events.XMLEvent;
public class StaxFiltered {
private static final String fdb = "path/ch02/Catalog.xml";
private Map<String, Double> expensiveBooks;
Search WWH ::




Custom Search