Android学习笔记之XML解析


这个网上有很多……

上源码先

  1. public class ChatLogContentHandler extends DefaultHandler{  
  2.     ChatInfo info=null;  
  3.     ArrayList<ChatInfo> infos=null;   
  4.     String tagName=null;  
  5.   
  6.     public ChatLogContentHandler(ArrayList<ChatInfo> infos) {  
  7.         super();  
  8.         this.infos = infos;  
  9.     }  
  10.       
  11.     public void startDocument() throws SAXException {  
  12.         System.out.println("`````````````````````解析XML```````````````````````````````");  
  13.     }  
  14.   
  15.     public void endDocument() throws SAXException {  
  16.         System.out.println("````````解析完了!!````````");  
  17.     }  
  18.   
  19.     public void startElement(String namespaceURI, String localName,  
  20.             String qName, Attributes attr) throws SAXException {  
  21.         //System.out.println("`````````````````````开始啦!!!``````````````````````````"+localName+"~~~~");   
  22.         tagName = localName;  
  23.         if(tagName.equals("chatinfo")){  
  24.             info=new ChatInfo();  
  25.             System.out.println("``````````````````````````````新建一个chatinfo对象``````````````````````````");  
  26.         }  
  27.     }  
  28.   
  29.     public void endElement(String namespaceURI, String localName, String qName)  
  30.             throws SAXException {  
  31.         if(qName.equals("chatinfo")){  
  32.             infos.add(info);  
  33.             System.out.println("``````````````````````````````put in``````````````````````````");  
  34.         }  
  35.         tagName = "";  
  36.     }  
  37.     public void characters(char[] ch, int start, int length)  
  38.             throws SAXException {  
  39.         String temp=null;  
  40.         if (tagName.equals("name")){  
  41.             temp = new String(ch, start, length);  
  42.             info.setChatName(temp);  
  43.             System.out.println("````````set name:"+temp+"````````");  
  44.         }  
  45.         else if (tagName.equals("time")){  
  46.             temp = new String(ch, start, length);  
  47.             info.setChatTime(temp);  
  48.             System.out.println("````````set time:"+temp+"````````");  
  49.         }  
  50.         else if (tagName.equals("info")){  
  51.             temp = new String(ch, start, length);  
  52.             info.setChatString(temp);  
  53.             System.out.println("````````set str:"+temp+"````````");  
  54.         }     
  55.     }  
  56. }  
这种接卸方式很简单,不多解释

重要的是不用在一开始全部读入,重要的是隔行解析——这也就是为什么在前篇一定要按要求存入xml的原因。

如果xml文档不标准,写成一行<chatlog><chatinfo><time>12:00</time></chatinfo></chatlog>

解析是会报错的~

相关内容