Java解析xml四种方式

先看xml的格式

<?xml version="1.0" encoding="UTF-8"?>
<xml-body>
    <student>
        <id>1</id>
        <name>zhanagsan</name>
        <age>14</age>
        <score>80</score>
        <height>179</height>
        <address>localhost</address>
    </student>
    <student>
        <id>2</id>
        <name>lisi</name>
        <age>16</age>
        <score>75</score>
        <height>175</height>
        <address>192.168.100.101</address>
    </student>
</xml-body>

Java的bo 类

    package com.test.dom4j;
    
    public class Student {
        private String name;
        private String age;
        private String address;
        private String score;
        private String height;
        private String id;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        public String getScore() {
            return score;
        }
        public void setScore(String score) {
            this.score = score;
        }
        public String getHeight() {
            return height;
        }
        public void setHeight(String height) {
            this.height = height;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        @Override
        public String toString() {
            // TODO Auto-generated method stub
            return this.id+"  "+this.name+" "+this.score+" "+this.address +" "+this.age+" "+this.score+" "+this.height;
        }
        
    }

第一种 Sax解析:

package com.test.sax;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

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

import com.test.dom4j.Student;

public class SaxParseXml {
    public static void main(String args[]) throws Exception{
        SAXParserFactory  factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        BeanParse beanParse = new BeanParse();
        File file = new File("d:\\1.xml");
        sax.parse(file, beanParse);
        List<Student> list = beanParse.getList();
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i).getAddress());
        }
    }
}

class BeanParse extends DefaultHandler {
    private Student student = null;
    private List<Student> list = null;
    private String preTag = null;

    public List<Student> getList() {
        return list;
    }

    public void setList(List<Student> list) {
        this.list = list;
    }

    public void startDocument() throws SAXException {
        list = new ArrayList<Student>();
    }

    public void startElement(String uri, String localName, String name,
            Attributes attributes) throws SAXException {
        preTag = name;
        if ("student".equals(name)) {
            student = new Student();
        }
    }
    
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        if (student != null) {
            
            String data = new String(ch, start, length);
            if ("name".equals(preTag)) {
                student.setName(data);
            }
            if ("address".equals(preTag)) {
                student.setAddress(data);
            }
            if ("age".equals(preTag)) {
                student.setAge(data);
            }
            if ("height".equals(preTag)) {
                student.setHeight(data);
            }
            if ("id".equals(preTag)) {
                student.setId(data);
            }
            if ("score".equals(preTag)) {
                student.setScore(data);
            }
        }
    }
    public void endElement(String uri, String localName, String name)
            throws SAXException {
        if(student!=null&&"student".equals(name)){
            list.add(student);
        }
        preTag = null;
    }

}

第二种 dom4j

package com.test.dom4j;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4jParseXml {

    public static File getFile(String fileName){
        if(null!=fileName||"".equals(fileName)){
            return new File(fileName);
        }
        return null;
    }
    public static  List<Student> parseXml(String fileName) throws Exception{
        List<Student> list = new ArrayList<Student>();
        if(getFile(fileName)!=null){
            File file = getFile(fileName);
            SAXReader readXml = new SAXReader();
            //读入文档
            Document document = readXml.read(file);
            //获取根节点下的子节点head
            Element element = document.getRootElement();
            Iterator<Element> it =  element.elementIterator("student");
            while(it.hasNext()){
                Element students =  it.next();
                Student student = new Student();
                student.setAge(students.elementTextTrim("age"));
                student.setAddress(students.elementTextTrim("address"));
                student.setHeight(students.elementTextTrim("height"));
                student.setId(students.elementTextTrim("id"));
                student.setName(students.elementTextTrim("name"));
                student.setScore(students.elementTextTrim("score"));
                list.add(student);
            }
        }
        return list;
    }
    public static void main(String args[]) throws Exception{
        List<Student> list = parseXml("d://1.xml");
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i).toString());
        }
    }
}

第三种 jdom解析

package com.test.jdom;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.test.dom4j.Student;

public class JdomParseXml {
    public static void main(String args[]) throws Exception{
        List<Student> list = XmlParse();
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i).toString());
        }
    }
    public static List<Student> XmlParse() throws Exception{
        List<Student> students = new ArrayList<Student>();
        SAXBuilder builder = new SAXBuilder();
        InputStream inputStream = new FileInputStream(new File("d:\\1.xml"));
        Document document = builder.build(inputStream);
        Element root = document.getRootElement();
        List<Element> list = root.getChildren();
        for(int i=0;i<list.size();i++){
            Student student = new Student();
            student.setId(list.get(i).getChildText("id"));
            student.setAge(list.get(i).getChildText("age"));
            student.setName(list.get(i).getChildText("name"));
            student.setAddress(list.get(i).getChildText("address"));
            student.setScore(list.get(i).getChildText("score"));
            student.setHeight(list.get(i).getChildText("height"));
            students.add(student);
        }
        return students;
        
    }
}

第四种:dom解析

package com.test.dom;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomParseXml {
    public static void main(String args[]) {
        DomParseXml();
    }

    public static void DomParseXml() {
        // 实例化一个文档构建器工厂
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // 通过文档构建器工厂获取一个文档构建器
            DocumentBuilder db = dbf.newDocumentBuilder();
            // 通过文档通过文档构建器构建一个文档实例
            Document doc = db.parse("d:\\1.xml");
            // 获取所有名字为 “student” 的节点
            NodeList nodeList = doc.getElementsByTagName("student");
            int size1 = nodeList.getLength();
            for (int i = 0; i < size1; i++) {
                Node n = nodeList.item(i);
                // 获取 n 节点下所有的子节点。
                NodeList nodeList2 = n.getChildNodes();
                int size2 = nodeList2.getLength();
                for (int j = 0; j < size2; j++) {
                    Node n2 = nodeList2.item(j);
                    if (n2.hasChildNodes()) {
                        System.out.println(n2.getNodeName() + " = "
                                + n2.getFirstChild().getNodeValue());
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

四种解析方式的比较:单纯从代码量来看jdom是最简单的解析方式,jdom出现的原因就是为了减少xml解析的代码量,但其内部解析还是用的sax,jdom解析缺点不灵活。

Sax解析:不需要读入全部的数据就开始解析,效率和性能较高。单向导航,无法定位文档层次,很难同时访问同一文档的不同部分数据。

dom4j解析:性能优越,功能强大。hibernate解析就是用的dom4j,api较为复杂。

dom解析:允许对数据和结构做出修改,但是dom解析占用资源较多。

posted @ 2014-05-26 22:50  942391815  阅读(340)  评论(0编辑  收藏  举报