Java——使用DOM4j解析XML文档

DOM4J是一个第三方的XML解析开发包,可以很方便的对XML文件进行增删改查等操作,可以在其开发文档中快速掌握使用方法。

  1. 简单使用
package com.keixn.day3;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 使用DOM4j解析XML文件 需要用时查阅DOM4j使用文档/docs/index.html
 * 
 * @author KeXin
 *
 */
public class Demo1 {
    // 创建解析器返回DOCUMENT对象
    public Document parse(File url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }

    // Writing a document to a file
    public void write(Document document) throws IOException {
        // lets write to a file
        XMLWriter writer = new XMLWriter(new FileWriter("src/com/keixn/day3/stu_info.xml"));
        writer.write(document);
        writer.close();
    }
    // Creating a new XML node
        public Element createElement(String examid,String idcard,String name,String location,String grade) {
            Element stu = DocumentHelper.createElement("stu").addAttribute("examid", examid).addAttribute("idcard", idcard);
            Element name_node = stu.addElement("name").addText(name);
            Element location_node = stu.addElement("location").addText(location);
            Element grade_node = stu.addElement("grade").addText(grade);
            return stu;
        }
    //Update a XML node
        public void UpdateElement(Document document) throws IOException{
            Element root = document.getRootElement();
            System.out.println("请输入学生身份证号:");
            Scanner scan = new Scanner(System.in);
            String idcard = scan.nextLine();
            for ( Iterator i = root.elementIterator( "stu" ); i.hasNext(); ) {
                Element stu = (Element) i.next();
                if(stu.attributeValue("idcard").equals(idcard)){
                    System.out.println("已经查到该学生,请输入他的成绩:");
                    String grade = scan.nextLine();  
                    stu.element("grade").setText(grade);
                    this.write(document);
                    System.out.println("更新成功");
                    return;
                }
            }
            System.out.println("查无此人");
        }
    public static void main(String[] args) throws DocumentException, IOException {
        Demo1 demo = new Demo1();
        Document document = demo.parse(new File("src/com/keixn/day3/stu_info.xml"));
        Element root = document.getRootElement();
        Element stu = demo.createElement("000", "122", "lisa", "北京", "86");
        root.add(stu);
        demo.write(document);
        System.out.println();
        demo.UpdateElement(document);

    }

}

2.作业:用XML文件模拟数据库,使用DOM4j对学生数据进行增删改查。

package com.keixn.day3;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class StuTask {
    private final String xml_path = "src/com/keixn/day3/stu_info.xml";
    private final String STU = "stu", EXAM = "exam", EXAMID = "examid", IDCARD = "idcard", NAME = "name",
            LOCATION = "location", GRADE = "grade";

    /*
     * 添加新用户
     */
    public void AddStu() throws IOException, DocumentException {
        Student stu = new Student();
        Scanner s1 = new Scanner(System.in);
        System.out.println("请输入学生姓名");
        stu.setName(s1.nextLine());
        System.out.println("请输入准考证号");
        stu.setExamid(s1.nextLine());
        System.out.println("请输入身份证号");
        stu.setIdcard(s1.nextLine());
        System.out.println("请输入学生地址");
        stu.setLocation(s1.nextLine());
        System.out.println("请输入学生成绩");
        stu.setGrade(s1.nextLine());
        Document document = this.GetDocument(new File(xml_path));
        Element root = document.getRootElement();
        // 创建stu标签
        Element stu_node = root.addElement(STU).addAttribute(IDCARD, stu.getIdcard()).addAttribute(EXAMID,
                stu.getExamid());
        // 创建stu标签内的name location grade标签
        Element stu_name_node = stu_node.addElement(NAME);
        stu_name_node.setText(stu.getName());
        Element stu_location_node = stu_node.addElement(LOCATION);
        stu_location_node.setText(stu.getLocation());
        Element stu_grade_node = stu_node.addElement(GRADE);
        stu_grade_node.setText(stu.getGrade());
        this.SvaeToXML(document);
        System.out.println("添加成功");
    }

    /*
     * 删除用户
     */
    public void DeleteStu() throws IOException, DocumentException {
        System.out.println("请输入准考证号");
        Scanner s1 = new Scanner(System.in);
        String examid = s1.nextLine();
        Document document = this.GetDocument(new File(xml_path));
        Element root = document.getRootElement();
        Iterator iterator = root.elementIterator(STU);
        Element e;
        while(iterator.hasNext()){
            e = (Element) iterator.next();
            if(e.attributeValue(EXAMID).equals(examid)){
                root.remove(e);
                this.SvaeToXML(document);
                System.out.println("删除成功");
                return;
            }
        }
        System.out.println("查无此人");
    }

    /*
     * 查询成绩
     */
    public void QuestStu() throws IOException, DocumentException {
        System.out.println("请输入准考证号");
        Scanner s1 = new Scanner(System.in);
        String examid = s1.nextLine();
        Document document = this.GetDocument(new File(xml_path));
        Element root = document.getRootElement();
        Iterator iterator = root.elementIterator(STU);
        Element e;
        while(iterator.hasNext()){
            e = (Element) iterator.next();
            if(e.attributeValue(EXAMID).equals(examid)){
                System.out.println(e.elementText(GRADE));
                return;
            }
        }
        System.out.println("查无此人");
    }

    public Document GetDocument(File url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }

    public static void main(String[] args) throws IOException, DocumentException {
        int key = 0;
        StuTask st = new StuTask();
        Scanner scan = new Scanner(System.in);
        System.out.println("请选择操作:");
        while (key != 4) {
            System.out.println("1、添加新用户;2、删除用户;3、查询成绩;4、退出系统");
            key = scan.nextInt();
            switch (key) {
            case 1:
                st.AddStu();
                break;
            case 2:
                st.DeleteStu();
                break;
            case 3:
                st.QuestStu();
                break;
            default:
                key = 4;
            }
        }
    }

    /*
     * 将document输出至xml文件
     */
    public void SvaeToXML(Document document) throws IOException {
        XMLWriter writer = new XMLWriter(new FileWriter("src/com/keixn/day3/stu_info.xml"));
        writer.write(document);
        writer.close();
    }
}

Student.java:

package com.keixn.day3;

public class Student {
    private String idcard;
    private String examid;
    private String name;
    private String location;
    private String 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 String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public String GetStu(Student stu) {
        String result = "";
        if (stu != null) {
            result+=stu.getName()+"\t"+stu.getExamid()+"\t"+stu.getIdcard()+"\t"+stu.getLocation()+"\t"+stu.getGrade();
        }

        return result;

    }

}

stu_info.xml:

<?xml version="1.0" encoding="UTF-8"?>
<exam>
    <stu examid="000" idcard="122">
        <name>lisa</name>
        <location>北京</location>
        <grade>78</grade>
    </stu>
</exam>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黄鸭and小黑鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值