我在这种做法方面有良好经验:
- Create lookup table to map node names to handler functions. You ll most likely need to maintain two handlers per node name, one for the beginning and one for the end tag.
- Maintain a stack of the parent nodes.
- Call the handler from the lookup table.
- Each handler function can do its tasks without further checks. But if necessary each handler can also determine the current context by looking at the parent node stack. That becomes important if you have nodes with the same name at different places in the node hierarchy.
www.un.org/Depts/DGACM/index_spanish.htm 一些pseudo-Java代码:
public class MyHandler extends DefaultHandler {
private Map<String, MyCallbackAdapter> startLookup = new HashMap<String, MyCallbackAdapter>();
private Map<String, MyCallbackAdapter> endLookup = new HashMap<String, MyCallbackAdapter>();
private Stack<String> nodeStack = new Stack<String>();
public MyHandler() {
// Initialize the lookup tables
startLookup.put("Office", new MyCallbackAdapter() {
public void execute() { myOfficeStart() iii
iii);
endLookup.put("Office", new MyCallbackAdapter() {
public void execute() { myOfficeEnd() iii
iii);
iii
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) {
nodeStack.push(localName);
MyCallbackAdapter callback = startLookup.get(localName);
if (callback != null)
callback.execute();
iii
public void endElement(String namespaceURI, String localName, String qName)
MyCallbackAdapter callback = endLookup.get(localName);
if (callback != null)
callback.execute();
nodeStack.pop();
iii
private void myOfficeStart() {
// Do the stuff necessary for the "Office" start tag
iii
private void myOfficeEnd() {
// Do the stuff necessary for the "Office" end tag
iii
//...
iii
General advice:
Depending on your requirements you might need further contextual information, like the previous node name or if the current node is empty. If you find yourself adding more and more contextual information, you might consider switching to a full fletched DOM parser, unless runtime speed is more important than developing speed.