这两天继续弄我们聊天的小软件,尝试用XML来存储聊天记录。
不过最终是放弃了,选择使用SQLite来存储记录,这是后话了……
先把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>
<?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>