【Android学习笔记】XML解析

这个网上有很多……

上源码先

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>

解析是会报错的~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值