sax解析其实是很简单的,主要代码如下 :
public void parseXml(){
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser;
SAXPraserHelper helper=null;
try{
parser=factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
helper=new SAXPraserHelper();
reader.setContentHandler(helper);
InputStream stream=getResources().openRawResource(R.raw.link);
InputSource source=new InputSource(stream);
reader.parse(source);
}catch (ParserConfigurationException e){
Log.v("====","ParserConfigurationException");
}catch (SAXException e){
Log.v("====","SAXException");
}catch (IOException e){
Log.v("====","IOException");
}
}
在解析的时候需要一个handler 于是自己定义了一个handler如下
public class SAXPraserHelper extends DefaultHandler{
private static final String TAG="";
List<Link> links;
Link link;
int currentState=0;
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(localName.equals("a")){
links.add(link);
}
Log.v(TAG,links.toString());
}
@Override
public void startDocument() throws SAXException {
links=new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
link=new Link();
if(localName.equals("a")){
for(int i=0;i<attributes.getLength();i++){
if(attributes.getLocalName(i).equals("href")){
link.setHref(attributes.getValue(i));
}else if(attributes.getLocalName(i).equals("name")){
link.setName(attributes.getValue(i));
}
}
currentState=1;
return;
}
currentState=0;
return;
}
}