1.SAX解析XML文档的过程:
1>创建事件处理程序;
2>创建SAX解析器;
3>将事件处理程序分配给解析器
4>将文档进行解析,将每个事件发送给处理程序;
1>创建事件处理程序;
2>创建SAX解析器;
3>将事件处理程序分配给解析器
4>将文档进行解析,将每个事件发送给处理程序;
如:
SAXParserFactory factory=SAXParserFactory.newInstance(); SAXParser parser=factory.newSAXParser(); XMLReader reader=parser.getXMLReader(); //handler是一个ContentHandler实现类的实例 reader.setContentHandler(handler);
2.实现ContentHandler接口:
创建一个类继承自ContentHandler类,并主要实现startElement,endElement,characters等方法。如:
public class MyHandler implements ContentHandler{ boolean flag_lat,flag_lng,flag_location,flag_address; String str_address,str_lat,str_lng; public String getData() { return "地址: " + str_address + "\n经度: " + str_lng + "\n纬度: " + str_lat; } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (localName.equals("formatted_address")) { flag_address = true; } if(localName.equals("location")) { flag_location=true; } if(flag_location==true) { if(localName.equals("lat")) { flag_lat=true; } if(localName.equals("lng")) { flag_lng=true; } } } public void characters(char[] ch, int start, int length) throws SAXException { if(flag_lat == true) { str_lat=new String(ch,start,length); } if (flag_address == true) { str_address = new String(ch, start, length); } if(flag_lng== true) { str_lng=new String(ch,start,length); } } public void endElement(String uri, String localName, String qName) throws SAXException { if (localName.equals("lat")) { flag_lat=false; } if(localName.equals("lng")) { flag_lng=false; } if(localName.equals("location")) { flag_location=false; } if (localName.equals("formatted_address")) { flag_address = false; } } }