DOM解析XML文件时,会将XML文件的所有内容以对象树方式存放在内存中,然后允许您使用DOM API遍历XML树、检索所需的数据。
使用DOM操作XML的代码看起来比较直观,并且,在某些方面比基于SAX的实现更加简单。
但是,因为DOM需要将XML文件的所有内容以对象树方式存放在内存中,所以内存的消耗比较大,特别对于运行Android的移动设备来说,因为设备的资源比较宝贵,所以建议还是采用SAX来解析XML文件,当然,如果XML文件的内容比较小采用DOM是可行的。
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">lession03_xml</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="btn_sax">采用sax解析xml文件</string> <string name="btn_dom">采用dom解析方式解析</string> <string name="btn_pull">采用pull解析方式解析</string> <string name="btn_cpull">采用pull解析生成xml文件</string> </resources>
<RelativeLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".XmlActivity" > <Button android:id="@+id/button_cpull" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btn_pull" android:layout_alignRight="@+id/btn_pull" android:layout_below="@+id/btn_pull" android:layout_marginTop="20dp" android:text="@string/btn_cpull" /> <Button android:id="@+id/btn_sax" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:text="@string/btn_sax" /> <Button android:id="@+id/btn_pull" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btn_dom" android:layout_alignRight="@+id/btn_dom" android:layout_below="@+id/btn_dom" android:layout_marginTop="68dp" android:text="@string/btn_pull" /> <Button android:id="@+id/btn_dom" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btn_sax" android:layout_alignRight="@+id/btn_sax" android:layout_below="@+id/btn_sax" android:layout_marginTop="60dp" android:text="@string/btn_dom" /> </RelativeLayout>
package com.example.lession03_xml.domain; import java.io.Serializable; /** * 创建一个javabean存储xml解析的数据 * * @author chenhj * */ public class Person implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private short age; public Person() { super(); // TODO Auto-generated constructor stub } public Person(int id, String name, short age) { super(); this.id = id; this.name = name; this.age = 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; } }
package com.example.lession03_xml.service; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.example.lession03_xml.domain.Person; public class XMLDomService { public List<Person> parseXML(InputStream inStream) { List<Person> list = new ArrayList<Person>(); // 创建dom工厂对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { // DocumentBuilder对象 DocumentBuilder builder = factory.newDocumentBuilder(); // 传过来instrean文件,得到document文档对象 Document document = builder.parse(inStream); // 获取文档对象的根root Element root = document.getDocumentElement(); // 获取person根节点中所有的person子节点 NodeList items = root.getElementsByTagName("person"); // 便利所有的 person节点 for (int i = 0; i < items.getLength(); i++) { Person person = new Person(); // 得到第一个person节点 Element personNode = (Element) items.item(i); // 获取person节点的id属性值 person.setId(new Integer(personNode.getAttribute("id"))); // 获取person节点下的所有子节点(标签之间的空白节点和name/age元素) NodeList childsNodes = personNode.getChildNodes(); // 遍历person的子节点 for (int index = 0; index < childsNodes.getLength(); index++) { // 获取子节点 Node node = (Node) childsNodes.item(index); // 判断是否为元素类型,是不是元素节点 if (node.getNodeType() == Node.ELEMENT_NODE) { //是元素节点需要造型 Element childNode = (Element) node; // 判断是否name元素 if ("name".equals(childNode.getNodeName())) { // 获取name元素下Text节点,然后从Text节点获取数据 person.setName(childNode.getFirstChild().getNodeValue()); } else if ("age".equals(childNode.getNodeName())) { person.setAge(new Short(childNode.getFirstChild() .getNodeValue())); } } } //把person对象加入到集合当中 list.add(person); } inStream.close(); } catch (Exception e) { e.printStackTrace(); } return list; } }
package com.example.lession03_xml; import java.io.InputStream; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import com.example.lession03_xml.domain.Person; import com.example.lession03_xml.service.XMLContentHandlerService; import com.example.lession03_xml.service.XMLDomService; import com.example.lession03_xml.service.XMLPullService; 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 XmlActivity extends Activity { // 声明控件 public Button btn_sax, btn_dom, btn_pull, btn_cpull; public XMLDomService xmlDomService; public XMLPullService xmlPullService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置显示的视图 setContentView(R.layout.activity_xml); // 实例化 xmlDomService = new XMLDomService(); xmlPullService = new XMLPullService(); // 通过findViewById方法获取控件对象 btn_sax = (Button) findViewById(R.id.btn_sax); btn_dom = (Button) findViewById(R.id.btn_dom); btn_pull = (Button) findViewById(R.id.btn_pull); btn_cpull = (Button) findViewById(R.id.button_cpull); // 给按钮注册事件 btn_sax.setOnClickListener(new MyClickListener()); btn_dom.setOnClickListener(new MyClickListener()); btn_pull.setOnClickListener(new MyClickListener()); btn_cpull.setOnClickListener(new MyClickListener()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.xml, menu); return true; } class MyClickListener implements View.OnClickListener { @Override public void onClick(View v) { // 获取组件的id int id = v.getId(); switch (id) { case R.id.btn_sax: break; case R.id.btn_dom: InputStream is = null; try { // 获取读取文件的输入流对象 is = getAssets().open("csdn.xml"); // 采用 List<Person> persons = xmlDomService.parseXML(is); // Toast.makeText(XmlActivity.this, "" + persons.get(0).getName(), Toast.LENGTH_LONG) .show(); } catch (Exception e) { e.printStackTrace(); } break; case R.id.btn_pull: break; case R.id.button_cpull: } } } }