歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android學習筆記之XML解析

Android學習筆記之XML解析

日期:2017/3/1 10:41:33   编辑:Linux編程

這個網上有很多……

上源碼先

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

重要的是不用在一開始全部讀入,重要的是隔行解析——這也就是為什麼在前篇一定要按要求存入xml的原因。

如果xml文檔不標准,寫成一行<chatlog><chatinfo><time>12:00</time></chatinfo></chatlog>

解析是會報錯的~

Copyright © Linux教程網 All Rights Reserved