这个网上有很多……
上源码先
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>
解析是会报错的~