这是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(key == null)
hotel.setNameTw(chars);
else*/
if(chars.indexOf("旅館")==-1) **<---------Here**
hotel = null;
else
hotel.setNameTw(chars);
break;
case "name_en":
hotel.setNameEn(chars);
break;
}
}
catch(Exception e){
//Log.d(TAG,"SAXContentHandler",e);
}
}
}
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if(localName.equals("hotel")){
hotel = new Hotel();
}
preTag = localName;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO Auto-generated method stub
if(hotel != null){
if(localName.equals("hotel")){
hotels.add(hotel);
hotel = null;
//i++;
}
}
preTag = null;
}
}
结果:
这是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(key == null)
hotel.setNameTw(chars);
else*/
if(chars.indexOf(keyWord)==-1)**<------HERE**
hotel = null;
else
hotel.setNameTw(chars);
break;
case "name_en":
hotel.setNameEn(chars);
break;
}
}
catch(Exception e){
//Log.d(TAG,"SAXContentHandler",e);
}
}
}
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if(localName.equals("hotel")){
hotel = new Hotel();
}
preTag = localName;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO Auto-generated method stub
if(hotel != null){
if(localName.equals("hotel")){
hotels.add(hotel);
hotel = null;
//i++;
}
}
preTag = null;
}
}
结果:
情况1:
我用
String key = "旅館";
SAXContenHandler handler = new SAXContenHandler(key);
使用code_2之前。
情况2:
我用
SAXContenHandler handler = new SAXContenHandler();
在使用code_1之前。
当我在情境1和情境2中使用方法:characters()
时,我认为结果应该是相同的。
但是!!!它不是。
为什么情况1和情况2如此不同?
哦!我忘了说:我想用关键字来过滤xml数据,但这是我第一次在android中使用xml文件,所以我不确定代码中的想法是否正确,或者你可以告诉我正确的想法,这对我很有帮助,谢谢。