Java在android中xml文件解析效率比較分析

在Android中,常見的XML解析器分別爲SAX解析器、DOM解析器和PULL解析器,下面,我將一一貫你們詳細介紹。java

SAX解析器:node

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

SAX解析器的優勢是解析速度快,佔用內存少。很是適合在Android移動設備中使用。數組

DOM解析器:app

DOM是基於樹形結構的的節點或信息片斷的集合,容許開發人員使用DOM API遍歷XML樹、檢索所需數據。分析該結構一般須要加載整個文檔和構造樹形結構,而後才能夠檢索和更新節點信息。dom

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

PULL解析器:ui

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

 

<?xml version="1.0" encoding="UTF-8"?>  
<persons>  
    <person id="1">  
        <name>sax</name>  
        <age>30</age>  
    </person>  
    <person id="2">  
        <name>dom</name>  
        <age>40</age>  
    </person>  
    <person id="3">  
        <name>pull</name>  
        <age>50</age>  
    </person>  
    <person id="4">  
        <name>ouyangpeng</name>  
        <age>60</age>  
    </person>  
    <person id="5">  
        <name>chengming</name>  
        <age>70</age>  
    </person>  
    <person id="6">  
        <name>just for test</name>  
        <age>80</age>  
    </person>  
</persons>
public class Person {  
    private Integer id;  
    private String name;  
    private Integer age;  
      
    public Integer getId() {  
        return id;  
    }  
    public void setId(Integer id) {  
        this.id = id;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public Integer getAge() {  
        return age;  
    }  
    public void setAge(Integer age) {  
        this.age = age;  
    }  
      
    @Override    
       public String toString() {    
           return "id:" + id + ", name:" + name + ", age:" + age;    
       }    
}
import java.io.InputStream;  
import java.io.OutputStream;  
import java.util.List;  
  
import cn.roco.xml.domain.Person;  
  
public interface IPersonService {  
    /** 
     * 獲取數據 
     * @param is  輸入方向 
     * @return   數據 
     * @throws Exception 
     */  
    public List<Person> parse(InputStream is) throws Exception;  
    /** 
     * 保存數據 
     * @param persons  數據 
     * @param out  輸出方向 
     * @throws Exception 
     */  
    public void serialize(List<Person> persons, OutputStream out)  
            throws Exception;  
}

SAX解析編碼

import java.io.InputStream;  
import java.io.OutputStream;  
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;  
  
import cn.roco.xml.domain.Person;  
import cn.roco.xml.service.IPersonService;  
  
public class PersonServiceImpBySax implements IPersonService {  
  
    @Override  
    public void serialize(List<Person> persons, OutputStream out)  
            throws Exception {  
        SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory  
                .newInstance();// 取得SAXTransformerFactory實例  
        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聲明  
  
        Result result=new StreamResult(out);  
        handler.setResult(result);  
          
        String uri = ""; // 表明命名空間的URI 當URI無值時 須置爲空字符串  
        String localName = ""; // 命名空間的本地名稱(不包含前綴) 當沒有進行命名空間處理時 須置爲空字符串  
          
        handler.startDocument();  
        handler.startElement(uri, localName, "persons", null);  
  
        AttributesImpl attrs = new AttributesImpl(); // 負責存放元素的屬性信息  
        char[] ch = null;  
        for (Person person : persons) {  
            attrs.clear();// 清空屬性列表  
            attrs.addAttribute(uri, localName, "id", "string",  
                    String.valueOf(person.getId()));// 添加一個名爲id的屬性(type影響不大,這裏設爲string)  
            handler.startElement(uri, localName, "person", attrs); // 開始一個person元素  
                                                                    // 關聯上面設定的id屬性  
            handler.startElement(uri, localName, "name", null); // 開始一個name元素   沒有屬性  
            ch = String.valueOf(person.getName()).toCharArray();  
            handler.characters(ch, 0, ch.length); // 設置name元素的文本節點  
            handler.endElement(uri, localName, "name");  
              
            handler.startElement(uri, localName, "age", null); // 開始一個name元素   沒有屬性  
            ch = String.valueOf(person.getAge()).toCharArray();  
            handler.characters(ch, 0, ch.length); // 設置name元素的文本節點  
            handler.endElement(uri, localName, "age");  
              
            handler.endElement(uri, localName, "person");  
        }  
        handler.endElement(uri, localName, "persons");  
        handler.endDocument();  
    }  
  
    @Override  
    public List<Person> parse(InputStream is) throws Exception {  
        SAXParserFactory factory = SAXParserFactory.newInstance();// 取得SAXParserFactory實例  
        SAXParser saxParser = factory.newSAXParser(); // 從factory獲取SAXParser實例  
        MyHandler handler = new MyHandler();// 實例化自定義Handler  
        saxParser.parse(is, handler); // 根據自定義Handler規則解析輸入流  
        return handler.getPersons();  
    }  
  
    private final class MyHandler extends DefaultHandler {  
        private List<Person> persons;  
        private Person person;  
        private StringBuilder builder;  
  
        public List<Person> getPersons() {  
            return persons;  
        }  
  
        @Override  
        public void startDocument() throws SAXException {  
            super.startDocument();  
            persons = new ArrayList<Person>();  
            builder = new StringBuilder();  
        }  
  
        @Override  
        public void startElement(String uri, String localName, String qName,  
                Attributes attributes) throws SAXException {  
            super.startElement(uri, localName, qName, attributes);  
            if ("person".equals(localName)) {  
                person = new Person();  
                Integer id = Integer.parseInt(attributes.getValue(0));  
                person.setId(id);  
            }  
            builder.setLength(0);// 將字符長度設置爲0 以便從新開始讀取元素內的字符節點  
        }  
  
        @Override  
        public void characters(char[] ch, int start, int length)  
                throws SAXException {  
            super.characters(ch, start, length);  
            builder.append(ch, start, length); // 將讀取的字符數組追加到builder中  
        }  
  
        @Override  
        public void endElement(String uri, String localName, String qName)  
                throws SAXException {  
            super.endElement(uri, localName, qName);  
            if ("name".equals(localName)) {  
                person.setName(builder.toString());  
            } else if ("age".equals(localName)) {  
                person.setAge(Integer.parseInt(builder.toString()));  
            } else if ("person".equals(localName)) {  
                persons.add(person);  
            }  
        }  
    }  
  
}

 

import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.util.List;  
  
import cn.roco.xml.domain.Person;  
import cn.roco.xml.service.IPersonService;  
import cn.roco.xml.service.imp.PersonServiceImpByDom;  
import cn.roco.xml.service.imp.PersonServiceImpByPull;  
import cn.roco.xml.service.imp.PersonServiceImpBySax;  
import android.app.Activity;  
import android.content.Context;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
import android.widget.TextView;  
import android.widget.Toast;  
  
public class MainActivity extends Activity {  
  
    TextView display;  
    List<Person> persons = null;  
    IPersonService personService = null;  
  
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        // 指定IPersonService由PersonServiceImpByPull實現  
//       personService = new PersonServiceImpByPull();  
  
        // 指定IPersonService由PersonServiceImpBySax實現  
        personService = new PersonServiceImpBySax();  
          
        // 指定IPersonService由PersonServiceImpByDom實現  
//      personService = new PersonServiceImpByDom();  
          
  
        Button readButton = (Button) findViewById(R.id.readButton);  
        Button saveButton = (Button) findViewById(R.id.saveButton);  
        display = (TextView) findViewById(R.id.display);  
        readButton.setOnClickListener(new ReadButtonOnClickListener());  
        saveButton.setOnClickListener(new SaveButtonOnClickListener());  
    }  
  
    private final class SaveButtonOnClickListener implements  
            View.OnClickListener {  
        @Override  
        public void onClick(View view) {  
            try {  
                FileOutputStream out = openFileOutput("persons_backup.xml",  
                        Context.MODE_PRIVATE);  
                personService.serialize(persons, out);  
                Toast.makeText(getApplicationContext(), R.string.save_succ, 1)  
                        .show();  
            } catch (Exception e) {  
                Toast.makeText(getApplicationContext(), R.string.save_fail, 1)  
                        .show();  
                e.printStackTrace();  
            }  
        }  
    }  
  
    private final class ReadButtonOnClickListener implements  
            View.OnClickListener {  
        @Override  
        public void onClick(View v) {  
            InputStream xml = this.getClass().getClassLoader()  
                    .getResourceAsStream("person.xml");  
            try {  
                persons = personService.parse(xml);  
            } catch (Exception e) {  
                Toast.makeText(getApplicationContext(), R.string.read_fail, 1)  
                        .show();  
                e.printStackTrace();  
            }  
            display.setText("");  
            for (Person person : persons) {  
                display.append(person.toString() + "\n");  
            }  
        }  
    }  
}

 

 

Dom解析

import java.io.InputStream;  
import java.io.OutputStream;  
import java.util.ArrayList;  
import java.util.List;  
  
import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
import javax.xml.parsers.SAXParser;  
import javax.xml.parsers.SAXParserFactory;  
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.sax.SAXTransformerFactory;  
import javax.xml.transform.sax.TransformerHandler;  
import javax.xml.transform.stream.StreamResult;  
  
import org.w3c.dom.Attr;  
import org.w3c.dom.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.AttributesImpl;  
import org.xml.sax.helpers.DefaultHandler;  
  
import android.R.bool;  
  
import cn.roco.xml.domain.Person;  
import cn.roco.xml.service.IPersonService;  
  
public class PersonServiceImpByDom implements IPersonService {  
  
    @Override  
    public void serialize(List<Person> persons, OutputStream out)  
            throws Exception {  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder = factory.newDocumentBuilder();  
        Document doc = builder.newDocument(); // 由builder建立新文檔  
  
        Element rootElement = doc.createElement("persons");  
        for (Person person : persons) {  
            Element personElement = doc.createElement("person");  
            Attr id=doc.createAttribute("id"); //建立Id屬性節點  
            id.setValue( person.getId().toString()); //給屬性賦值  
            personElement.setAttributeNode(id);//把id屬性節點追加到person  
          
              
            Element nameElement = doc.createElement("name");  
            nameElement.setTextContent(person.getName());  
            personElement.appendChild(nameElement);  
  
            Element ageElement = doc.createElement("age");  
            ageElement.setTextContent(person.getAge().toString());  
            personElement.appendChild(ageElement);  
              
            rootElement.appendChild(personElement);  
        }  
        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聲明  
  
        Source source=new DOMSource(doc);  
        Result result=new StreamResult(out);  
        transformer.transform(source, result);  
    }  
  
    @Override  
    public List<Person> parse(InputStream is) throws Exception {  
        List<Person> persons = new ArrayList<Person>();  
        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++) {  
            Element item = (Element) items.item(i);  
            Person person = new Person();  
            person.setId(Integer.parseInt(item.getAttribute("id")));  
  
            NodeList properties = item.getChildNodes();  
            for (int j = 0; j < properties.getLength(); j++) {  
                if (properties.item(j).getNodeType() == Node.ELEMENT_NODE) {  
                    Node property = properties.item(j);  
                    String nodeName = property.getNodeName();  
                    if ("name".equals(nodeName)) {  
                        person.setName(property.getFirstChild().getNodeValue());  
                    } else if ("age".equals(nodeName)) {  
                        person.setAge(Integer.parseInt(property.getFirstChild()  
                                .getNodeValue()));  
                    }  
                }  
            }  
            persons.add(person);  
        }  
        return persons;  
    }  
}

 

PULL解析

import java.io.InputStream;  
import java.io.OutputStream;  
import java.util.ArrayList;  
import java.util.List;  
  
import org.xmlpull.v1.XmlPullParser;  
import org.xmlpull.v1.XmlSerializer;  
  
import android.util.Xml;  
  
import cn.roco.xml.domain.Person;  
import cn.roco.xml.service.IPersonService;  
  
public class PersonServiceImpByPull implements IPersonService {  
  
 
    public void serialize(List<Person> persons, OutputStream out)  
            throws Exception {  
        XmlSerializer serializer = Xml.newSerializer(); // 由android.util.Xml建立一個XmlSerializer實例  
        serializer.setOutput(out, "UTF-8");  
        serializer.startDocument("UTF-8", true);  
        serializer.startTag(null, "persons");  
        for (Person person : persons) {  
            serializer.startTag(null, "person");  
            serializer.attribute(null, "id", person.getId().toString());  
  
            serializer.startTag(null, "name");  
            serializer.text(person.getName());  
            serializer.endTag(null, "name");  
  
            serializer.startTag(null, "age");  
            serializer.text(person.getAge().toString());  
            serializer.endTag(null, "age");  
  
            serializer.endTag(null, "person");  
        }  
        serializer.endTag(null, "persons");  
        serializer.endDocument();  
        out.flush();  
        out.close();  
    }  
  
  
    public List<Person> parse(InputStream is) throws Exception {  
        List<Person> persons = null;  
        Person person = null;  
  
        // XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
        // XmlPullParser pullParser = factory.newPullParser();  
        XmlPullParser pullParser = Xml.newPullParser();// 由android.util.Xml建立一個XmlPullParser實例  
        pullParser.setInput(is, "UTF-8");// 設置輸入流 並指明編碼方式  
        int eventType = pullParser.getEventType();  
        while (eventType != XmlPullParser.END_DOCUMENT) {  
            switch (eventType) {  
            case XmlPullParser.START_DOCUMENT:  
                persons = new ArrayList<Person>();  
                break;  
            case XmlPullParser.START_TAG:  
                if ("person".equals(pullParser.getName())) {  
                    person = new Person();  
                    person.setId(Integer.parseInt(pullParser  
                            .getAttributeValue(0)));  
                }  
                if ("name".equals(pullParser.getName())) {  
                    person.setName(pullParser.nextText());  
                }  
                if ("age".equals(pullParser.getName())) {  
                    person.setAge(Integer.parseInt(pullParser.nextText()));  
                }  
                break;  
            case XmlPullParser.END_TAG:  
                if ("person".equals(pullParser.getName())) {  
                    persons.add(person);  
                    person = null;  
                }  
                break;  
            }  
            eventType = pullParser.next();  
        }  
        return persons;  
    }  
}
相關文章
相關標籤/搜索