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 {@Overrideprotected 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;}@Overridepublic 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 {@Overrideprotected 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();}			}
}




 

转载于:https://www.cnblogs.com/xj626852095/p/3647985.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/294003.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

.NET大会2021参会笔记

全面拥抱Linux拥抱linux是微软的战略转型。Satya Nadella写的书《refresh》&#xff0c;就提到了MS loves Linux。所以&#xff0c;大会一开始&#xff0c;以然是Scott Hanselman&#xff0c;给我们演示如果在linux上面使用.net。好了&#xff0c;好了&#xff0c;你不用说了&a…

zookeeper配置文件详解

zoo.cfg配置文件 # The number of milliseconds of each tick tickTime2000 # The number of ticks that the initial # synchronization phase can take initLimit10 # The number of ticks that can pass between # sending a request and getting an acknowledgement sync…

html 图片 填充方式,css怎么让图片填满?

在css中&#xff0c;可以将div的高度和宽度属性设置为100%&#xff0c;同时使用background-size属性设置背景图片为100%&#xff0c;便可以实现背景图片铺满屏幕。css怎么让图片填满&#xff1f;1、新建一个HTML文件&#xff0c;使用div标签创建一个模块&#xff0c;并设置其cl…

solrcloud线上创建collection,修改默认配置

一、先看API&#xff0c;创建collection1、上传配置文件到zookeeper1&#xff09; 本地内嵌zookeeper集群&#xff1a;java -classpath ./solr-webapp/webapp/WEB-INF/lib/* org.apache.solr.cloud.ZkCLI -cmd upconfig -zkhost localhost:9983,localhost:8574,localhost:9900 …

Android之判断手机黑屏以及锁屏

1、黑屏 /** * 判断是否黑屏 * param c * return */ public final static boolean isScreenLocked(Context c) { android.app.KeyguardManager mKeyguardManager (KeyguardManager) c.getSystemService(c.KEYGUARD_SERVICE); return !mKeyguardManager.inKeyguardRestricte…

豆瓣评分9.4!这一部纪录片,探秘中国的未至之境!

全世界只有3.14 % 的人关注了爆炸吧知识Bilibili 联合“美国国家地理”&#xff0c;悄悄出品了一部史诗级动物记录片&#xff0c;忍不住要推荐给大朋友小朋友们——《未至之境》。这部纪录片由B站和国家地理联合创作&#xff0c;从绵延万里的山脉高原到枝繁叶茂的雨林竹海&…

html5设置不缓存页面,页面的缓存与不缓存设置

HTML的HTTP和谈头信息中把握着页面在几个处所的缓存信息&#xff0c;包含浏览器端&#xff0c;中心缓存办事器端(如&#xff1a;squid等)&#xff0c;Web办事器端。本文评论辩论头信息 中带缓存把握信息的HTML页面(JSP/Servlet生成好出来的也是HTML页面)在中心缓存办事器中的缓…

Ubuntu 10.10, 11.04, 11.10这三个版本无法从优盘启动

问题&#xff1a;Ubuntu 10.10, 11.04, 11.10这三个版本无法从优盘启动 解决&#xff1a;从U盘启动安装的时候&#xff0c;会卡住不动。搞定办法相当简单&#xff0c;修改syslinux/syslinuxfg文件&#xff1a;将default vesamenu32这句话注释掉即可&#xff0c;即&#xff1a;将…

.NET内存性能分析指南

.NET Memory Performance Analysis知道什么时候该担心&#xff0c;以及在需要担心的时候该怎么做译者注作者信息&#xff1a;Maoni Stephens - 微软架构师&#xff0c;负责.NET Runtime GC设计与实现 博客链接 Github译者&#xff1a;Bing Translator、INCerry 博客链接&#x…

解决php连接mysql数据库中文乱码问题

首先数据库编码和Mysql连接校对编码要一致&#xff1a; 其次在php文件中加入这两句&#xff1a; 2013-3-21更新&#xff1a; Linux下最好都用UTF-8编码&#xff1a; 1、数据库里面选utf-8_general_ci 2、php文件加上header("Content-Type: text/html; charset utf-8"…

使用反射将DataTable的数据转成实体类

利用反射避免了硬编码出现的错误&#xff0c;但是实体类的属性名必须和数据库名字对应&#xff08;相同&#xff09; 1、利用反射把DataTable的数据写到单个实体类 /// <summary>///利用反射把DataTable的数据写到单个实体类/// </summary>/// <typeparam name&…

Andorid之KeyguardManager的介绍

android.app.KeyguardManager类用于对Keyguard进行管理&#xff0c;即对锁屏进行管理。 详细信息参考&#xff1a; http://blog.csdn.net/hudashi/article/details/7073373 下面的代码用来设定键盘锁和解锁 //声明键盘管理器并获取键盘的服务 KeyguardManager keyguardManage…

html表格在页面间距,在CSS中设置单元格和单元格间距?

梦里花落0921基本要控制css中的“单元格填充”&#xff0c;只需使用padding放在桌子上。例如10便士的“细胞填充物”&#xff1a;td { padding: 10px;}对于“单元格间距”&#xff0c;可以应用border-spacing属性设置到表中。例如&#xff0c;10 px的“单元间距”&#xff1a;t…

DAS,NAS,SAN在数据库存储上的应用

一. 硬盘接口类型1. 并行接口还是串行接口(1) 并行接口&#xff0c;指的是并行传输的接口&#xff0c;比如有0~9十个数字&#xff0c;用10条传输线&#xff0c;那么每根线只需要传输一位数字&#xff0c;即可完成。从理论上看&#xff0c;并行传输效率很高&#xff0c;但是由于…

Spring Data Redis—Pub/Sub(附Web项目源码)

一、发布和订阅机制 当一个客户端通过 PUBLISH 命令向订阅者发送信息的时候&#xff0c;我们称这个客户端为发布者(publisher)。 而当一个客户端使用 SUBSCRIBE 或者 PSUBSCRIBE 命令接收信息的时候&#xff0c;我们称这个客户端为订阅者(subscriber)。 为了解耦发布者(publish…

Android之Intent.ACTION_MEDIA_SCANNER_SCAN_FILE:扫描指定文件

1&#xff0e;启动MediaScanner服务&#xff0c;扫描媒体文件&#xff1a; 程序通过发送下面的Intent启动MediaScanner服务扫描指定的文件或目录&#xff1a; Intent.ACTION_MEDIA_SCANNER_SCAN_FILE&#xff1a;扫描指定文件 public void scanFileAsync(Context ctx, String …

libuv 中文编程指南(四)网络

网络 libuv 的网络接口与 BSD 套接字接口存在很大的不同, 某些事情在 libuv 下变得更简单了, 并且所有接口都是都是非阻塞的, 但是原则上还是一致的. 另外 libuv 也提供了一些工具类的函数抽象了一些让人生厌的, 重复而底层的任务,比如使用 BSD 套接字结构来建立套接字, DNS 查…

突破历史,21年C#将首获年度编程语言奖!

2021年渐入尾声&#xff0c;TIOBE今日发布了12月排行榜&#xff0c;Java(第3)持续下滑&#xff0c;PHP(第12)跌出前十&#xff0c;而C#(第5)继续稳步增长。据悉&#xff0c;TIOBE的CEO Paul Jansen表示&#xff0c;C#极有可能获取“TIOBE 年度编程语言奖”。该奖项一般颁发给被…

史上最接近上帝的方程!神秘的数字4.669,目前没有人能解开这个谜语......

全世界只有3.14 % 的人关注了爆炸吧知识上帝指纹统治世界&#xff1f;春节进入倒计时&#xff0c;实不相瞒&#xff0c;超模君想鸽的心蠢蠢欲动&#xff0c;费了好大劲才摁住&#xff01;为了不鸽&#xff0c;连夜翻了个墙&#xff0c;明明刚开始还在认认真真看论文&#xff0c…