Android -- 创建XML文件对象及其序列化, pull解析XML文件

1. 创建XML文件对象及其序列化

示例代码:(模拟以xml格式备份短信到SD卡)

SmsInfo.java, bean对象

/**
 * 短信的业务bean
 * @author Administrator
 *
 */
public class SmsInfo {
	private String body;
	private String number;
	private int type;
	private long id;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public SmsInfo() {
	}

	public SmsInfo(String body, String number, int type,long id) {
		this.body = body;
		this.number = number;
		this.type = type;
		this.id = id;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

}

SmsUtils.java 工具类

public class SmsUtils {

	/**
	 * 短信备份的工具方法
	 * @param file 短信备份到哪个文件里面
	 * @param smsInfos 要备份的短信对象的集合.
	 */
	public static void backUpSms(File file, List<SmsInfo> smsInfos) throws Exception{
		//xml文件的序列号器  帮助生成一个xml文件
		FileOutputStream fos = new FileOutputStream(file);
		//1.获取到xml的序列号器
		XmlSerializer serializer = Xml.newSerializer();
		//2.序列化器的初始化
		serializer.setOutput(fos, "utf-8"); //文件的编码方式 utf-8
		//3.创建xml文件,编码和是否独立,如果独立,一个xml文件 就会包含所有信息		
		serializer.startDocument("utf-8", true);
		serializer.startTag(null, "smss");
		
		//循环的把所有的短信数据都写到 xml文件里面
		for(SmsInfo info: smsInfos){
			serializer.startTag(null, "sms");
			serializer.attribute(null, "id", String.valueOf(info.getId()));
			
			serializer.startTag(null, "body");
			serializer.text(info.getBody());
			serializer.endTag(null, "body");
			
			serializer.startTag(null, "type");
			serializer.text(info.getType()+"");
			serializer.endTag(null, "type");
			
			serializer.startTag(null, "number");
			serializer.text(info.getNumber());
			serializer.endTag(null, "number");
			
			serializer.endTag(null, "sms");
		}
		serializer.endTag(null, "smss");
		serializer.endDocument();
		
		fos.flush();
		fos.close();
	}
}

MainActivity.java

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		List<SmsInfo> smsInfos = new ArrayList<SmsInfo>();
		
		//模拟创建两个短信数据的对象.
		SmsInfo sms1 = new SmsInfo("你好啊  短信1", "5556", 1,9999);
		SmsInfo sms2 = new SmsInfo("你好啊  短信2", "5558", 1,8888);
				
		smsInfos.add(sms1);
		smsInfos.add(sms2);
		
		File file = new File(Environment.getExternalStorageDirectory(),"back.xml");
		try {
			SmsUtils.backUpSms(file, smsInfos);
			Toast.makeText(this, "备份短信成功", 0).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "备份短信失败", 0).show();
		}
	}
}


2. pull解析XML文件

示例代码:(模拟解析xml格式的天气情况)

weather.xml 需要解析的XML文件

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<weather>
	<day id="1">
		<wendu>18</wendu>
		<wind>5</wind>
		<type>晴</type>
	</day>
	<day id="2">
		<wendu>16</wendu>
		<wind>3</wind>
		<type>雨</type>
	</day>
</weather>

Weather.java, bean

public class Weather {
	private int wendu;
	private int wind;
	private String type;
	private int id;
	public int getWendu() {
		return wendu;
	}
	public void setWendu(int wendu) {
		this.wendu = wendu;
	}
	public int getWind() {
		return wind;
	}
	public void setWind(int wind) {
		this.wind = wind;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "天气信息 [温度=" + wendu + ", 风力=" + wind + "级 , 天气状况=" + type
				+ ", 未来第=" + id + "天]";
	}		
}

WeatherService.java,业务类

public class WeatherService {
	/**
	 * 解析获取天气信息
	 * 
	 * @param is
	 *            天气信息xml文件对应的流
	 * @return
	 * @throws Exception
	 */
	public static List<Weather> getWeather(InputStream is) throws Exception {
		// 解析 天气的xml文件.
		// 1.获取到一个xml文件的解析器.
		XmlPullParser parser = Xml.newPullParser();
		// 2.初始化解析器.
		parser.setInput(is, "utf-8");
		// 3.解析xml文件.
		// 得到当前解析条目的节点类型.
		int eventType = parser.getEventType(); // 第一次被调用的时候 定位在xml开头
		List<Weather> weatherInfos = null;
		Weather weatherInfo = null;
		while (eventType != XmlPullParser.END_DOCUMENT) {// 需要 不停的让 解析器解析下一个节点
			switch (eventType) {
			case XmlPullParser.START_TAG:
				if ("weather".equals(parser.getName())) {
					// 发现开始节点 为weather 创建集合
					weatherInfos = new ArrayList<Weather>();
				} else if ("day".equals(parser.getName())) {
					// 发现一个新的日期 对应的天气
					weatherInfo = new Weather();
					String id = parser.getAttributeValue(0);
					weatherInfo.setId(Integer.parseInt(id));
				} else if ("wendu".equals(parser.getName())) {
					String wendu = parser.nextText();
					weatherInfo.setWendu(Integer.parseInt(wendu));
				} else if ("wind".equals(parser.getName())) {
					String wind = parser.nextText();
					weatherInfo.setWind(Integer.parseInt(wind));
				} else if ("type".equals(parser.getName())) {
					String type = parser.nextText();
					weatherInfo.setType(type);
				}

				break;

			case XmlPullParser.END_TAG:
				if ("day".equals(parser.getName())) {
					weatherInfos.add(weatherInfo);
				}
				break;
			}
			eventType = parser.next();// 控制解析器 解析下一个节点
		}
		is.close();
		return weatherInfos;

	}
}

MainActivity.java

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);		
		
		TextView tv = (TextView) findViewById(R.id.tv_weather);
		
		try {
			StringBuilder sb = new StringBuilder();
			List<Weather> weatherinfos = WeatherService.getWeather(getClassLoader().getResourceAsStream("weather.xml"));
			for(Weather weather : weatherinfos){
				sb.append(weather.toString());
				sb.append("\n");
				
			}
			tv.setText(sb.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "解析天气信息失败", 0).show();
		}			
	}
}




 

posted @ 2014-03-24 13:58  今晚打酱油_  阅读(272)  评论(0编辑  收藏  举报