SAXフィルターのチェーンを設定することをお勧めします。SAXフィルターは、他のSAXハンドラーと同じですが、完了時にイベントを渡すための別のSAXハンドラーがある点が異なります。これらは、XMLストリームへの一連の変換を実行するために頻繁に使用されますが、必要に応じて物事を因数分解するためにも使用できます。
使用している言語については言及していませんが、DefaultHandlerについて言及しているので、Javaを想定します。最初に行うことは、フィルターをコーディングすることです。Javaでは、これを行うには、XMLFilterを実装します(または、より簡単に言えば、XMLFilterImplをサブクラス化します)。
import java.util.Collection;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;
public class TagOneFilter extends XMLFilterImpl {
private Collection<Object> collectionOfStuff;
public TagOneFilter(Collection<Object> collectionOfStuff) {
this.collectionOfStuff = collectionOfStuff;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if ("tagOne".equals(qName)) {
// Interrogate the parameters and update collectionOfStuff
}
// Pass the event to downstream filters.
if (getContentHandler() != null)
getContentHandler().startElement(uri, localName, qName, atts);
}
}
次に、すべてのフィルターをインスタンス化し、それらをチェーン化するメインクラス。
import java.util.ArrayList;
import java.util.Collection;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class Driver {
public static void main(String[] args) throws Exception {
Collection<Object> collectionOfStuff = new ArrayList<Object>();
XMLReader parser = XMLReaderFactory.createXMLReader();
TagOneFilter tagOneFilter = new TagOneFilter(collectionOfStuff);
tagOneFilter.setParent(parser);
TagTwoFilter tagTwoFilter = new TagTwoFilter(collectionOfStuff);
tagTwoFilter.setParent(tagOneFilter);
// Call parse() on the tail of the filter chain. This will finish
// tying the filters together before executing the parse at the
// XMLReader at the beginning.
tagTwoFilter.parse(args[0]);
// Now do something interesting with your collectionOfStuff.
}
}