This is code_1:
public class SAXContenHandler extends DefaultHandler {
private Hotel hotel;
private String preTag = null;
private String keyWord;
public SAXContenHandler(String key){
keyWord = key;
}
public SAXContenHandler(){
}
public void characters(char[] ch, int start,int length) throws SAXException{
if(preTag != null){
try{
String chars = new String(ch,start,length);
switch(preTag){
case "hotel_id":
hotel.setId(chars);
break;
case "name_tw":
if(chars.indexOf("旅館")==-1) **<---------Here**
hotel = null;
else
hotel.setNameTw(chars);
break;
case "name_en":
hotel.setNameEn(chars);
break;
}
}
catch(Exception e){
}
}
}
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if(localName.equals("hotel")){
hotel = new Hotel();
}
preTag = localName;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(hotel != null){
if(localName.equals("hotel")){
hotels.add(hotel);
hotel = null;
}
}
preTag = null;
}
}
Result:

And this is code_2:
public class SAXContenHandler extends DefaultHandler {
private Hotel hotel;
private String preTag = null;
private String keyWord;
public SAXContenHandler(String key){
keyWord = key;
}
public SAXContenHandler(){
}
public void characters(char[] ch, int start,int length) throws SAXException{
if(preTag != null){
try{
String chars = new String(ch,start,length);
switch(preTag){
case "hotel_id":
hotel.setId(chars);
break;
case "name_tw":
if(chars.indexOf(keyWord)==-1)**<------HERE**
hotel = null;
else
hotel.setNameTw(chars);
break;
case "name_en":
hotel.setNameEn(chars);
break;
}
}
catch(Exception e){
}
}
}
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if(localName.equals("hotel")){
hotel = new Hotel();
}
preTag = localName;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(hotel != null){
if(localName.equals("hotel")){
hotels.add(hotel);
hotel = null;
}
}
preTag = null;
}
}
Result:

situation 1:
I use
String key = "旅館";
SAXContenHandler handler = new SAXContenHandler(key);
before using code_2.
situation 2:
I use
SAXContenHandler handler = new SAXContenHandler();
before using code_1.
When I use the method: characters()in situation1 and in situation2, I think the result should be the same.
BUT, this is not so.
What is the reason why situation1 and situation2 are so different?
ABOUT! I forgot to say: I want to use the keyword to filter xml data, but this is my first time I use the xml file in android, so I'm not sure if the idea in the code is correct or you can tell me the right idea, this will be useful for me, thanks.