安卓中xml学习笔记

生成xml 的方式
package com.example.writexml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import com.xml.sms.domain.SmsInfo;

import android.animation.ArgbEvaluator;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity implements OnClickListener {
	private List<SmsInfo> smss;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button bt1 = (Button) findViewById(R.id.bt1);
		Button bt2 = (Button) findViewById(R.id.bt2);
		bt1.setOnClickListener(this);
		bt2.setOnClickListener(this);
		long address = 1300001;
		smss = new ArrayList<SmsInfo>();
		for (int i = 0; i < 10; i++) {
			smss.add(new SmsInfo("短信内容"+i, Long.toString(address+i),1,System.currentTimeMillis(),i));
		}
	}

	public void onClick(View v) {
		switch (v.getId()) 
		{
			case R.id.bt1:
				writeStringXml();
				break;
			case R.id.bt2:
				xmlSerailze();
				break;
		}
	}
	
	public void writeStringXml()
	{
		System.out.println(Environment.getExternalStorageDirectory());
		File file = new File(this.getFilesDir(),"sringXml.xml");
		try {
			FileOutputStream fo = new FileOutputStream(file);
			String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
			str+="<Smss>";
			for (SmsInfo info : smss) {
				str+="<sms>";
				
				str+="<body>";
				str+=info.getBody();
				str+="</body>";
				
				str+="<address>";
				str+=info.getAddress();
				str+="</address>";
				
				str+="<type>";
				str+=info.getType();
				str+="</type>";
				
				str+="<time>";
				str+=info.getTime();
				str+="</time>";
				
				str+="</sms>";
			}
			str+="</Smss>";
			fo.write(str.getBytes());
			fo.close();
			Toast.makeText(this, "保存xml成功", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	public void xmlSerailze () 
	{
		File file = new File(this.getFilesDir(), "stringXml2.xml");
		FileOutputStream fo;
		try {
			fo = new FileOutputStream(file);
			XmlSerializer xml = Xml.newSerializer();
			xml.setOutput(fo, "utf-8");
			xml.startDocument(null,true);
			xml.startTag(null, "smss");
			for (SmsInfo info : smss) {
				xml.startTag(null, "sms");
				xml.attribute(null, "id", info.getId()+"");
				xml.startTag(null, "body");
				xml.text(info.getBody());
				xml.endTag(null,"body");
				
				xml.startTag(null, "address");
				xml.text(info.getAddress());
				xml.endTag(null,"address");
				
				xml.startTag(null, "time");
				xml.text(Long.toString(info.getTime()));
				xml.endTag(null,"time");

				xml.startTag(null, "type");
				xml.text(info.getType()+"");
				xml.endTag(null,"type");
				
				xml.endTag(null, "sms");
			}
			xml.endTag(null, "smss");
			xml.endDocument();
			fo.close();
			Toast.makeText(this, "保存xml成功", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
		}
	
		
	}
}

2,利用xmlPull解析xml文件

watherInfo.java

package com.xml.domain;

public class watherInfo {
	private String name;
	private String temp;
	private String pm;
	private String date;
	private int id;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTemp() {
		return temp;
	}
	public void setTemp(String temp) {
		this.temp = temp;
	}
	public String getPm() {
		return pm;
	}
	public void setPm(String pm) {
		this.pm = pm;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	@Override
	public String toString() {
		return "天气预报: [天气=" + name + ", 温度=" + temp + ", pm=" + pm
				+ ", 日期=" + date + "]";
	}
	
}



watherService.java

package com.xml.service;

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

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;
import android.util.Xml;

import com.xml.domain.watherInfo;

public class watherService {
	
	/**
	 * 
	 * @param is
	 * @return
	 * @throws Exception
	 */
	static public List<watherInfo> getWatherInfos(InputStream is) throws Exception
	{
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");
		int type = parser.getEventType();
		List<watherInfo> watherInfos = null;
		watherInfo watherInfo = null;
		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
				case XmlPullParser.START_TAG:
					if ("weather".equals(parser.getName())) {
						watherInfos = new ArrayList<watherInfo>();
					} else if ("city".equals(parser.getName())) {
						watherInfo = new watherInfo();
						String id = parser.getAttributeValue(0);
						watherInfo.setId(Integer.parseInt(id));
					} else if ("name".equals(parser.getName())) {
						String name = parser.nextText();
						watherInfo.setName(name);
					}else if ("temp".equals(parser.getName())) {
						String temp =parser.nextText();
						watherInfo.setTemp(temp);
					}else if ("pm".equals(parser.getName())) {
						String pm = parser.nextText();
						watherInfo.setPm(pm);;
					}else if ("date".equals(parser.getName())) {
						String date = parser.nextText();
						watherInfo.setDate(date);
					}
					break;
				case XmlPullParser.END_TAG:
					if ("city".equals(parser.getName())) {
						Log.i("test", watherInfo.toString());
						watherInfos.add(watherInfo);
						watherInfo = null;
					}
					break;
			}
			is.close();
			type = parser.next();
		}
		return watherInfos;
	}
}



string.xml

<?xml version="1.0" encoding="utf-8"?>
<weather>
	<city id="1">
		<name>北京</name>
		<temp>25度</temp>
		<pm>2.8</pm>
		<date>2015-05-20</date>
	</city>
	<city id="2">
		<name>北京</name>
		<temp>25度</temp>
		<pm>2.8</pm>
		<date>2015-05-20</date>
	</city>
	<city id="3">
		<name>北京</name>
		<temp>25度</temp>
		<pm>2.8</pm>
		<date>2015-05-20</date>
	</city>
</weather>



MainActivity.java

package com.example.xmlparse;

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

import com.xml.domain.watherInfo;
import com.xml.service.watherService;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

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);
		StringBuilder sb = new StringBuilder();
		InputStream is = MainActivity.class.getClassLoader().getResourceAsStream("sringXml.xml");
		try {
			List<watherInfo> watherInfos = watherService.getWatherInfos(is);
			for (watherInfo info : watherInfos) {
				String str = info.toString();
				sb.append(str);
				sb.append("\r\n");
			}
			tv.setText(sb.toString());
			Log.i("test", sb.toString());
			Toast.makeText(this, "解析成功", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "解析失败", Toast.LENGTH_SHORT).show();
		}
	}

}




你可能感兴趣的:(安卓中xml学习笔记)