DOM4J解析XML

一、DOM4J解析XML文档的实例

book.xml

<?xml version="1.0" encoding="UTF-8"?>
<书架> 
  <> 
    <书名>JavaSE基础</书名>  
    <作者>张三</作者>  
    <售价>38.00</售价>  
    <内部价>19.00</内部价> 
  </>  
  <> 
    <书名>Android</书名>  
    <作者>李四</作者>  
    <售价>28.00</售价> 
  </> 
</书架>

DOM4JDemo.java

package cn.lsl.dom4j;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class DOM4JDemo {
    //1.得到某个具体节点的内容:第二本书的作者
    @Test
    public void test1() throws Exception{
        //得到Document对象
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        //得到根元素
        Element root = document.getRootElement();
        //依次得到第二本书的作者
        List<Element> es = root.elements("书");
        Element e = es.get(1);
        Element author = e.element("作者");
        System.out.println(author.getText());
    }
    
    //使用XPath方式得到第二本书的作者
    @Test
    public void test2() throws Exception{
        //得到Document对象
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        String xpath = "//书[2]/作者";
        Node author = document.selectSingleNode(xpath);
        System.out.println(author.getText());
    }
    
    
    //遍历所有元素的节点
    @Test
    public void test3() throws Exception{
        //得到Document对象
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        //得到根元素
        Element root = document.getRootElement();
        treeWalk(root);
    }

    private void treeWalk(Element root) {
        System.out.println(root.getName());
        List<Element> es = root.elements();
        for (Element e : es) {
            treeWalk(e);
        }
    }
    
    //修改某个元素节点的主题内容:修改第2本书的售价
    @Test
    public void test4() throws Exception{
        //得到Document对象
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        //得到根元素
        Element root = document.getRootElement();
        Element secondBook = (Element)root.elements().get(1);
        Element secondBookPrice = secondBook.element("售价");
        //设置主题内容
        secondBookPrice.setText("28.00");
        //写回XML文档
        OutputStream out = new FileOutputStream("src/book.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
    }
    
    
    //向指定元素节点中增加子元素节点:给第一本书添加批发价
    @Test
    public void test5() throws Exception{
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        Element root = document.getRootElement();
        Element firstBook = root.element("书");
        firstBook.addElement("批发价").setText("18.00");
        //写回XML文档
        OutputStream out = new FileOutputStream("src/book.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
    }
    
    
    //向指定元素节点上增加同级元素节点:在第一本书的售价前面添加内部价
    @Test
    public void test6() throws Exception{
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        Element root = document.getRootElement();
        //得到第一本书
        Element firstBook = root.element("书");
        //得到第一本书的所有子元素:List
        List<Element> children = firstBook.elements();
        //借组DocumentHelper创建内部价元素
        Element price = DocumentHelper.createElement("内部价");
        price.setText("19.00");
        children.add(3, price);
        //写回XML文档中
        OutputStream out = new FileOutputStream("src/book.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
    }
    
    //删除指定节点元素:删除批发价
    @Test
    public void test7() throws Exception{
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        Element root = document.getRootElement();
        Element firstBook = root.element("书");
        Element price = firstBook.element("批发价");
        firstBook.remove(price);
        //写回XML文档中
        OutputStream out = new FileOutputStream("src/book.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
    }
    
    
    
    //操作XML文件属性:第一本书添加一个出版社属性
    @Test
    public void test8() throws Exception{
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        Element root = document.getRootElement();
        Element firstBook = root.element("书");
        firstBook.addAttribute("出版社","清华大学出版社");
        //写回XML文档中
        OutputStream out = new FileOutputStream("src/book.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
    }
    
    //获取第一本书的出版社属性
    @Test
    public void test9() throws Exception{
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/book.xml");
        Element root = document.getRootElement();
        Element firstBook = root.element("书");
        String value = firstBook.attributeValue("出版社");
        System.out.println(value);
    }
}

二、案例(学生成绩的增删改查,采用分层开发和DOM4J进行操作)

首先需要导入dom4j.jar和jaxen.jar

exam.xml

<?xml version="1.0" encoding="UTF-8"?>
<exam> 
  <student examid="444" idcard="333"> 
    <name>李四</name>  
    <location>大连</location>  
    <grade>97</grade> 
  </student> 
</exam>

实体类:Student.java

package cn.lsl.domain;
public class Student {
    private String idcard;
    private String examid;
    private String name;
    private String location;
    private Double grade;
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getExamid() {
        return examid;
    }
    public void setExamid(String examid) {
        this.examid = examid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public Double getGrade() {
        return grade;
    }
    public void setGrade(Double grade) {
        this.grade = grade;
    }
    @Override
    public String toString() {
        return "Student [examid=" + examid + ", grade=" + grade + ", idcard="
                + idcard + ", location=" + location + ", name=" + name + "]";
    }
}

工具类:Dom4JUtil.java

package cn.lsl.util;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4JUtil {
    public static Document getDocument() throws Exception{
        SAXReader reader = new SAXReader();
        return reader.read("src/exam.xml");
    }
    
    public static void writer2xml(Document document) throws Exception{
        OutputStream out = new FileOutputStream("src/exam.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
    }
}

接口:StudentDaoImpl.java

package cn.lsl.dao.impl;
import cn.lsl.domain.Student;
public interface StudentDaoImpl {
    //添加学生信息到XML中
    boolean createStudent(Student s);
    //根据准考证好查询学生信息
    Student findStudent(String examid);
    //根据学生姓名删除学生
    boolean deleteStudent(String name);
}

DAO层:StudentDao.java

package cn.lsl.dao;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import cn.lsl.dao.impl.StudentDaoImpl;
import cn.lsl.domain.Student;
import cn.lsl.util.Dom4JUtil;

public class StudentDao implements StudentDaoImpl {

    @Override
    public boolean createStudent(Student s) {
        boolean result = false;
        try{
            Document document = Dom4JUtil.getDocument();
            Element root = document.getRootElement();
            Element studentE = root.addElement("student")
                        .addAttribute("examid", s.getExamid())
                        .addAttribute("idcard", s.getIdcard());
            studentE.addElement("name").setText(s.getName());
            studentE.addElement("location").setText(s.getLocation());
            studentE.addElement("grade").setText(s.getGrade()+"");
            Dom4JUtil.writer2xml(document);
            result = true;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public boolean deleteStudent(String name) {
        boolean result = false;
        try{
            Document document = Dom4JUtil.getDocument();
            //选择所有的name元素
            List<Node> nodes = document.selectNodes("//name");
            //遍历
            for (Node n : nodes) {
                if(n.getText().equals(name))
                    n.getParent().getParent().remove(n.getParent());
            }
            Dom4JUtil.writer2xml(document);
            result = true;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public Student findStudent(String examid) {
        Student s = null;
        try{
            Document document = Dom4JUtil.getDocument();
            Node node = document.selectSingleNode("//student[@examid='"+examid+"']");
            if(node!=null){
                Element e = (Element)node;
                s = new Student();
                s.setExamid(examid);
                s.setIdcard(e.valueOf("@idcard"));
                s.setName(e.element("name").getText());
                s.setLocation(e.elementText("location"));
                s.setGrade(Double.parseDouble(e.elementText("grade")));
            }
        }catch(Exception e){
            throw new RuntimeException(e);
        } 
        return s;
    }    
}

View层:Main.java

package cn.lsl.view;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import cn.lsl.dao.StudentDao;
import cn.lsl.domain.Student;

public class Main {
    public static void main(String[] args) {
        try{
            StudentDao dao = new StudentDao();
            System.out.println("a、添加学生\tb、删除学生\tc、查询成绩");
            System.out.println("请输入操作类型");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String operation = br.readLine();
            if("a".equals(operation)){
                //添加操作
                System.out.println("请输入学生姓名");
                String name = br.readLine();
                System.out.println("请输入学生准考证号");
                String examid = br.readLine();
                System.out.println("请输入学生身份证号");
                String idcard = br.readLine();
                System.out.println("请输入学生所在地");
                String location = br.readLine();
                System.out.println("请输入学生成绩");
                String grade = br.readLine();
                Student s = new Student();
                s.setExamid(examid);
                s.setIdcard(idcard);
                s.setName(name);
                s.setLocation(location);
                s.setGrade(Double.parseDouble(grade));
                //System.out.println(s);
                boolean b = dao.createStudent(s);
                if(b){
                    System.out.println("---添加成功---");
                }else{
                    System.out.println("对不起!数据有误");
                }
            }else if("b".equals(operation)){
                System.out.println("请输入要删除的学生姓名:");
                String name = br.readLine();
                boolean b = dao.deleteStudent(name);
                if(b){
                    System.out.println("--删除成功--");
                }else{
                    System.out.println("对不起!删除失败或者学生不存在");
                }
            }else if("c".equals(operation)){
                //查询操作
                System.out.println("请输入要查询的学生准考证号:");
                String examid = br.readLine();
                Student s = dao.findStudent(examid);
                if(s == null){
                    System.out.println("对不起!您查询的学生不存在");
                }else{
                    System.out.println(s);
                }
            }else{
                System.out.println("请输入正确的操作类型");
            }
        }catch(Exception e){
            System.out.println("对不起!服务器忙!");
        }
    }
}

 

posted @ 2014-04-18 14:22  Evan Liu  阅读(1028)  评论(0编辑  收藏  举报