安卓sax解析xml

新建raw文件夹下的xml文件做为解析测试的xml

dashu.xml

<?xml version="1.0" encoding="UTF-8"?>
<user-list>
	<user id="1">
		<name>大树</name>
		<age>22</age>
	</user>
	
	<user id="2">
		<name>梅子</name>
		<age>28</age>
	</user>

	<user id="3">
		<name>爸爸</name>
		<age>48</age>
	</user>
	
	<user id="4">
		<name>妈妈</name>
		<age>48</age>
	</user>
</user-list>


 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>


 

items.xml是listview的item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text=""
        android:textSize="18sp" 
        android:textColor="@android:color/holo_blue_dark"/>


    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text=""
        android:textSize="18sp" 
        android:textColor="@android:color/holo_blue_dark"/>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text=""
        android:textSize="18sp"
        android:textColor="@android:color/holo_blue_dark" />

</LinearLayout>


MyHandler继承DefaultHandler解析工具类

package com.example.dashu_saxxml;

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

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.R.integer;

public class MyHandler extends DefaultHandler {
	private HashMap<String, String> map = null;// 存储单个解析的完整对象
	List<HashMap<String, String>> list = null;// 存储所以的解析对象
	private String currentTag = null;// 正在解析元素的标签
	private String currentValue = null;// 正在解析元素的值
	private String nodeName = null;// 当前解析节点名称

	public MyHandler(String nodeName) {
		super();
		this.nodeName = nodeName;
	}

	public List<HashMap<String, String>> getList() {
		return list;
	}

	/**
	 * xml文件开始解析时候调用的方法
	 * */
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		list = new ArrayList<HashMap<String, String>>();
		super.startDocument();
	}

	/**
	 * 解析到节点开头调用方法<name>
	 * */
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		if (qName.equals(nodeName)) {
			map = new HashMap<String, String>();
		}
		if (attributes != null && map != null) {
			for (int i = 0; i < attributes.getLength(); i++) {
				map.put(attributes.getQName(i), attributes.getValue(i));
			}
		}
		currentTag = qName;
	}

	/**
	 * 解析到节点开头结尾中间夹的文字所调用的方法
	 * */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		if (currentTag != null && map != null) {
			currentValue = new String(ch, start, length);
			if (currentValue != null && !currentValue.trim().equals("")
					&& !currentValue.trim().equals("\n")) {
				map.put(currentTag, currentValue);
			}
		}
		currentTag = null;// 把当前节点对应的值和标签设置为空
		currentValue = null;
	}

	/**
	 * 解析到节点结尾调用方法</name>
	 * */
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// 遇到结束标记时候
		if (qName.equals(nodeName)) {
			list.add(map);
			map = null;
		}
	}
}


SaxService

package com.example.dashu_saxxml;

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

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;

public class SaxService {
	public SaxService() {
	}

	/**
	 * 网络xml解析方式
	 * */
	public static List<HashMap<String, String>> readXML(
			InputStream inputStream, String nodeName) {
		List<HashMap<String, String>>list=null;
		try {
			//创建一个解析xml工厂对象
			SAXParserFactory saxParserFactory=SAXParserFactory.newInstance();
			SAXParser parser=saxParserFactory.newSAXParser();//解析xml
			MyHandler myHandler=new MyHandler(nodeName);
			parser.parse(inputStream, myHandler);
			list=myHandler.getList();
			inputStream.close();//关闭io
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
	}
}


MainActivity

package com.example.dashu_saxxml;

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

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.os.Build;

public class MainActivity extends Activity {
	List<HashMap<String, String>> list = null;
	InputStream inputStream = null;
	SimpleAdapter simpleAdapter;
	ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		inputStream = getResources().openRawResource(R.raw.dashu);
		list = SaxService.readXML(inputStream, "user");
		listView = (ListView) this.findViewById(R.id.listview);
		simpleAdapter = new SimpleAdapter(getApplicationContext(), list,
				R.layout.litems, new String[] { "id", "name", "age" },
				new int[] { R.id.textView1, R.id.textView2, R.id.textView3 });
		listView.setAdapter(simpleAdapter);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值