Android 创建与解析xml文件
来源:互联网 发布:windows me u盘安装 编辑:程序博客网 时间:2024/05/18 01:12
要求:
创建一个Android项目,在项目中创建一个javaBean(City.java),该文件中包含了对应城市的名称,温度,pm。之后模拟出几个City对象,用这些对象生成一个xml文件。
之后解析这个xml文件,让解析出来的内容通过ListView显示在屏幕上。
步骤:
1.创建一个android的项目E_AB_createXmlAndPullparser2.
2.编辑布局文件activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="hhh.exercise.e_ab_createxmlandpullparser.MainActivity" > <Button android:id="@+id/button_create" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="生成xml文件" android:textColor="#00ff00" android:textSize="30sp" /> <Button android:id="@+id/button_parser" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/button_create" android:text="解析xml文件" android:textColor="#00ff00" android:textSize="30sp" /> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/button_parser" > <TextView android:id="@+id/textView_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="NAME" android:textColor="#ff0000" android:textSize="24sp" /> <TextView android:id="@+id/textView_temp" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="TEMP" android:textColor="#00ff00" android:textSize="24sp" /> <TextView android:id="@+id/textView_pm" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="PM" android:textColor="#0000ff" android:textSize="24sp" /> </LinearLayout> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/linearLayout" > </ListView></RelativeLayout>
3.创建item.xml,该文件时ListView的资源文件
<?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/textView_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:textColor="#ff0000" android:textSize="24sp" /> <TextView android:id="@+id/textView_temp" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:textColor="#00ff00" android:textSize="24sp" /> <TextView android:id="@+id/textView_pm" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:textColor="#0000ff" android:textSize="24sp" /></LinearLayout>
4.在src目录下创建一个包hhh.exercise.domian,在包中创建一个JavaBean(City类):
package hhh.exercise.domian;/** * @author HHH * */public class City { private String name; private String temp; private String pm; @Override public String toString() { return "City [name=" + name + ", temp=" + temp + ", pm=" + pm + "]"; } public City(String name, String temp, String pm) { super(); this.name = name; this.temp = temp; this.pm = pm; } public City() { super(); } 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; }}
5.在hhh.exercise.e_ab_createxmlandpullparser包里创建MainActivity.java文件:
package hhh.exercise.e_ab_createxmlandpullparser;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ListView;import android.widget.Toast;import hhh.exercise.domian.City;import hhh.exercise.e_a1_createxml.R;import hhh.exercise.service.CityAdapter;import hhh.exercise.service.FileService;public class MainActivity extends Activity { private ListView listView; private List<City> list; private FileService service; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); service = new FileService(); // 模拟出几条城市的信息 init(); // 生成xml文件 Button button_create = (Button) findViewById(R.id.button_create); button_create.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { boolean b = service.createXml(list); if (b) { Toast.makeText(getApplicationContext(), "成功生成xml文件", 0).show(); } else { Toast.makeText(getApplicationContext(), "未生成xml文件", 0).show(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "出现未知错误,无法生成xml文件", 0).show(); e.printStackTrace(); } } }); // 解析xml文件 Button button_parser = (Button) findViewById(R.id.button_parser); button_parser.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { List<City> result = service.getXml(); show(result); } catch (Exception e) { Toast.makeText(getApplicationContext(), "出现未知错误,无法解析xml文件", 0).show(); e.printStackTrace(); } } }); } /** * 将集合中的数据显示在ListView中 * * @param result */ protected void show(List<City> result) { CityAdapter adapter = new CityAdapter(getApplicationContext(), R.layout.item, result); listView.setAdapter(adapter); } /** * 初试化List列表,创建几个City对象,用于后面的测试 */ private void init() { list = new ArrayList<City>(); list.add(new City("哈尔冰", "-20", "200")); list.add(new City("北京", "-15", "180")); list.add(new City("天津", "-10", "160")); list.add(new City("济南", "-5", "140")); list.add(new City("连云港", "0", "120")); list.add(new City("上海", "5", "100")); list.add(new City("南京", "10", "80")); list.add(new City("合肥", "15", "60")); list.add(new City("武汉", "20", "40")); }}
6.在src目录下创建一个hhh.exercise.service包,在包中创建FileService.java:
package hhh.exercise.service;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.ArrayList;import java.util.List;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlSerializer;import android.os.Environment;import android.util.Xml;import hhh.exercise.domian.City;/** * @author HHH * */public class FileService { public boolean createXml(List<City> list) throws Exception { boolean b = false; if ((Environment.MEDIA_MOUNTED).equals(Environment.getExternalStorageState())) { // 获取序列化器对象 XmlSerializer xmlSerializer = Xml.newSerializer(); String path = Environment.getExternalStorageDirectory().getPath(); File file = new File(path, "weather.xml"); FileOutputStream fos = new FileOutputStream(file); // 指定xml文件生成的方式。 // 第二个参数指定用utf-8生成xml文件 xmlSerializer.setOutput(fos, "utf-8"); // 开始生成xml文件 xmlSerializer.startDocument("utf-8", true); // 设置头检点 xmlSerializer.startTag(null, "weather"); for (City city : list) { xmlSerializer.startTag(null, "city"); xmlSerializer.startTag(null, "name"); xmlSerializer.text(city.getName()); xmlSerializer.endTag(null, "name"); xmlSerializer.startTag(null, "temp"); xmlSerializer.text(city.getTemp()); xmlSerializer.endTag(null, "temp"); xmlSerializer.startTag(null, "pm"); xmlSerializer.text(city.getPm()); xmlSerializer.endTag(null, "pm"); xmlSerializer.endTag(null, "city"); } xmlSerializer.endDocument(); b = true; } return b; } /** * @return * @throws Exception */ public List<City> getXml() throws Exception { City city = null; List<City> result = null; if ((Environment.MEDIA_MOUNTED).equals(Environment.getExternalStorageState())) { String path = Environment.getExternalStorageDirectory().getPath(); File file = new File(path, "weather.xml"); // 判断文件是够存在,存在就开始解析文件 if (file.exists()) { // 获取解析器 XmlPullParser parser = Xml.newPullParser(); // 设置数据源编码 parser.setInput(new FileInputStream(file), "UTF-8"); // 获取当前结点的时间类型 int type = parser.getEventType(); while (type != XmlPullParser.END_DOCUMENT) { switch (type) { case XmlPullParser.START_TAG: String tag_name=parser.getName(); if ("weather".equals(tag_name)) { result = new ArrayList<City>(); } if ("city".equals(tag_name)) { city = new City(); } if ("name".equals(tag_name)) { // 获取当前结点的下一节点文本,把指针移动到该结点的结束节点,并且把得到的信息存入city中。 // 如果当前事件是START_TAG,则如果下一个元素是TEXT,则返回元素内容,或者如果下一个事件是END_TAG,则返回空字符串,否则抛出异常。调用此函数后,成功解析器将位于END_TAG上。 String name = parser.nextText(); city.setName(name); } if ("temp".equals(tag_name)) { String temp = parser.nextText(); city.setTemp(temp); } if ("pm".equals(tag_name)) { String pm = parser.nextText(); city.setPm(pm); } break; case XmlPullParser.END_TAG: if ("city".equals(parser.getName())) { result.add(city); } break; } // 获取下一个结点,注意不要写成nextTag(); type = parser.next(); } } } return result; }}
7..在hhh.exercise.service包中创建CityAdapter.java,该类为自定义的适配器(也可以用系统写好的适配器),继承BaseAdapter:
package hhh.exercise.service;import java.util.List;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;import hhh.exercise.domian.City;import hhh.exercise.e_a1_createxml.R;/** * @author HHH * */public class CityAdapter extends BaseAdapter { // 定义变量,表示传入的布局资源 private int resource; // 定义变量,表示需要绑定的数据 private List<City> result; // 定义变量,为布局填充器 private LayoutInflater layoutInflater; /** * @param resource * @param result * @param layoutInflater */ public CityAdapter(Context context, int resource, List<City> result) { super(); this.resource = resource; this.result = result; this.layoutInflater = LayoutInflater.from(context); } /* * (non-Javadoc) * * @see android.widget.Adapter#getCount() */ @Override public int getCount() { // 返回绑定数据的条目数量 return result.size(); } /* * (non-Javadoc) * * @see android.widget.Adapter#getItem(int) */ @Override public Object getItem(int position) { // 通过索引获取result中的数据 return result.get(position); } /* * (non-Javadoc) * * @see android.widget.Adapter#getItemId(int) */ @Override public long getItemId(int position) { return position; } /* * (non-Javadoc) * * @see android.widget.Adapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; // 根据给定的索引获取资源 City city = (City) getItem(position); // 实例化ViewHolder类,为后面的优化工作做准备 ViewHolder holder = new ViewHolder(); if (convertView != null) { view = convertView; // 从view中获取存储的ViewHolder对象 holder = (ViewHolder) view.getTag(); } else { // 利用布局填充器创建View对象那个 view = layoutInflater.inflate(resource, null); // 利用ViewHolder对象把view中的组件存储起来 holder.textView_name = (TextView) view.findViewById(R.id.textView_name); holder.textView_temp = (TextView) view.findViewById(R.id.textView_temp); holder.textView_pm = (TextView) view.findViewById(R.id.textView_pm); // 把ViewHolder对象存储到view中 view.setTag(holder); } TextView textView_name = holder.textView_name; TextView textView_temp = holder.textView_temp; TextView textView_pm = holder.textView_pm; textView_name.setText(city.getName()); textView_temp.setText(city.getTemp()); textView_pm.setText(city.getPm()); return view; } class ViewHolder { TextView textView_name; TextView textView_temp; TextView textView_pm; }}
8.在AndroidManifest.xml添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
9.部署到模拟器上:首先点击“生成xml文件”,点击后在sd卡目录下生成weather.xml文件,在浏览器下解析如下所示:
点击“解析xml文件”按钮,屏幕上显示如下:
0 0
- Android中解析与创建XML文件
- Android 创建与解析xml文件
- Android 创建与解析XML
- 使用Dom4j创建与解析XML文件
- Android xml文件创建和pull解析
- Android Xml文件的解析和创建
- Android Apps xml创建与解析PullXml
- Android Apps xml创建与解析DomXml
- xml解析与创建
- xml解析与创建
- android xml文件的生成与解析
- Android中的Xml文件与解析简介
- Android中xml和json文件的解析和创建
- 解析规律文件 创建XML
- Android中Sax解析与Dom解析xml文件
- Android解析XML文件
- android xml文件解析
- Android 解析XML文件
- requirejs使用AMD标准的jquery-ui
- Subsets
- ios开发self和super的区别
- 【笔试练习】腾讯2016笔试题
- 推荐系统 Crab 初探(一)
- Android 创建与解析xml文件
- 微信小程序笔记
- 算法训练 Anagrams问题
- 『 Jack_a_Lent_Notes』---按键状态机[ATmega128]
- 读《透过结构看世界》
- iWebShop二次开发之商城之后台系统菜单管理【转载】
- BZOJ 4240 有趣的家庭菜园
- C++11之经典书籍和网文推荐(持续更新资源下载链接)
- 初识Nginx(一):nginx的安装