question about two SAXParser in a class
I have two sax parser as follows:
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
SAXParser parser1 = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new File("G:\\Documents\\posts.xml"), this);
parser1.parse(new File("G:\\Documents\\comments.xml"), this);
} catch (Exception ex) {
ex.printStackTrace();
}
the question is that when the handler startEl开发者_JAVA百科ement is called, how do I check whether this is from parser1 or parser2? I am assuming that uri and localName is used, but how?
I'd suggest using two handlers. As a trivial example (you'll have to fill in the details):
class SaxClass {
Handler h1;
Handler h2;
//...stuff
method() {
h1 = new Handler();
h2 = new Handler();
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
SAXParser parser1 = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new File("G:\\Documents\\posts.xml"), h1);
parser1.parse(new File("G:\\Documents\\comments.xml"), h2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
class Handler extends DefaultHandler {
// Implementation
}
}
It doesn't look like there's a way to find the parser that generated the event.
If you want to differentiate two content handlers based on the same class, you should construct two instances of the content handler, and pass a constructor parameter to differentiate the two, (or setter method). Save that information in the content handler as fields, and refer to them to differentiate.
精彩评论