Android数据存储之XmlPull解析XML文件(输出部分)
为了逻辑更清晰,输出部分单独新建一个项目:XmlPullWriteProject
还是先写XmlPullUtll操作类:
构造方法与基本的成员变量:
View Code
public class XmlPullUtil { // 需要两个参数:一个输出流和一个节点对象列表 private OutputStream outputStream = null; private List<Person> persons = null; private XmlPullParserFactory xppFac = null; private XmlSerializer xs = null; // 输出操作使用XmlSerializer类 public XmlPullUtil(OutputStream outputStream, List<Person> persons) { this.outputStream = outputStream; this.persons = persons; }
负责生成Xml的方法:
View Code
public void generateXml() throws XmlPullParserException, IOException{ xppFac = XmlPullParserFactory.newInstance(); xs = xppFac.newSerializer(); // 设置输出流与编码 xs.setOutput(outputStream, "UTF-8"); // 下面的步骤很好理解,按照xml的格式放入各个元素 xs.startDocument("UTF-8", true); xs.startTag(null, "moka"); Iterator<Person> it = persons.iterator(); while (it.hasNext()) { Person person = it.next(); xs.startTag(null, "person"); xs.startTag(null, "id"); xs.text(person.getId()); xs.endTag(null, "id"); xs.startTag(null, "name"); xs.text(person.getName()); xs.endTag(null, "name"); xs.endTag(null, "person"); } xs.endTag(null, "moka"); xs.endDocument(); // 将所有准备的数据放入输出流 xs.flush(); } }
主Activity:
检测储存环境方法与读取篇相同,这里不再写出
View Code
public class MainActivity extends Activity { private EditText idText = null; private EditText nameText = null; private Button saveBtn = null; private File file = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); idText = (EditText) findViewById(R.id.idText); nameText = (EditText) findViewById(R.id.nameText); saveBtn = (Button) findViewById(R.id.saveBtn); saveBtn.setOnClickListener(new SaveBtnListener()); } private class SaveBtnListener implements OnClickListener { @Override public void onClick(View v) { // 首先调用检测储存环境的方法 if(!MainActivity.this.CheckEnvironment()) { return; } else { generateElements(); } } }
generateElements():
View Code
private void generateElements() { // 创建欲添加的节点对象列表 List<Person> persons = new ArrayList<Person>(); for (int i = 0; i < 3; i++) { Person person = new Person(); person.setId("" + i); person.setName("shuai " + i); persons.add(person); } // 实例化XmlPull操作类,调用生成xml文件方法 try { XmlPullUtil xpu = new XmlPullUtil(new FileOutputStream(file), persons); xpu.generateXml(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
生成文档如下: