Android读取XML文件(SAX)

 

package com.xiva.service;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.xiva.domain.Person;

public class XmlContentHandler extends DefaultHandler{

	private List<Person> personList;
	private Person person;
	private String perTag; 
	
	
	public List<Person> getPersonList() {
		return personList;
	}

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		personList = new ArrayList<Person>();
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if(person!=null){
			String data = new String(ch,start,length);
			if("name".equals(perTag))
			{
				person.setPersonName(data);
			}else if("age".equals(perTag))
			{
				person.setAge(data);
			}
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		if("person".equals(localName))
		{
			person = new Person();
			person.setId(new Integer(attributes.getValue("id")));
		}
		perTag = localName;
		
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if("person".equals(localName) && person!=null){
			personList.add(person);
			person = null;
		}
		perTag = null;
	}
}

 package com.xiva.xml;

import java.io.InputStream;
import java.util.List;

import com.xiva.domain.Person;
import com.xiva.service.SAXService;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class XMLActivity extends Activity {
    /** Called when the activity is first created. */
	
	private static final String TAG = "XMLActivity";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView text = (TextView)this.findViewById(R.id.content);
        InputStream iStream = XMLActivity.class.getClassLoader().getResourceAsStream("person.xml");
        List<Person> personList;
		try {
			personList = SAXService.readXML(iStream);
	        StringBuffer strB = new StringBuffer();
	        for(Person person:personList)
	        {
	        	String str = person.toString();
	        	strB.append(str);
	        }
	        text.setText(strB);
		}
	    catch(Exception e){
			Log.i(TAG, "Xml Load failure!");
			Toast.makeText(XMLActivity.this, "Xml Load failure!", 1).show();
			e.printStackTrace();
		}

    }
}

 完整代码见附件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值