繼續弄我們聊天的小軟件,嘗試用XML來存儲聊天記錄。
不過最終是放棄了,選擇使用SQLite來存儲記錄,(見http://www.linuxidc.com/Linux/2012-01/50683.htm )這是後話了……
先把XML的存儲與解析的代碼放來把(網上有很多,這兒就是小魏自己復習總結一下)
XMl存儲使用XML序列化對象XmlSerializer,看代碼就知道怎麼寫,很簡單:
- private ChatInfo info;
- public String FirstWriteXml(){
- XmlSerializer serializer = Xml.newSerializer();
- StringWriter writer = new StringWriter();
- try{
- serializer.setOutput(writer);
-
- // <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- serializer.startDocument("UTF-8",true);
- serializer.text("\n");
- // System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> ");
-
- serializer.startTag("","chatlog");
- serializer.text("\n");
-
- serializer.startTag("","chatinfo");
- serializer.text("\n");
- // System.out.println("<chatinfo>");
-
- //<name>小魏</name>
- serializer.text("\t");
- serializer.startTag("","name");
- serializer.text(info.getChatName().toString());
- serializer.endTag("","name");
- serializer.text("\n");
- // System.out.println("<name>"+info.getChatName()+"</name");
-
- //<time>2011-11-27 20:00</time>
- serializer.text("\t");
- serializer.startTag("","time");
- serializer.text(info.getChatTime().toString());
- serializer.endTag("","time");
- serializer.text("\n");
- // System.out.println("<name>"+info.getChatTime()+"</name");
-
- //<info>Hi~~~</info>
- serializer.text("\t");
- serializer.startTag("","info");
- serializer.text(info.getChatString().toString());
- serializer.endTag("","info");
- serializer.text("\n");
- // System.out.println("<name>"+info.getChatString()+"</name");
-
- // </chatinfo>
- serializer.endTag("","chatinfo");
- serializer.text("\n");
- // System.out.println("</chatinfo> ");
-
- serializer.endTag("","chatlog");
- serializer.text("\n");
- // System.out.println("</chatinfo> ");
- serializer.endDocument();
-
-
- return writer.toString();
- }
- catch(Exception e)
- {
- throw new RuntimeException(e);
- }
-
- }
寫出來的效果如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <chatlog>
- <chatinfo>
- <name>小魏</name>
- <time>2011-11-27 20:00</time>
- <info>Hi~~~</info>
- </chatinfo>
- </chatlog>
這裡需要注意,<chatlog>這個標簽是必須的,因為xml裡一定要有一顆主樹,如果有多條記錄,但是沒有最外這層結構,比如下面的例子有多條記錄:
- <?xml version="1.0" encoding="UTF-8"?>
- <chatinfo>
- <name>小魏</name>
- <time>2011-11-27 20:00</time>
- <info>Hi~~~</info>
- </chatinfo>
- <chatinfo>
- <name>我</name>
- <time>2011-11-27 20:01</time>
- <info>你好!</info>
- </chatinfo>
- <chatinfo>
- <name>小魏</name>
- <time>2011-11-27 20:02</time>
- <info>聊天模塊終於搞完了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</info>
- </chatinfo>
- <chatinfo>
- <name>我</name>
- <time>2011-11-27 20:02</time>
- <info>太好啦!</info>
- </chatinfo>
使用SAXParserFactory解析時,解析玩第一條記錄就會停止,而且會報錯: