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

在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解析器。

 

  
  
      
        sax  
        30  
      
      
        dom  
        40  
      
      
        pull  
        50  
      
      
        ouyangpeng  
        60  
      
      
        chengming  
        70  
      
      
        just for test  
        80  
      
  
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 parse(InputStream is) throws Exception;  
    /** 
     * 保存数据 
     * @param persons  数据 
     * @param out  输出方向 
     * @throws Exception 
     */  
    public void serialize(List 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 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 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 persons;  
        private Person person;  
        private StringBuilder builder;  
  
        public List getPersons() {  
            return persons;  
        }  
  
        @Override  
        public void startDocument() throws SAXException {  
            super.startDocument();  
            persons = new ArrayList();  
            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 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 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 parse(InputStream is) throws Exception {  
        List persons = 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++) {  
            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 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 parse(InputStream is) throws Exception {  
        List 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();  
                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;  
    }  
}  

 

转载于:https://my.oschina.net/210920/blog/756570

你可能感兴趣的:(Java在android中xml文件解析效率比较分析)