Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android(12)_解析xml文件1_dom

android(12)_解析xml文件1_dom

編輯:關於Android編程

 DOM解析XML文件時,會將XML文件的所有內容以對象樹方式存放在內存中,然後允許您使用DOM API遍歷XML樹、檢索所需的數據。

使用DOM操作XML的代碼看起來比較直觀,並且,在某些方面比基於SAX的實現更加簡單。

但是,因為DOM需要將XML文件的所有內容以對象樹方式存放在內存中,所以內存的消耗比較大,特別對於運行Android的移動設備來說,因為設備的資源比較寶貴,所以建議還是采用SAX來解析XML文件,當然,如果XML文件的內容比較小采用DOM是可行的。

Strings.xml
[html] 
<?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> 

<?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>

 

activity_xml.xml
[html]
<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> 

<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>


Person.java
[java] 
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.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;
 }

}

XMLDomService.java
[java]
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.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;
 }
}

 

XmlActivity.java
[java] 
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: 
                 
            } 
 
        } 
    } 

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:
    
   }

  }
 }
}

 


 

\
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved