Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Android中使用Pull解析器生成XML文件和读取xml文件

$
0
0

有些时候,我们需要生成一个XML文件,生成XML文件的方法有很多,如:可以只使用一个StringBuilder组拼XML内容,然后把内容写入到文件中;或者使用DOM API生成XML文件,或者也可以使用pull解析器生成XML文件,这里推荐大家使用Pull解析器。

一、布局界面

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:paddingBottom="@dimen/activity_vertical_margin"
  6. android:paddingLeft="@dimen/activity_horizontal_margin"
  7. android:paddingRight="@dimen/activity_horizontal_margin"
  8. android:paddingTop="@dimen/activity_vertical_margin"
  9. tools:context=".MainActivity" >
  10. <Button
  11. android:id="@+id/btn_pull"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:layout_alignParentLeft="true"
  15. android:layout_alignParentRight="true"
  16. android:layout_alignParentTop="true"
  17. android:layout_marginTop="110dp"
  18. android:text="@string/btn_pull" />
  19. <Button
  20. android:id="@+id/btn_write"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:layout_alignLeft="@+id/btn_pull"
  24. android:layout_alignRight="@+id/btn_pull"
  25. android:layout_below="@+id/btn_pull"
  26. android:layout_marginTop="61dp"
  27. android:text="@string/btn_write" />
  28. </RelativeLayout>


二、写一个xml文件

[html] view plaincopyprint?
<?xml version="1.0" encoding="UTF-8"?> 
<persons> 
<person id="23"> 
<name>李明</name> 
<age>30</age> 
</person> 
<person id="20"> 
<name>李向梅</name> 
<age>25</age> 
</person> 
</persons> 


三、写一个和xml相对应的bean

[java] view plaincopyprint?
package com.example.lession04_pull.domain; 

import java.io.Serializable; 

public class Person implements Serializable{ 

/** 
* 
*/ 
private static final long serialVersionUID = 1L; 
private int id; 
private String name; 
private short age; 
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 short getAge() { 
return age; 
} 
public void setAge(short age) { 
this.age = age; 
} 
public Person(int id, String name, short age) { 
super(); 
this.id = id; 
this.name = name; 
this.age = age; 
} 
public Person() { 
super(); 
// TODO Auto-generated constructor stub 
} 


} 


四、写一个Pul的服务类

 

[java] view plaincopyprint?
package com.example.lession04_pull.service; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
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 com.example.lession04_pull.domain.Person; 

public class PullXmlService { 

public Person currentPerson; 

public List<Person> readXml(InputStream is){ 
//声明返回值 
List<Person> persons=null; 
//首先利用Xml.newPullParser()获取解析对象 
XmlPullParser xmlPullParser=Xml.newPullParser(); 
try{ 
// 解析文件 
xmlPullParser.setInput(is, "UTF-8"); 
//获取解析的事件类型 
int eventType=xmlPullParser.getEventType(); 
//判断文件解析的是否完毕 
while(eventType!=XmlPullParser.END_DOCUMENT){ 
switch (eventType) { 
case XmlPullParser.START_DOCUMENT: 
persons=new ArrayList<Person>(); 
break; 

case XmlPullParser.START_TAG: 
String tagName=xmlPullParser.getName(); 
if("person".equals(tagName)){ 
//创建person对象 
currentPerson=new Person(); 
currentPerson.setId(Integer.parseInt(xmlPullParser 
.getAttributeValue(null, "id"))); 
}else if("name".equals(tagName)){ 
currentPerson.setName(xmlPullParser.nextText()); 
}else if("age".equals(tagName)){ 
currentPerson.setAge(new Short(xmlPullParser.nextText())); 
} 
break; 
case XmlPullParser.END_TAG: 
if("person".equals(xmlPullParser.getName()) && currentPerson!=null){ 
//把person对象放到集合中去 
persons.add(currentPerson); 
currentPerson=null; 
} 
break; 
} 
eventType=xmlPullParser.next(); 
} 
is.close(); 
}catch(Exception e){ 
e.printStackTrace(); 
} 
return persons; 
} 



// 写入 
public boolean write(List<Person> persons) { 
// 采用pull解析进行实现 

if (Environment.getExternalStorageState().equals( 
Environment.MEDIA_MOUNTED)) { 

// 获取sdcard目录 文件对象 
File sdCardDir = Environment.getExternalStorageDirectory(); 
// 创建文件 
File file = new File(sdCardDir, "mycsdn.xml"); 

XmlSerializer serializer = Xml.newSerializer(); 

FileOutputStream fos = null; 
try { 
// 根据文件对象创建一个文件的输出流对象 
fos = new FileOutputStream(file); 
// 设置输出的流及编码 
serializer.setOutput(fos, "UTF-8"); 
// 设置文件的开始 
serializer.startDocument("UTF-8", true); 
// persons标签开始 
serializer.startTag(null, "persons"); 
for (Person person : persons) { 
// person标签的开始 
serializer.startTag(null, "person"); 
// 设置person标签的属性 
serializer.attribute("null", "id", person.getId() + ""); 

// 设置person标签的子标签 name 
serializer.startTag(null, "name"); 
serializer.text(person.getName()); 
serializer.endTag(null, "name"); 

// 设置person标签的子标签的age 
serializer.startTag(null, "age"); 
serializer.text(person.getAge() + ""); 
serializer.endTag(null, "age"); 

// person标签的结束 
serializer.endTag(null, "person"); 
} 

// persons标签的结束 
serializer.endTag(null, "persons"); 
// 文件的结束 
serializer.endDocument(); 

fos.flush(); 
fos.close(); 
return true; 
} catch (Exception e) { 
e.printStackTrace(); 
} 

} 

return false; 
} 


 

  1. }


五、在MainActivity中调用测试

[java] view plaincopyprint?
package com.example.lession04_pull; 

import java.util.List; 

import com.example.lession04_pull.domain.Person; 
import com.example.lession04_pull.service.PullXmlService; 

import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

public Button btn_pull,btn_write; 
public PullXmlService pullXmlService; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
//实例化 
pullXmlService=new PullXmlService(); 

btn_pull=(Button) findViewById(R.id.btn_pull); 
btn_write=(Button) findViewById(R.id.btn_write); 

btn_pull.setOnClickListener(new MyOnClickListener()); 
btn_write.setOnClickListener(new MyOnClickListener()); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
// Inflate the menu; this adds items to the action bar if it is present. 
getMenuInflater().inflate(R.menu.main, menu); 
return true; 
} 

class MyOnClickListener implements View.OnClickListener{ 

@Override 
public void onClick(View v) { 
int id=v.getId(); 
switch (id) { 
case R.id.btn_pull: 
List<Person> persons=null; 
try{ 
persons=pullXmlService.readXml(getAssets().open("csdn.xml")); 
}catch(Exception e){ 
e.printStackTrace(); 
} 
if(persons!=null){ 
Toast.makeText(MainActivity.this, "采用pull解析xml文件"+persons.get(0).getName()+"--"+persons.get(1).getName(), 
Toast.LENGTH_LONG).show(); 
} 
break; 

case R.id.btn_write: 
try{ 
List<Person> pers=pullXmlService.readXml(getAssets().open("csdn.xml")); 
//重新生成一个xml文件 mysdcare.xml 
boolean flag=pullXmlService.write(pers); 
if(flag){ 
Toast.makeText(MainActivity.this, "采用pull解析生产xml文件成功", 
Toast.LENGTH_LONG).show(); 
}else{ 
Toast.makeText(MainActivity.this, "采用pull解析生产xml文件失败", 
Toast.LENGTH_LONG).show(); 

} 
}catch(Exception e){ 
e.printStackTrace(); 
} 
break; 
} 

} 

} 

} 

作者:chrp99 发表于2013-6-3 20:32:07 原文链接
阅读:60 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>