這個網上有很多……
上源碼先
- public class ChatLogContentHandler extends DefaultHandler{
- ChatInfo info=null;
- ArrayList<ChatInfo> infos=null;
- String tagName=null;
-
- public ChatLogContentHandler(ArrayList<ChatInfo> infos) {
- super();
- this.infos = infos;
- }
-
- public void startDocument() throws SAXException {
- System.out.println("`````````````````````解析XML```````````````````````````````");
- }
-
- public void endDocument() throws SAXException {
- System.out.println("````````解析完了!!````````");
- }
-
- public void startElement(String namespaceURI, String localName,
- String qName, Attributes attr) throws SAXException {
- //System.out.println("`````````````````````開始啦!!!``````````````````````````"+localName+"~~~~");
- tagName = localName;
- if(tagName.equals("chatinfo")){
- info=new ChatInfo();
- System.out.println("``````````````````````````````新建一個chatinfo對象``````````````````````````");
- }
- }
-
- public void endElement(String namespaceURI, String localName, String qName)
- throws SAXException {
- if(qName.equals("chatinfo")){
- infos.add(info);
- System.out.println("``````````````````````````````put in``````````````````````````");
- }
- tagName = "";
- }
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- String temp=null;
- if (tagName.equals("name")){
- temp = new String(ch, start, length);
- info.setChatName(temp);
- System.out.println("````````set name:"+temp+"````````");
- }
- else if (tagName.equals("time")){
- temp = new String(ch, start, length);
- info.setChatTime(temp);
- System.out.println("````````set time:"+temp+"````````");
- }
- else if (tagName.equals("info")){
- temp = new String(ch, start, length);
- info.setChatString(temp);
- System.out.println("````````set str:"+temp+"````````");
- }
- }
- }
這種接卸方式很簡單,不多解釋
重要的是不用在一開始全部讀入,重要的是隔行解析——這也就是為什麼在前篇一定要按要求存入xml的原因。
如果xml文檔不標准,寫成一行<chatlog><chatinfo><time>12:00</time></chatinfo></chatlog>
解析是會報錯的~