Android開發(8)--Android中DOM解析xml檔案

來源:互聯網
上載者:User

一、在assets檔案中寫xml檔案

[html]
<?xmlversion="1.0"encoding="UTF-8"?>
<persons>
<personid="23">
<name>李明</name>
<age>30</age>
</person>
<personid="20">
<name>李向梅</name>
<age>25</age>
</person>
</persons>
[html]
<?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 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>
二、在service中寫一個DOM解析的操作

[java]
package com.example.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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.example.domain.Person;

 

public class XMLDomService {

public List<Person> parseXML(InputStream is) {

List<Person> list = new ArrayList<Person>();

// 建立DOM工廠對象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

try {
// DocumentBuilder對象
DocumentBuilder builder = factory.newDocumentBuilder();

// 擷取文檔對象
Document document = builder.parse(is);

// 擷取文檔對象的root
Element root = document.getDocumentElement();

// 擷取persons根節點中所有的person節點對象

NodeList personNodes = root.getElementsByTagName("person");

// 遍曆所有的person節點

for (int i =0; i < personNodes.getLength(); i++) {
Person person = new Person();
// 根據item(index)擷取該索引對應的節點對象
Element personNode = (Element) personNodes.item(i); // 具體的person節點
// 設定id屬性值
person.setId(Integer.parseInt(personNode.getAttribute("id")));

// 擷取該節點下面的所有位元組點
NodeList personChildNodes = personNode.getChildNodes();

// 遍曆person的位元組點
for (int index =0; index < personChildNodes.getLength(); index++) {
// 擷取子節點
Node node = personChildNodes.item(index);

// 判斷node節點是否是元素節點
if (node.getNodeType() == Node.ELEMENT_NODE) {
//把節點轉換成元素節點
Element element = (Element) node;

//判斷元素節點是否是name元素節點
if ("name".equals(element.getNodeName())) {
person.setName(element.getFirstChild()
.getNodeValue());
} else if ("age".equals(element.getNodeName())) {//判斷是否是age節點
person.setAge(new Short(element.getFirstChild()
.getNodeValue()));
}
}

}

// 把person對象加入到集合中
list.add(person);

}
//關閉輸入資料流
is.close();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return list;
}
}
[java]
package com.example.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.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
 
import com.example.domain.Person; 
 
 
 
public class XMLDomService { 
 
    public List<Person> parseXML(InputStream is) { 
 
        List<Person> list = new ArrayList<Person>(); 
 
        // 建立DOM工廠對象  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
 
        try { 
            // DocumentBuilder對象  
            DocumentBuilder builder = factory.newDocumentBuilder(); 
 
            // 擷取文檔對象  
            Document document = builder.parse(is); 
 
            // 擷取文檔對象的root  
            Element root = document.getDocumentElement(); 
 
            // 擷取persons根節點中所有的person節點對象  
 
            NodeList personNodes = root.getElementsByTagName("person"); 
 
            // 遍曆所有的person節點  
 
            for (int i = 0; i < personNodes.getLength(); i++) { 
                Person person = new Person(); 
                // 根據item(index)擷取該索引對應的節點對象  
                Element personNode = (Element) personNodes.item(i); // 具體的person節點  
                // 設定id屬性值  
                person.setId(Integer.parseInt(personNode.getAttribute("id"))); 
 
                // 擷取該節點下面的所有位元組點  
                NodeList personChildNodes = personNode.getChildNodes(); 
 
                // 遍曆person的位元組點  
                for (int index = 0; index < personChildNodes.getLength(); index++) { 
                    // 擷取子節點  
                    Node node = personChildNodes.item(index); 
 
                    // 判斷node節點是否是元素節點  
                    if (node.getNodeType() == Node.ELEMENT_NODE) { 
                        //把節點轉換成元素節點  
                        Element element = (Element) node; 
 
                        //判斷元素節點是否是name元素節點  
                        if ("name".equals(element.getNodeName())) { 
                            person.setName(element.getFirstChild() 
                                    .getNodeValue()); 
                        } else if ("age".equals(element.getNodeName())) { //判斷是否是age節點  
                            person.setAge(new Short(element.getFirstChild() 
                                    .getNodeValue())); 
                        } 
                    } 
 
                } 
 
                // 把person對象加入到集合中  
                list.add(person); 
 
            } 
            //關閉輸入資料流  
            is.close(); 
 
        } catch (Exception e) { 
            // TODO Auto-generated catch block  
            e.printStackTrace(); 
        } 
 
        return list; 
    } 

package com.example.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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.example.domain.Person;

 

public class XMLDomService {

 public List<Person> parseXML(InputStream is) {

  List<Person> list = new ArrayList<Person>();

  // 建立DOM工廠對象
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  try {
   // DocumentBuilder對象
   DocumentBuilder builder = factory.newDocumentBuilder();

   // 擷取文檔對象
   Document document = builder.parse(is);

   // 擷取文檔對象的root
   Element root = document.getDocumentElement();

   // 擷取persons根節點中所有的person節點對象

   NodeList personNodes = root.getElementsByTagName("person");

   // 遍曆所有的person節點

   for (int i = 0; i < personNodes.getLength(); i++) {
    Person person = new Person();
    // 根據item(index)擷取該索引對應的節點對象
    Element personNode = (Element) personNodes.item(i); // 具體的person節點
    // 設定id屬性值
    person.setId(Integer.parseInt(personNode.getAttribute("id")));

    // 擷取該節點下面的所有位元組點
    NodeList personChildNodes = personNode.getChildNodes();

    // 遍曆person的位元組點
    for (int index = 0; index < personChildNodes.getLength(); index++) {
     // 擷取子節點
     Node node = personChildNodes.item(index);

     // 判斷node節點是否是元素節點
     if (node.getNodeType() == Node.ELEMENT_NODE) {
      //把節點轉換成元素節點
      Element element = (Element) node;

      //判斷元素節點是否是name元素節點
      if ("name".equals(element.getNodeName())) {
       person.setName(element.getFirstChild()
         .getNodeValue());
      } else if ("age".equals(element.getNodeName())) { //判斷是否是age節點
       person.setAge(new Short(element.getFirstChild()
         .getNodeValue()));
      }
     }

    }

    // 把person對象加入到集合中
    list.add(person);

   }
   //關閉輸入資料流
   is.close();

  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return list;
 }
}

三、在Activity中顯示操作

[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.domain.Person;
import com.example.service.XMLContentHandler;
import com.example.service.XMLDomService;

 

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

public class XmlActivityextends Activity {

//聲明組件
public Button btn_sax,btn_dom,btn_pull;

public XMLDomService xmlDomService;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//設定顯示的視圖
setContentView(R.layout.activity_xml);

xmlDomService=new XMLDomService();
//根據id擷取組件
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_sax.setOnClickListener(new MyOnclickListener());
btn_dom.setOnClickListener(new MyOnclickListener());
btn_pull.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.xml, menu);
return true;
}

//匿名類
class MyOnclickListener implements OnClickListener{

@Override
public void onClick(View v) {
int id=v.getId();
switch (id) {
case R.id.btn_sax:
Toast.makeText(XmlActivity.this,"採用SAX解析", Toast.LENGTH_LONG).show();
try{
//SAX解析的工廠對象
SAXParserFactory factory=SAXParserFactory.newInstance();
//得到sax的解析器
SAXParser saxParser=factory.newSAXParser();
//建立handler對象
XMLContentHandler handlerService=new XMLContentHandler();
InputStream is=getAssets().open("csdn.xml");
//直接解析
saxParser.parse(is, handlerService);
//通過handlerService對象擷取
Toast.makeText(XmlActivity.this,"----"+handlerService, Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}

break;
case R.id.btn_dom:

InputStream is=null;
try{
//擷取讀取檔案的輸入資料流對象
is=getAssets().open("csdn.xml");
//採用dom解析
List<Person> persons=xmlDomService.parseXML(is);
//簡單測試
//Toast.makeText(XmlActivity.this, ""+persons.get(0).getName(), Toast.LENGTH_LONG).show();
Toast.makeText(XmlActivity.this,"採用DOM解析"+persons.get(0).getName(), Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}


break;
case R.id.btn_pull:
Toast.makeText(XmlActivity.this,"採用PULL解析", Toast.LENGTH_LONG).show();
break;

default:
break;
}

}

}
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.