关闭

xml的pull解析

122人阅读 评论(0) 收藏 举报
分类:

第一部分,xml序列化

先得到xml序列化对象,然后设置要输出流和编码格式,

接下来就开始序列化,然后你自己看代码吧,懒得打字了


//创建了一个文件输出流,并指定其输出的位置
		FileOutputStream fos=new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "smsbackup.xml"));
		
		//得到xml序列化对象
		XmlSerializer serializer=Xml.newSerializer();
		
		//设置输出流和编码格式
		serializer.setOutput(fos, "utf-8");
		
		//设置文档编码格式和是否为独立文件
		serializer.startDocument("utf-8", true);
		
		
		serializer.startTag(null, "Smss");
<span style="white-space:pre">		</span>//设置属性
		serializer.attribute(null, "count", String.valueOf(cursor.getCount()));
		
		
		while(cursor!=null&&cursor.moveToNext()){
			serializer.startTag(null, "sms");
			
			
			serializer.startTag(null, "address");
			serializer.text(cursor.getString(0));
			serializer.endTag(null, "address");
			
			serializer.startTag(null, "date");
			serializer.text(cursor.getString(1));
			serializer.endTag(null, "date");
			
			serializer.startTag(null, "type");
			serializer.text(cursor.getString(2));
			serializer.endTag(null, "type");
			
			serializer.startTag(null, "body");
			serializer.text(cursor.getString(3));
			serializer.endTag(null, "body");
			
			
			serializer.endTag(null, "sms");
			
			listener.onChange(cursor.getPosition());
		}
		
		
		serializer.endTag(null, "Smss");
		serializer.endDocument();
		
		
		cursor.close();
		fos.close();

好了,这样就序列化完 了,接下来介绍怎么解析



FileInputStream fis=new FileInputStream(new File(Environment.getExternalStorageDirectory(), "smsbackup.xml"));
		XmlPullParser pullparser=Xml.newPullParser();
		pullparser.setInput(fis, "utf-8");
		Log.i("huang", "whileqian");
		while(pullparser.next()!=pullparser.END_DOCUMENT){
			switch(pullparser.getEventType()){
			
			
			case XmlPullParser.START_TAG:
				if(pullparser.getName().equals("Smss")){
					listner.onSize(Integer.valueOf(pullparser.getAttributeValue(null, "count")));
				}
				else if(pullparser.getName().equals("sms")){
					value=new ContentValues();
				}
				else if(pullparser.getName().equals("address")){
					value.put("address", pullparser.nextText());
					
					
				}
				else if(pullparser.getName().equals("date")){
					value.put("date", pullparser.nextText());
				}
				else if(pullparser.getName().equals("type")){
					value.put("type", pullparser.nextText());
				}
				else if(pullparser.getName().equals("body")){
					value.put("body", pullparser.nextText());
				}
				break;
				
				
				
			case XmlPullParser.END_TAG:
				if(pullparser.getName().equals("sms")){
					resolver.insert(uri, value);
					
					position++;
//					Log.i("huang", "还原"+position+"条");
					listner.onChange(position);
				}
				break;
			}
		}
		
		fis.close();


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20172次
    • 积分:657
    • 等级:
    • 排名:千里之外
    • 原创:46篇
    • 转载:12篇
    • 译文:0篇
    • 评论:1条