在编写解析代码的时候发现,我在这方面掌握的还不够扎实。
出现的问题是,在一个元素中“<item></item>”,里面的数据总是得不到,经过测试发现,
public void characters(char[] ch, int start, int length)
执行了两次。
具体描述如下:
由于第二次得到的都是空值,所以我得不到数据。
解决的办法是添加一个判断,一个布尔变量。在元素开始和结束的时候,设定布尔值。
public class MySaxParseHandler extends DefaultHandler {
APN apn;
boolean flag = true;
String string;
public MySaxParseHandler(APN apn) {
this.apn = apn;
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
System.out.println("文档解析开始");
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
System.out.println("文档解析结束");
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
System.out.println("元素开始" + localName);
flag = true;
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
System.out.println("元素结束" + localName);
flag = false;
if ("name".equals(localName)) {
apn.setName(string);
} else if ("apn".equals(localName)) {
apn.setApn(string);
} else if ("mcc".equals(localName)) {
apn.setMcc(string);
} else if ("mnc".equals(localName)) {
apn.setMnc(string);
} else if ("numeric".equals(localName)) {
apn.setNumeric(string);
} else if ("proxy".equals(localName)) {
apn.setProxy(string);
} else if ("port".equals(localName)) {
apn.setPort(string);
} else if ("mmsproxy".equals(localName)) {
apn.setMmsproxy(string);
} else if ("mmsport".equals(localName)) {
apn.setMmsport(string);
} else if ("insert_by".equals(localName)) {
apn.setInsert_by(string);
} else if ("authtype".equals(localName)) {
apn.setAuthtype(string);
} else if ("current".equals(localName)) {
apn.setCurrent(string);
} else if ("type".equals(localName)) {
apn.setType(string);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
if (flag) {
string = new String(ch, start, length);
}
}
}
数据模型
public class APN {
String name;
String apn;
String mcc;
String mnc;
String numeric;
String user;
String password;
String server;
String proxy;
String port;
String mmsport;
String mmsproxy;
String mmsprotocol;
String mmsc;
String insert_by;
String authtype;
String current;
String type;
public String getName() {
return name;
}
public void setName(String name) {
System.out.println(name);
this.name = name;
}
//---很多的getter和setter,省去了。
}
外部调用事例,(抛异常)
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader reader;
reader = factory.newSAXParser().getXMLReader();
MySaxParseHandler handler = new MySaxParseHandler(apn);
reader.setContentHandler(handler);
reader.parse(new InputSource(getResources().openRawResource(R.raw.apn)));
System.out.println(apn.toString());