SAX是一种事件驱动的XMLAPI,特点:
分析能即刻开始,并可随时结束
所占内存小,适合大型文档
示例xml文件如下:
<?xml version="1.0" encoding="utf-8"?> <persons> <person name="Claw" age="24"> <weight>70kg</weight> <height>173cm</height> </person> <person name="Nancy" age="25"> <weight>54kg</weight> <height>172cm</height> </person> <person name="dearcloud" age="27"> <weight>55kg</weight> <height>172cm</height> </person> </persons>
使用方法:扩展defaultHandler实现解析细节,重写主要的五个方法,实例代码如下:
package com.example.xmlparser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SaxHandler extends DefaultHandler { HashMap<String,String> map; List<Map<String,String>> list; private String curTag;//当前标签 private String curValue;//当前值 private String nodeName;//当前节点名 public SaxHandler(String node) { nodeName=node; } public List<Map<String,String>> getList() { return list; } @Override public void startDocument() throws SAXException { list=new ArrayList<Map<String,String>>(); super.startDocument(); } @Override public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException { if(qName.equals(nodeName)) map=new HashMap<String,String>(); if(attributes!=null&&map!=null) for(int i=0;i<attributes.getLength();i++){ map.put(attributes.getQName(i),attributes.getValue(i)); } curTag=qName; super.startElement(uri,localName,qName,attributes); } @Override public void characters(char[] ch,int start,int length) throws SAXException { if(curTag!=null&&map!=null){ curValue=new String(ch,start,length); if(curValue!=null&&!curValue.trim().equals("")){ map.put(curTag,curValue); } } super.characters(ch,length); } @Override public void endElement(String uri,String qName) throws SAXException { if(nodeName.equals(qName)) list.add(map); super.endElement(uri,qName); } @Override public void endDocument() throws SAXException { super.endDocument(); } }
有了这个DefaultHandler就可以解析了,解析类的静态方法如下:
public static List<Map<String,String>> parseSax(InputStream is,String node){ try { SAXParserFactory saxPF=SAXParserFactory.newInstance(); SAXParser saxParser=saxPF.newSAXParser(); SaxHandler saxHandler=new SaxHandler(node); saxParser.parse(is,saxHandler); return saxHandler.getList(); } catch (Exception e) { Log.e("parse error",e.getMessage()+e.getLocalizedMessage()); return null; }finally{ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } }
如此,就可以用这个方法来解析xml文件了,使用示例如下:
String nodeName="person"; InputStream is=getResources().openRawResource(R.raw.parsed); List<Map<String,String>> list=ParserUtil.parseSax(is,nodeName);原文链接:https://www.f2er.com/xml/298360.html