Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android三種方式解析Xml

Android三種方式解析Xml

編輯:關於Android編程

在Android中,常見的XML解析器分別為SAX解析器、DOM解析器和PULL解析器

SAX解析器:

SAX(Simple API for XML)解析器是一種基於事件的解析器,它的核心是事件處理模式,主要是圍繞著事件源以及事件處理器來工作的。當事件源產生事件後,調用事件處理器相應的處理方法,一個事件就可以得到處理。在事件源調用事件處理器中特定方法的時候,還要傳遞給事件處理器相應事件的狀態信息,這樣事件處理器才能夠根據提供的事件信息來決定自己的行為。

SAX解析器的優點是解析速度快,占用內存少。非常適合在Android移動設備中使用。

DOM解析器:

DOM是基於樹形結構的的節點或信息片段的集合,允許開發人員使用DOM API遍歷XML樹、檢索所需數據。分析該結構通常需要加載整個文檔和構造樹形結構,然後才可以檢索和更新節點信息。

由於DOM在內存中以樹形結構存放,因此檢索和更新效率會更高。但是對於特別大的文檔,解析和加載整個文檔將會很耗資源。

PULL解析器:

PULL解析器的運行方式和SAX類似,都是基於事件的模式。不同的是,在PULL解析過程中,我們需要自己獲取產生的事件然後做相應的操作,而不像SAX那樣由處理器觸發一種事件的方法,執行我們的代碼。PULL解析器小巧輕便,解析速度快,簡單易用,非常適合在Android移動設備中使用,Android系統內部在解析各種XML時也是用PULL解析器。


下面我們做一個demo來具體實現下

首先在Androidmanifest.xml中添加權限,此權限用於輸出xml文件


departments.xml被解析的xml文件



    
        1001
        張三
        8000.0
        
     
        1002
        李四
        9000.0
        
     
        1003
        王五
        10000.0
        



封裝實體類Department

public class Department {

	private int id;
	
	private String name;
	
	private float salary;

	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 float getSalary() {
		return salary;
	}

	public void setSalary(float salary) {
		this.salary = salary;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		 return "id:" + id + ", name:" + name + ", salary:" + salary;  
	}
	
}


為解析器定義一個DepartParser接口,每種類型的解析器需要實現此接口

public interface DepartParser {

	/**
	 * 解析輸入流 得到Department對象集合
	 * @param is
	 * @return
	 * @throws Exception
	 */
	public List parse(InputStream is) throws Exception;

	/**
	 * 序列化Department對象集合,得到XML形式的字符串
	 * @param departs
	 * @return
	 * @throws Exception
	 */
	public String serialize(List departs) throws Exception;
}


serialize(List)解析出來的數據樣式如下:



    
        張三
        8000.0
        
     
        李四
        9000.0
        
     
        王五
        10000.0
        


使用SAX解析

import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

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

/**
 * Sax方式解析
 * 
 * @author 孟祥程
 * 
 */
public class SaxDepartmentParser implements DepartParser {

	@Override
	public List parse(InputStream is) throws Exception {
		// TODO Auto-generated method stub
		// 取得SAXParserFactory實例
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 從factory獲取SAXParser實例
		SAXParser parser = factory.newSAXParser();
		// 實例化自定義Handler
		MyHandler handler = new MyHandler();
		// 根據自定義Handler規則解析輸入流
		parser.parse(is, handler);
		return handler.getDeparts();
	}

	@Override
	public String serialize(List departs) throws Exception {
		// TODO Auto-generated method stub
		SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory
				.newInstance();
		TransformerHandler handler = factory.newTransformerHandler(); // 從factory獲取TransformerHandler實例
		Transformer transformer = handler.getTransformer(); // 從handler獲取Transformer實例
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // 設置輸出采用的編碼方式
		transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // 是否自動添加額外的空白
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // 是否忽略XML聲明
		
		StringWriter writer = new StringWriter();
		//Result result = new StreamResult();這樣的話,handler.startDocument()會報 No output specified異常
		Result result = new StreamResult(writer);
		handler.setResult(result);
		
		String uri = "";//代表命名空間的URI 當URI無值時 須置為空字符串  
		String localName = "";//命名空間的本地名稱(不包含前綴) 當沒有進行命名空間處理時 須置為空字符串 

	
		handler.startDocument();
		handler.startElement(uri, localName, "department", null);
		
		AttributesImpl attrs = new AttributesImpl();   //負責存放元素的屬性信息  
		char[] ch = null;
		
		  for (Department depart : departs) {  
	            attrs.clear();  //清空屬性列表  
	            attrs.addAttribute(uri, localName, "id", "string", String.valueOf(depart.getId()));//添加一個名為id的屬性(type影響不大,這裡設為string)  
	            handler.startElement(uri, localName, "person", attrs);    //開始一個元素 關聯上面設定的id屬性  
	              
	            handler.startElement(uri, localName, "name", null); //開始一個name元素 沒有屬性  
	            ch = String.valueOf(depart.getName()).toCharArray();  
	            handler.characters(ch, 0, ch.length);   //設置name元素的文本節點  
	            handler.endElement(uri, localName, "name");  
	              
	            handler.startElement(uri, localName, "salary", null);//開始一個price元素 沒有屬性  
	            ch = String.valueOf(depart.getSalary()).toCharArray();  
	            handler.characters(ch, 0, ch.length);   //設置price元素的文本節點  
	            handler.endElement(uri, localName, "salary");  
	              
	            handler.endElement(uri, localName, "person");  
	        }  
	        handler.endElement(uri, localName, "department");  
	        handler.endDocument();  
	          
	        return writer.toString();  
	        
	}

	/**
	 * DefaultHandler是一個事件處理器,可以接收解析器報告的所有事件,處理所發現的數據
	 * 
	 * @author 孟祥程
	 * 
	 */
	private class MyHandler extends DefaultHandler {
		private List departs;
		private Department depart;
		private StringBuilder builder;

		// 返回解析後得到的Department對象集合
		public List getDeparts() {
			return departs;
		}

		@Override
		public void startDocument() throws SAXException {
			// TODO Auto-generated method stub
			super.startDocument();
			departs = new ArrayList();
			builder = new StringBuilder();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			// TODO Auto-generated method stub
			super.startElement(uri, localName, qName, attributes);
			if (localName.equals("person")) {
				depart = new Department();
			}
			// 將字符長度設置為0 以便重新開始讀取元素內的字符節點
			builder.setLength(0);
		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			// TODO Auto-generated method stub
			super.characters(ch, start, length);
			// 將讀取的字符數組追加到builder中
			builder.append(ch, start, length);//將讀取的字符數組追加到builder中  
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			// TODO Auto-generated method stub
			super.endElement(uri, localName, qName);
			if (localName.equals("id")) {
				depart.setId(Integer.parseInt(builder.toString()));
			} else if (localName.equals("name")) {
				depart.setName(builder.toString());
			} else if (localName.equals("salary")) {
				depart.setSalary(Float.parseFloat(builder.toString()));
			} else if (localName.equals("person")) {
				departs.add(depart);
			}
		}

	}

}


使用DOM解析方式

import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
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.Node;
import org.w3c.dom.NodeList;

public class DomDepartmentParser implements DepartParser{

	@Override
	public List parse(InputStream is) throws Exception {
		// TODO Auto-generated method stub
		List departs  = new ArrayList();
		 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  //取得DocumentBuilderFactory實例  
	        DocumentBuilder builder = factory.newDocumentBuilder(); //從factory獲取DocumentBuilder實例  
	        Document doc = builder.parse(is);   //解析輸入流 得到Document實例  
	        Element rootElement = doc.getDocumentElement();  
	        NodeList items = rootElement.getElementsByTagName("person");  
	        for (int i = 0; i < items.getLength(); i++) {  
	            Department depart = new Department();  
	            Node item = items.item(i);  
	            NodeList properties = item.getChildNodes();  
	            for (int j = 0; j < properties.getLength(); j++) {  
	                Node property = properties.item(j);  
	                String nodeName = property.getNodeName();  
	                if (nodeName.equals("id")) {  
	                	depart.setId(Integer.parseInt(property.getFirstChild().getNodeValue()));  
	                } else if (nodeName.equals("name")) {  
	                	depart.setName(property.getFirstChild().getNodeValue());  
	                } else if (nodeName.equals("salary")) {  
	                	depart.setSalary(Float.parseFloat(property.getFirstChild().getNodeValue()));  
	                }  
	            }  
	            departs.add(depart);  
	        }  
	        return departs;  
	}

	@Override
	public String serialize(List departs) throws Exception {
		// TODO Auto-generated method stub
		 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
	        DocumentBuilder builder = factory.newDocumentBuilder();  
	        Document doc = builder.newDocument();   //由builder創建新文檔  
	          
	        Element rootElement = doc.createElement("department");  
	  
	        for (Department depart : departs) {  
	            Element departElement = doc.createElement("person");  
	            departElement.setAttribute("id", depart.getId() + "");  
	              
	            Element nameElement = doc.createElement("name");  
	            nameElement.setTextContent(depart.getName());  
	            departElement.appendChild(nameElement);  
	              
	            Element priceElement = doc.createElement("salary");  
	            priceElement.setTextContent(depart.getSalary() + "");  
	            departElement.appendChild(priceElement);  
	              
	            rootElement.appendChild(departElement);  
	        }  
	          
	        doc.appendChild(rootElement);  
	          
	        TransformerFactory transFactory = TransformerFactory.newInstance();//取得TransformerFactory實例  
	        Transformer transformer = transFactory.newTransformer();    //從transFactory獲取Transformer實例  
	        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");            // 設置輸出采用的編碼方式  
	        transformer.setOutputProperty(OutputKeys.INDENT, "yes");                // 是否自動添加額外的空白  
	        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");   // 是否忽略XML聲明  
	          
	        StringWriter writer = new StringWriter();  
	          
	        Source source = new DOMSource(doc); //表明文檔來源是doc  
	        Result result = new StreamResult(writer);//表明目標結果為writer  
	        transformer.transform(source, result);  //開始轉換  
	          
	        return writer.toString();  
	}

}

使用PULL解析

import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

public class PullDepartmentParser implements DepartParser {  
    
  @Override  
  public List parse(InputStream is) throws Exception {  
      List departs = null;  
      Department depart = null;  
        
        
      XmlPullParser parser = Xml.newPullParser(); //由android.util.Xml創建一個XmlPullParser實例  
      parser.setInput(is, "UTF-8");               //設置輸入流 並指明編碼方式  

      int eventType = parser.getEventType();  
      while (eventType != XmlPullParser.END_DOCUMENT) {  
          switch (eventType) {  
          case XmlPullParser.START_DOCUMENT:  
        	  departs = new ArrayList();  
              break;  
          case XmlPullParser.START_TAG:  
              if (parser.getName().equals("person")) {  
            	  depart = new Department();  
              } else if (parser.getName().equals("id")) {  
                  eventType = parser.next();  
                  depart.setId(Integer.parseInt(parser.getText()));  
              } else if (parser.getName().equals("name")) {  
                  eventType = parser.next();  
                  depart.setName(parser.getText());  
              } else if (parser.getName().equals("salary")) {  
                  eventType = parser.next();  
                  depart.setSalary(Float.parseFloat(parser.getText()));  
              }  
              break;  
          case XmlPullParser.END_TAG:  
              if (parser.getName().equals("person")) {  
            	  departs.add(depart);  
            	  depart = null;      
              }  
              break;  
          }  
          eventType = parser.next();  
      }  
      return departs;  
  }  
    
  @Override  
  public String serialize(List departs) throws Exception {  
        
      XmlSerializer serializer = Xml.newSerializer(); //由android.util.Xml創建一個XmlSerializer實例  
      StringWriter writer = new StringWriter();  
      serializer.setOutput(writer);   //設置輸出方向為writer  
      serializer.startDocument("UTF-8", true);  
      serializer.startTag("", "department");  
      for (Department depart : departs) {  
          serializer.startTag("", "person");  
          serializer.attribute("", "id", depart.getId() + "");  
            
          serializer.startTag("", "name");  
          serializer.text(depart.getName());  
          serializer.endTag("", "name");  
            
          serializer.startTag("", "salary");  
          serializer.text(depart.getSalary() + "");  
          serializer.endTag("", "salary");  
            
          serializer.endTag("", "person");  
      }  
      serializer.endTag("", "department");  
      serializer.endDocument();  
        
      return writer.toString();  
  }  
}  

布局文件activity_main.xml



   

Activity代碼

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
	private static final String TAG = "XML";

	private DepartParser parser;
	private List departs;

	private Button saxIn, domIn, pullIn, outXml;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		saxIn = (Button) findViewById(R.id.btn_sax);
		saxIn.setOnClickListener(this);
		domIn = (Button) findViewById(R.id.btn_dom);
		domIn.setOnClickListener(this);
		pullIn = (Button) findViewById(R.id.btn_pull);
		pullIn.setOnClickListener(this);
		outXml = (Button) findViewById(R.id.btn_outxml);
		outXml.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		switch (id) {
		case R.id.btn_sax:
			saxReadXml();
			break;
		case R.id.btn_dom:
			domReadXml();
			break;
		case R.id.btn_pull:
			pullReadXml();
			break;
		case R.id.btn_outxml:
			writeXml();
			break;
	
		}
	}
	
	private void saxReadXml(){
		try {
			InputStream is = getAssets().open("departs.xml");
			parser = new SaxDepartmentParser(); // 創建SaxDepartParser實例
			departs = parser.parse(is); // 解析輸入流
			for (Department depart : departs) {
				Log.i(TAG, "sax read xml:"+depart.toString());
			}
		} catch (Exception e) {
			Log.e(TAG, "sax read xml:"+e.getMessage());
		}
	}
	
	private void domReadXml(){
		try {  
	        InputStream is = getAssets().open("departs.xml");  
	        parser = new DomDepartmentParser();  
	        departs = parser.parse(is);  
	        for (Department depart : departs) {  
	            Log.i(TAG, "dom read xml:"+depart.toString());  
	        }  
	    } catch (Exception e) {  
	        Log.e(TAG, "dom read xml:"+e.getMessage());  
	    }  
	}
	
	private void pullReadXml(){
		 try {  
             InputStream is = getAssets().open("departs.xml");  
             parser = new PullDepartmentParser();  
             departs = parser.parse(is);  
             for (Department depart : departs) {  
                 Log.i(TAG, "pull read xml:"+depart.toString());  
             }  
         } catch (Exception e) {  
             Log.e(TAG, "pull read xml:"+e.getMessage());  
         }  
	}
	
	private void writeXml(){
		 try {  
             String xml = parser.serialize(departs);  //序列化  
             File dir = null;
             if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
            	  dir = new File(Environment.getExternalStorageDirectory()+"/xml");
            	  if(!dir.exists()){
            		  System.out.println("mkdirs:"+dir.mkdirs());
            	  }
             }
             File file = new File(dir.getPath(), "departs.xml"); 
 			if (file.exists()) {
 				file.delete();
 			}
 			file.createNewFile();
 			FileOutputStream out = new FileOutputStream(file);
 			out.write(xml.getBytes("UTF-8"));
 			out.flush();
 			out.close();
         } catch (Exception e) {  
             Log.e(TAG, e.getMessage());  
         }  
	}
	
	
}

輸出文件在sd卡xml文件夾下,每獲取一遍xml就可以輸出一遍
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved