Dom4j操作XML文件(创建文件、增删改查、删除文件)

所需jar包:jdom-2.0.1.jar

1.实体类

package com.entity;

import java.io.Serializable;

public class User implements Serializable{

    /**
     *id
     */
    private  Long id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 姓别
     */
    private String sex;
    /**
     * 年龄
     */
    private int age;
    /**
     * 联系方式
     */
    private String telephone;


    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getSex() {
        return sex;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getTelephone() {
        return telephone;
    }

}

2.测试类

package com.controller;

import com.entity.User;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

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

public class Test {
    public static void main(String[] args){

        //新建xml文件
//        creatXml(Long.valueOf(2), "user", 20,"男","15189722456");

        String path = "D:/user.xml";

        //增加xml中数据
//        save(Long.valueOf(3), "bc", 20,"男","15189722879",path);

        //删除xml中数据
//        delete(Long.valueOf(2),path);

        //修改xml中数据
//        update(Long.valueOf(3), "yc", 20,"女","15189722456",path);

        //查询xml中数据
//        System.out.println(getList(path).size());

        //删除xml文件
      deleteXml("user");
    }


    /**
     * 新建xml文件
     * @param name
     * @return
     */
    private static String creatXml(Long id, String name, int age, String sex,
                            String telephone) {

        Element root = new Element("listUser");
        Document doc = new Document(root);
        try {
            Element nodes = new Element("user");
            nodes.setAttribute("id", String.valueOf(id));
            nodes.setAttribute("name", name);
            nodes.setAttribute("age", String.valueOf(age));
            nodes.setAttribute("sex", sex);
            nodes.setAttribute("telephone", telephone);
            root.addContent(nodes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        XMLOutputter XMLOut = new XMLOutputter();
        try {
            String path = "D:/" + name + ".xml";
            FileOutputStream fOutputStream = new FileOutputStream(path);
            XMLOut.output(doc, fOutputStream);
            fOutputStream.close();
            return path;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 保存数据到xml文件中
     *
     */
    public static String save(Long id, String name, int age, String sex,
                              String telephone,String path) {
        File file = new File(path);
        SAXBuilder sb = new SAXBuilder();
        Document document = null;
        try {
            document = sb.build(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (document == null) {
            return null;
        }
        try {

            Element root = document.getRootElement();
            Element nodes = new Element("user");
            nodes.setAttribute("id", String.valueOf(id));
            nodes.setAttribute("name", name);
            nodes.setAttribute("age", String.valueOf(age));
            nodes.setAttribute("sex", sex);
            nodes.setAttribute("telephone", telephone);
            root.addContent(nodes);

            XMLOutputter out = new XMLOutputter();
            out.setFormat(Format.getCompactFormat().setEncoding("UTF-8"));// 防止中文乱码
            out.output(document, new FileWriter(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 删除xml信息
     */
    public static void delete(Long id,String path) {
        Document document = getDocument(path);
        Element root = document.getRootElement();
        List<Element> nodesList = root.getChildren("user");
        for (Element el : nodesList) {
            if (id==Long.valueOf(el.getAttributeValue("id"))) {
                root.removeContent(el);
                break;
            }
        }
        try {
            XMLOutputter out = new XMLOutputter();
            out.setFormat(Format.getCompactFormat().setEncoding("GBK"));// 设置UTF-8编码可能出现了乱码,故设置为GBK
            out.output(document, new FileWriter(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改数据到xml文件中
     *
     */
    public static String update(Long id, String name, int age, String sex,
                              String telephone,String path) {
        Document document = getDocument(path);
        Element root = document.getRootElement();
        List<Element> nodesList = root.getChildren("user");

        if (document == null) {
            return null;
        }
        try {
            for (Element el : nodesList) {

                if (id==Long.valueOf(el.getAttributeValue("id"))) {
                    el.setAttribute("name", name);
                    el.setAttribute("age", String.valueOf(age));
                    el.setAttribute("sex", sex);
                    el.setAttribute("telephone", telephone);
                    break;
                }
            }
            XMLOutputter out = new XMLOutputter();
            out.setFormat(Format.getCompactFormat().setEncoding("UTF-8"));// 防止中文乱码
            out.output(document, new FileWriter(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    //查询xml中的数据
    private static List<User> getList(String path) {
        Document document = getDocument(path);
        Element root = document.getRootElement();
        List<Element> BoardList = root.getChildren();
        List<User> dtos = new ArrayList<>();
        for (Element element : BoardList) {
            User board = new User();
            board.setId(Long.valueOf(element.getAttributeValue("id")));
            board.setName(element.getAttributeValue("name"));
            board.setAge(Integer.valueOf(element.getAttributeValue("age")));
            board.setSex(element.getAttributeValue("sex"));
            board.setTelephone(element.getAttributeValue("telephone"));
            dtos.add(board);
        }
        return dtos;
    }


    /**
     * 得到Document
     *
     * @param path 路径
     * @return document
     */
    private static Document getDocument(String path) {
        File file = new File(path);
        SAXBuilder sb = new SAXBuilder();
        Document document = null;
        try {
            document = sb.build(file);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (document == null) {
            return null;
        }
        return document;
    }

    /**
     * 删除xml文件
     * @param name
     * @return
     */
    private static void deleteXml(String name) {

        String path = "D:/" + name + ".xml";
        // 删除文件
        if (path != null && path != "") {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值