Android開發(7)--Android中的SAX解析XML檔案

來源:互聯網
上載者:User

一、在assets檔案中寫一個xml檔案
[html] v
<?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中寫一個SAX解析的類

[java]
package com.example.service;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.example.domain.Person;

public class XMLContentHandlerextends DefaultHandler{

//解析的personObject Storage Service到list集合中
private List<Person> persons;
//解析當前的person對象
public Person currentPerson;
//聲明標籤的名稱
public String tagName;


//擷取解析所有的person對象
public List<Person> getPersons() {
return persons;
}

@Override
public void characters(char[] ch,int start, int length)
throws SAXException {

super.characters(ch, start, length);
//首先判斷tagName是否為空白
if(tagName!=null){
String data=new String(ch,start,length);
//判斷標籤是否為空白
if(tagName.equals("name")){
currentPerson.setName(data);
}else if(tagName.equals("age")){//判斷標籤是否是age
currentPerson.setAge((short) Integer.parseInt(data));
}
}
}

@Override
public void endDocument()throws SAXException {

super.endDocument();
}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {

super.endElement(uri, localName, qName);
//當person標籤結束的時候把personObject Storage Service到集合中
if(localName.equals("person")){
persons.add(currentPerson);
currentPerson=null;
}

this.tagName=null;
}

/**
* 文檔開始觸發的事件
*/
@Override
public void startDocument()throws SAXException {

super.startDocument();
persons=new ArrayList<Person>();
}

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {

super.startElement(uri, localName, qName, attributes);
//判斷解析的標籤是否是person
if(localName.equals("person")){
currentPerson=new Person();
//把id屬性的值解析出來 並且把id賦值給currentPerson對象
currentPerson.setId(Integer.parseInt(attributes.getValue(0)));
}

this.tagName=localName;
}

}
[java]
package com.example.service; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import org.xml.sax.Attributes; 
import org.xml.sax.SAXException; 
import org.xml.sax.helpers.DefaultHandler; 
 
import com.example.domain.Person; 
 
public class XMLContentHandler extends DefaultHandler{ 
 
    //解析的personObject Storage Service到list集合中  
            private List<Person> persons; 
            //解析當前的person對象  
            public Person currentPerson; 
            //聲明標籤的名稱  
            public String tagName; 
             
             
            //擷取解析所有的person對象  
            public List<Person> getPersons() { 
                return persons; 
            } 
     
    @Override 
    public void characters(char[] ch, int start, int length) 
            throws SAXException { 
         
        super.characters(ch, start, length); 
        //首先判斷tagName是否為空白  
        if(tagName!=null){ 
            String data=new String(ch,start,length); 
            //判斷標籤是否為空白  
            if(tagName.equals("name")){ 
                currentPerson.setName(data); 
            }else if(tagName.equals("age")){//判斷標籤是否是age  
                currentPerson.setAge((short) Integer.parseInt(data)); 
            } 
        } 
    } 
 
    @Override 
    public void endDocument() throws SAXException { 
         
        super.endDocument(); 
    } 
 
    @Override 
    public void endElement(String uri, String localName, String qName) 
            throws SAXException { 
         
        super.endElement(uri, localName, qName); 
        //當person標籤結束的時候把personObject Storage Service到集合中   
        if(localName.equals("person")){ 
            persons.add(currentPerson); 
            currentPerson=null; 
        } 
         
        this.tagName=null; 
    } 
 
    /**
     * 文檔開始觸發的事件
     */ 
    @Override 
    public void startDocument() throws SAXException { 
         
        super.startDocument(); 
        persons=new ArrayList<Person>(); 
    } 
 
    @Override 
    public void startElement(String uri, String localName, String qName, 
            Attributes attributes) throws SAXException { 
         
        super.startElement(uri, localName, qName, attributes); 
        //判斷解析的標籤是否是person  
        if(localName.equals("person")){ 
            currentPerson=new Person(); 
            //把id屬性的值解析出來 並且把id賦值給currentPerson對象  
            currentPerson.setId(Integer.parseInt(attributes.getValue(0))); 
        } 
         
        this.tagName=localName; 
    } 
     

package com.example.service;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.example.domain.Person;

public class XMLContentHandler extends DefaultHandler{

 //解析的personObject Storage Service到list集合中
   private List<Person> persons;
   //解析當前的person對象
   public Person currentPerson;
   //聲明標籤的名稱
   public String tagName;
   
   
   //擷取解析所有的person對象
   public List<Person> getPersons() {
    return persons;
   }
 
 @Override
 public void characters(char[] ch, int start, int length)
   throws SAXException {
  
  super.characters(ch, start, length);
  //首先判斷tagName是否為空白
  if(tagName!=null){
   String data=new String(ch,start,length);
   //判斷標籤是否為空白
   if(tagName.equals("name")){
    currentPerson.setName(data);
   }else if(tagName.equals("age")){//判斷標籤是否是age
    currentPerson.setAge((short) Integer.parseInt(data));
   }
  }
 }

 @Override
 public void endDocument() throws SAXException {
  
  super.endDocument();
 }

 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {
  
  super.endElement(uri, localName, qName);
  //當person標籤結束的時候把personObject Storage Service到集合中
  if(localName.equals("person")){
   persons.add(currentPerson);
   currentPerson=null;
  }
  
  this.tagName=null;
 }

 /**
  * 文檔開始觸發的事件
  */
 @Override
 public void startDocument() throws SAXException {
  
  super.startDocument();
  persons=new ArrayList<Person>();
 }

 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {
  
  super.startElement(uri, localName, qName, attributes);
  //判斷解析的標籤是否是person
  if(localName.equals("person")){
   currentPerson=new Person();
   //把id屬性的值解析出來 並且把id賦值給currentPerson對象
   currentPerson.setId(Integer.parseInt(attributes.getValue(0)));
  }
  
  this.tagName=localName;
 }
 
}
三、在Activity中擷取SAX類的操作
[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.