xml基本操作

package com.yangwei.service;

import java.io.IOException;
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 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.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

import com.yangwei.mode.Person;

public class XMLService {
   
    /**
     * SAX解析xml
     * 基于事件驱动
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static List<Person> SAXReader(InputStream inputStream) throws Exception{
       
        SAXParserFactory factory = SAXParserFactory.newInstance();//创建SAM工厂
        SAXParser parser =  factory.newSAXParser();
        SAXHander hander = new SAXHander();
        parser.parse(inputStream, hander);
        inputStream.close();
        return hander.getPersons();
       
    }
   
    /**
     * DOM解析xml
     * 一次性加载到内存树
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static List<Person> DOMReader(InputStream inputStream) throws Exception{
       
        List<Person> persons = new ArrayList<Person>();
        Person person = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(inputStream);
        Element root = document.getDocumentElement();
        NodeList nodeList = root.getElementsByTagName("person");
        //遍历节点
        for(int i = 0 ; i < nodeList.getLength() ; i ++){
            Element element = (Element)nodeList.item(i);
            person = new Person();
            person.setId(Integer.parseInt(element.getAttribute("id")));
            NodeList nodeList2 = element.getChildNodes();
            //遍历子节点
            for(int j = 0 ; j < nodeList2.getLength() ; j ++){
                if(nodeList2.item(j).getNodeType() == Node.ELEMENT_NODE){//判断节点类型
                    Element element2 = (Element)nodeList2.item(j);
                    if(element2.getNodeName().equals("name")){
                        person.setName(element2.getFirstChild().getTextContent());
                    }else if(element2.getNodeName().equals("age")){
                        person.setAge(Short.parseShort(element2.getFirstChild().getTextContent()));
                    }
                }
            }
            persons.add(person);
        }
        return persons;
    }
   
    /**
     * PULL解析xml
     * 基于事件驱动,但需要节点推送
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static List<Person> PULLReader(InputStream inputStream) throws Exception{
       
        List<Person> persons = null;
        Person person = null;
        XmlPullParser parser = Xml.newPullParser();//解析类
        parser.setInput(inputStream, "UTF-8");
        int parserType = parser.getEventType();
        while(parserType != XmlPullParser.END_DOCUMENT ){
            switch (parserType) {
                case XmlPullParser.START_DOCUMENT://文档开始
                    persons = new ArrayList<Person>();
                    break;
                case XmlPullParser.START_TAG://标签开始
                    String name = parser.getName();//获取节点名称
                    if(name.equals("person")){
                        person = new Person();
                        person.setId(Integer.parseInt(parser.getAttributeValue(0)));
                    }
                    if(name.equals("name")){
                        person.setName(parser.nextText());
                    }
                    if(name.equals("age")){
                        person.setAge(Short.parseShort(parser.nextText()));
                    }
                    break;
                case XmlPullParser.END_TAG://标签结束
                    if(parser.getName().equals("person")){
                        persons.add(person);
                    }
                    break;
                }
            parserType = parser.next();
        }
        return persons;
    }
   
    /**
     * 利用pull生成xml
     * @param persons
     * @param outputStream
     * @throws Exception
     */
   
    public static void createXMLByPULL(List<Person> persons,OutputStream outputStream) throws Exception{
       
        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(outputStream, "UTF-8");
        serializer.startDocument("UTF-8",true);
        serializer.startTag("", "persons");
        for (Person person : persons) {
            serializer.startTag("", "person");
            serializer.attribute("", "id", person.getId()+"");
            serializer.startTag("", "name");
            serializer.text(person.getName());
            serializer.endTag("", "name");
            serializer.startTag("", "age");
            serializer.text(person.getAge()+"");
            serializer.endTag("", "age");
            serializer.endTag("", "person");
        }
        serializer.endTag("", "persons");
        serializer.endDocument();
        outputStream.close();       
    }
   
    /**
     * 内部事件驱动类
     * @author Administrator
     *
     */
    private static class SAXHander extends DefaultHandler{
       
        private List<Person> persons;
        private Person person = null;
        private String tag = null;
       
        public List<Person> getPersons() {
            return persons;
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException {
           
            if(tag != null){
                if(tag.equals("name")){
                    person.setName(new String(ch,start,length));
                }else if(tag.equals("age")){
                    person.setAge(Short.parseShort(new String(ch,start,length)));
                }
            }
           
        }

        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            if(localName.equals("person")){
                persons.add(person);
            }
            tag = null;
        }

        public void startDocument() throws SAXException {
            persons = new ArrayList<Person>();
        }

        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
           
            if(localName.equals("person")){
                person = new Person();
                String id = attributes.getValue(0);
                person.setId(Integer.parseInt(id));
            }
            tag = localName;
        }
    }

}

你可能感兴趣的:(xml基本操作)