android sax解析xml文档

11,308 views

采用xml文件存储数据是android常用的存储方式,比如可以在客户端存储用户基本信息,存储下载的文本

数据等等。解析xml主要有DOM,SAX方式,DOM处理XML文档是基于将XML文档解析成树状模型,放入内

存进行处理。而SAX则是采用基于事件驱动的处理模式,它将XML文档转化成一系列的事件,由单独的事

件处理器来决定如何处理。关于DOM与SAX更详细使用方法可以参考网上资料。

下面写一个关于android写入和读取xml文件的方法。
界面如下:

图-1 添加数据并生成相应的xml文件数据

主要思路:在一个Activity界面,输入要生成的数据,点击to xml按钮,生成相应的xml文件。另一个按

钮则查看生成的xml文件,并在另个一Activity中展现数据(界面如图-2).

图-2 显示读取的xml数据

1.)user.xml文件
生成的用户xml文件格式如下:

user.xml
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<users>
<user id="1">
<name>charlie</name>
<pwd>charlie</pwd>
<info>a student</info>
</user>
</users>
user.xml文件主要是记录用户的基本信息,用户id,用户名,密码等。
2.)SaxWriteXml.java
SaxWriteXml类主要是实现将数据写入xml文件。该类采用List数组作为传递写入的数据,采用List传递数据方便管理,将传递的List数组转换成相应的xml格式的字符串后,调用writeToXml()方法,写入xml文件。源码如下:
SaxWriteXml.java
package com.sax.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

public class SaxWriteXml {
//将一个list users对象的数据转换为字符串
public String writeUserInfoToString(List<User> users) {
// 实现xml信息序列号的一个对象
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
// xml数据经过序列化后保存到String中,然后将字串通过OutputStream保存为xml文件
serializer.setOutput(writer);
// 文档开始
serializer.startDocument("utf-8", true);
// 开始一个节点
serializer.startTag("", "users");
// 开始一个子节点
for (User user : users) {
serializer.startTag("", "user");
serializer.attribute("", "id", String.valueOf(user.getUserId()));
serializer.startTag("", "name");
serializer.text(user.getUserName());
serializer.endTag("", "name");
serializer.startTag("", "pwd");
serializer.text(user.getPassword());
serializer.endTag("", "pwd");
serializer.startTag("", "info");
serializer.text(String.valueOf(user.getInfo()));
serializer.endTag("", "info");
serializer.endTag("", "user");
}
serializer.endTag("", "users");
// 关闭文档
serializer.endDocument();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();

} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
return writer.toString();
}

public boolean writeToXml(String str,String filePath) {
OutputStream out = null;
try {

//com.sax.test是应用程序的根目录,跟入口应用程序有关,创建files文件夹
File dir=new File("/data/data/com.sax.test/files");
//如果没有则创建文件夹
if(!dir.exists())
dir.mkdirs();
//写入文件filePath
File f=new File("/data/data/com.sax.test/files/"+filePath);

out = new FileOutputStream(f);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;

}
OutputStreamWriter outw = new OutputStreamWriter(out);
try {
outw.write(str);
outw.close();
out.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
}
3.)SaxDoc.java
SaxDoc类主要是实现解析xml文件的功能。与SaxWriteXml类相对应,也是采用List管理数据,将节点的数据按照一定数据模型(User.java)存储数据,并最终返回一个List(User)模型对象的数组,通过getUserList()函数获取数组数据。这样比起单纯的打印每个字符串更便于传递数据。源码如下:
SaxDoc.java
package com.sax.test;

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

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

/**************
*
* 该类主要是实现对xml文件的解析,并返回一个list对象
*
* **********************/

public class SaxDoc extends DefaultHandler{
private List<User> list = null;
private User user = null;
private String tagname;
// 开始解析XML文档
@Override
public void startDocument() throws SAXException {
//初始化list
list = new ArrayList<User>();
super.startDocument();

}
StringBuffer sb = new StringBuffer();

// 开始处理节点,在这里获得节点属性值的(节点属性)
@Override
public void startElement(String uri, String localName, String qName,

Attributes attributes) throws SAXException {

sb.delete(0, sb.length());
if (localName.equals("user")) {
user = new User();
user.setUserId(Integer.parseInt(attributes.getValue("id")));
}
this.tagname = localName;
super.startElement(uri, localName, qName, attributes);
} // 处理没有属性的节点(节点内容)

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {

if (this.tagname != "") {
if (this.tagname.equals("name")) {
sb.append(ch, start, length);

user.setUserName(sb.toString());
} else if (this.tagname.equals("pwd")) {
sb.append(ch, start, length);

user.setPassword(sb.toString());

} else if (this.tagname.equals("info")) {
sb.append(ch, start, length);

user.setInfo(sb.toString());

}
}
super.characters(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
//一个元素结束后往list里加入一个user对象
if (localName.equals("user")) {
list.add(user);
}
super.endElement(uri, localName, qName);
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}

//返回user list对象

public List<User> getUserList() {
return list;
}

}
4.)SaxActivity.java

SaxActivity类是程序的主要界面,包含用户输入的文本框以及两个按钮。将用户输入的信息输入后,点击To XML按钮即可实现将数据生成xml文件;点击Read XML按钮,则可以查看生成的xml文件内容。源码如下:

SaxActivity.java
package com.sax.test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SaxActivity extends Activity {
/** Called when the activity is first created. */

private EditText userid;
private EditText username;
private EditText password;
private EditText info;

private Button toXml;
private Button readXml;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

userid=(EditText)findViewById(R.id.userid);
username=(EditText)findViewById(R.id.username);
password=(EditText)findViewById(R.id.password);
info=(EditText)findViewById(R.id.info);

toXml=(Button)findViewById(R.id.toXml);
toXml.setOnClickListener(toXmlClick);

readXml=(Button)findViewById(R.id.readXml);
readXml.setOnClickListener(readXmlClick);

}

OnClickListener toXmlClick=new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//用户Id必须填入一个数字否则会出现转换数字异常
String id=userid.getText().toString();
String user=username.getText().toString();
String pwd=password.getText().toString();
String _info=info.getText().toString();

User u=new User();

u.setUserId(new Integer(id));
u.setUserName(user);
u.setPassword(pwd);
u.setInfo(_info);
//如果有多个User对象,可以继续添加
List <User>list=new ArrayList<User>();
list.add(u);

SaxWriteXml sax=new SaxWriteXml();
String strXml=sax.writeUserInfoToString(list);
sax.writeToXml(strXml, "user.xml");

Toast.makeText(getApplicationContext(), "write to xml file successful ", 
Toast.LENGTH_SHORT).show();
}
};

OnClickListener readXmlClick=new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

SaxDoc sax=new SaxDoc();

SAXParser sp=null;
try {
sp = SAXParserFactory.newInstance().newSAXParser();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();

} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();

} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block

e.printStackTrace();

}
//解析user.xml文件

File f = new File("/data/data/com.sax.test/files/user.xml");
if(!f.exists()){
Toast.makeText(getApplicationContext(), "not exist user.xml  ", 
Toast.LENGTH_SHORT).show();
return ;
}
try {
sp.parse(f, sax);

} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//解析user.xml后,获取返回list的user数据
List <User>list=sax.getUserList();
//目前只有一个User对象
User user=list.get(0);
int r_userid=user.getUserId();
String r_username=user.getUserName();
String r_password=user.getPassword();
String r_info=user.getInfo();

System.out.println("r_userid"+r_userid);
System.out.println("r_username"+r_username);
System.out.println("r_password"+r_password);
System.out.println("r_info"+r_info);

Intent intent=new Intent(SaxActivity.this,ReadActivity.class);
Bundle map = new Bundle();
map.putSerializable("r_userid", r_userid);
map.putSerializable("r_username", r_username);
map.putSerializable("r_password", r_password);
map.putSerializable("r_info", r_info);
intent.putExtra("user", map);
startActivity(intent);

}
};
}
5.)ReadActivity.java
ReadActivity类主要是实现将SaxActivity传递过来的用户数据显示出来。
ReadActivity.java
package com.sax.test;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ReadActivity extends Activity{

private TextView userid;
private TextView username;
private TextView password;
private TextView info;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.read);

int _userid=this.getIntent().getBundleExtra("user").getInt("r_userid");

String _username=this.getIntent().getBundleExtra("user").getString("r_username");

String _password=this.getIntent().getBundleExtra("user").getString("r_password");

String _info=this.getIntent().getBundleExtra("user").getString("r_info");

userid=(TextView)findViewById(R.id.r_userid);
username=(TextView)findViewById(R.id.r_username);
password=(TextView)findViewById(R.id.r_password);
info=(TextView)findViewById(R.id.r_info);

System.out.println("_userid"+_userid);
System.out.println("_username"+_username);
System.out.println("_password"+_password);
System.out.println("_info"+_info);

userid.setText(String.valueOf(_userid));
username.setText(_username);
password.setText(_password);
info.setText(_info);
}
}
6.)User.java
User类文件主要是按照user.xml文件的数据格式而建立的数据模型对象,用于List中传递对象。
User.java

package com.sax.test;

public class User {
private int userId;
private String userName;
private String password;
private String info;

public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}

}
7.)layout.xml
关于layout文件此处省略……

源码下载:Sax.zip

This entry was posted in android, SAX, XML and tagged by Charlie. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>