Android笔记(四十五) Android中的数据存储——XML(一)DOM解析器
DOM解析XML在j2ee开发中比较常见,在Dom解析的过程中,是先把dom全部文件读入到内存中,然后使用dom的api遍历所有数据,检索想要的数据,这种方式显然是一种比较消耗内存的方式,对于像手机这样的移动设备来讲,内存是非常有限的,所以对于比较大的XML文件,不推荐使用这种方式,但是Dom也有它的优点,它比较直观,在xml文档比较小的情况下也可以考虑使用dom方式。
代码演示:
MainActivity.java
package cn.lixyz.xmltest.activity; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import cn.lixyz.xmltest.R; import cn.lixyz.xmltest.model.Student; public class MainActivity extends Activity { private Button bt_readxml_dom, bt_writexml_dom; private List<Student> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findView(); } private void findView() { bt_readxml_dom = (Button) findViewById(R.id.bt_readxml_dom); } public void clickButton(View view) { switch (view.getId()) { case R.id.bt_readxml_dom: domReadXML(); break; case R.id.bt_writexml_dom: domWriteXML(); break; } } // dom方式生成xml private void domWriteXML() { // 生成xml文件的数据 List<Student> dataList = createStudents(); try { // 利用DocumentBuilderFactory创建一个DocumentBuilderFactory实例 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 利用DocumentBuilderFactory创建DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // 利用DocumentBuilder创建Document文件 Document document = builder.newDocument(); // 创建根节点Students Element element = document.createElement("Students"); // 将根节点添加到document中 document.appendChild(element); // 用循环将数据添加到document中 for (int i = 0; i < dataList.size(); i++) { // 获取第i个数据对象 Student student = dataList.get(i); // 创建student元素 Element studentElement = document.createElement("student"); // 设置student元素的属性id studentElement.setAttribute("id", student.getId() + ""); // 把student节点添加到document中 element.appendChild(studentElement); // 添加name节点 Element name = document.createElement("name"); // 给name元素设置值 name.setTextContent(student.getName()); // 添加到student节点中 studentElement.appendChild(name); // 添加name节点 Element age = document.createElement("age"); // 给age元素设置值 age.setTextContent(student.getAge() + ""); // 添加到student节点中 studentElement.appendChild(age); } // 使用TransformerFactory创建一个TransformerFactory对象 TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); // 创建文件存放在 /data/data/cn.xxx.xxx(当前包)/files FileOutputStream fos = openFileOutput("Dom.xml", Context.MODE_PRIVATE); PrintWriter pw = new PrintWriter(fos); StreamResult result = new StreamResult(pw); transformer.transform(source, result); Toast.makeText(MainActivity.this, "生成成功", Toast.LENGTH_LONG).show(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // dom方式读取xml文件 private void domReadXML() { try { // 利用DocumentBuilderFactory创建一个DocumentBuilderFactory实例 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 利用DocumentBuilderFactory创建DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // 加载XML文档(Document) FileInputStream is = this.getBaseContext().openFileInput("Dom.xml"); // 调用完这句后XML文档解析完成,暂存在内存中 Document document = builder.parse(is); // 获取文档的根结点(Element) Element rootElement = document.getDocumentElement(); // 获取根结点中所有子节点的列表(NodeList) NodeList element = rootElement.getElementsByTagName("student"); for (int i = 0; i < element.getLength(); i++) { // 使用getElementsByTagName再获取子节点列表中的需要读取的结点 Element node = (Element) element.item(i); String id = node.getAttribute("id"); String name = node.getElementsByTagName("name").item(0).getTextContent(); int age = Integer.parseInt(node.getElementsByTagName("age").item(0).getTextContent()); Log.d("TTTT", "id=" + id + ",name=" + name + ",age=" + age); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 模拟生成xml的数据 private List<Student> createStudents() { list = new ArrayList<Student>(); Student s1 = new Student(); s1.setId(11); s1.setName("张三"); s1.setAge(10); list.add(s1); Student s2 = new Student(); s2.setId(22); s2.setName("李四"); s2.setAge(11); list.add(s2); Student s3 = new Student(); s3.setId(33); s3.setName("王五"); s3.setAge(12); list.add(s3); Student s4 = new Student(); s4.setId(44); s4.setName("赵六"); s4.setAge(13); list.add(s4); Student s5 = new Student(); s5.setId(55); s5.setName("刘七"); s5.setAge(14); list.add(s5); return list; } }
activity_main.xml
<ScrollView 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" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="cn.lixyz.xmltest.activity.MainActivity" > <Button android:id="@+id/bt_writexml_dom" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="clickButton" android:text="DOM方式生成XML" /> <Button android:id="@+id/bt_readxml_dom" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="clickButton" android:text="DOM方式读取XML" /> </LinearLayout> </ScrollView>
Student.java
package cn.lixyz.xmltest.model; public class Student { private int id; private String name; private int 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } }