为了账号安全,请及时绑定邮箱和手机立即绑定

使用Dom4j实现对XML文件读取和生成

标签:
Java

在实际项目的开发当中经常会遇到对XML文件的解析,常用的第三方解析XML的组件也很多,例如像DOM,SAX,JDOM和Dom4J。在这几款解析XML组件当中最优秀也是最容易学的也就属DOM4j了,在这篇文章中我将介绍如何使用DOM4j实现对XML文件的读取和创建。

  • 在Eclipse中创建Java工程项目,并右键项目建立lib文件夹导入DOM4J的jar包,建立如下包目录结构。如下图所示:
    图片描述

其中model包存放JavaBean,用来读取XML文件封装成JavaBean对象时用到的,test包是用来测试的,而util存放工具类的。

  • 编写books.xml文件内容和该XML文件所对应的JavaBean
<!---books.xml的文件内容->
<?xml version="1.0" encoding="UTF-8"?>
<books> 
  <book id="imooc-001" categlory="历史"> 
    <name>三国演义</name>  
    <author>罗贯中</author>  
    <price>1030</price> 
  </book>  
  <book id="imooc-001" categlory="history"> 
    <name>Oracle开发实战经典</name>  
    <author>李兴华</author>  
    <price>60</price> 
  </book> 
</books>

books.xml对应的JavaBean

public class Book {

    private String id;
    private String categlory;
    private String author;
    private int price;
    private String name;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getCateglory() {
        return categlory;
    }
    public void setCateglory(String categlory) {
        this.categlory = categlory;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Book [id=" + id + ", categlory=" + categlory + ", author=" + author + ", price=" + price + ", publish="
                + name + "]";
    }

}

编写读取Dom对象的工具类Dom4JReaderUtils

public class Dom4JReaderUtils {

    private static final String RESOURCE;
    static {
        RESOURCE = Dom4JReaderUtils.class.getClassLoader().getResource("books.xml").getPath();
    }

    public static Document getDocument() {
        Document document = null;
        SAXReader reader = new SAXReader();
        try {
            document = reader.read(new File(RESOURCE));

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return document;
    }
}

编写写入DOM对象的工具类Dom4JWriterUtils

public class Dom4JWriterUtils {

    /**
     * 
     * OutputFormat format = OutputFormat.createPrettyPrint();
     * format.setEncoding("gb2312"); //源文档用"gb2312"编码,既不改变源文档的编码格式,又不能有乱码
     * XMLWriter writer = new XMLWriter(new FileOutputStream(file),format);
     * writer.write(document); writer.close()
     * 
     * 
     * 
     * @param document
     */
    public static void writeDom(Document document) {
        OutputFormat format = OutputFormat.createPrettyPrint();// 创建文件输出的时候,自动缩进的格式
        XMLWriter writer = null;

        try {
            format.setEncoding("UTF-8");// 设置编码
            //创建XMLWriter对象的时候,为防止乱码最好传入FileOutStream作为参数
            writer = new XMLWriter(new FileOutputStream(new File("src//books.xml")), format);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

编写Dom4JCRUD实现对books.xml进行读取,新增,修改和删除。

public class Dom4JCRUD {

    /**
     * 读取xml文件中所有的book子节点并将其封装成Book对象放在List中返回。
     * 
     * @param document
     *            XML文档对象
     * @return 存放Book对象的List
     */
    public static List<Book> getBookListFromXML(Document document) {
        List<Book> bookList = new ArrayList<Book>();
        Element root = document.getRootElement();
        Iterator<Element> bookIterator = root.elementIterator();
        while (bookIterator.hasNext()) {
            Element element = bookIterator.next();
            Book book = new Book();
            book.setName(element.elementText("name"));
            book.setPrice(Integer.parseInt(element.elementText("price")));
            book.setAuthor(element.elementText("author"));
            Iterator<Attribute> bookAttr = element.attributeIterator();
            while (bookAttr.hasNext()) {
                Attribute attribute = bookAttr.next();
                String attributeName = attribute.getName();
                if (attributeName.equals("id")) {
                    book.setId(attribute.getValue());
                } else {
                    book.setCateglory(attribute.getValue());
                }

            }
            bookList.add(book);
        }

        System.out.println(root.getName());

        return bookList;
    }

    /**
     * 向books.xml文件中添加一个新的子节点 books.
     * @param document XMl文档对象
     */
    public static void addElement(Document document) {
        Element root = document.getRootElement();
        Element book = root.addElement("book");
        Element name = book.addElement("name");
        name.setText("java基础教程");
        Element author = book.addElement("author");
        author.setText("张孝详");
        Element price = book.addElement("price");
        price.setText("1234");
        book.addAttribute("id", "imooc-003");
        book.addAttribute("categlory", "宫廷");
        Dom4JWriterUtils.writeDom(document); 
    }

    /**
     * 从根节点中删除指定ID的子节点book
     * @param id 待删除的子节点的ID
     */
    public static void removeElementById(Document document,String id){
        Element books=document.getRootElement();
        Iterator<Element>elementIter=books.elementIterator();
        while(elementIter.hasNext()){
            Element book=elementIter.next();
            String bookID=book.attribute("id").getText();
            if(id.equals(bookID)){
                books.remove(book);
                break;
            }
        }
        Dom4JWriterUtils.writeDom(document);
    }

    /**
     * 根据指定的ID更新子节点的内容
     * @param document
     * @param id
     */
    public static void updateElementById(Document document,String id,String name,String author,String price){
        Element books=document.getRootElement();
        List<Element>elementList=books.elements();
        for (int i = 0; i < elementList.size(); i++) {
            Element book=elementList.get(i);
            String bookId=book.attribute("id").getText();
            if(bookId.equals(id)){
                book.element("name").setText(name);
                book.element("author").setText(author);
                book.element("price").setText(price);
            }

        }

      Dom4JWriterUtils.writeDom(document);

    }

}

演示读取

public static void main(String[] args) {
        //读取books文件中的内容
        Document document=Dom4JReaderUtils.getDocument();
        List<Book>bookList=getBookListFromXML(document);
        System.out.println(bookList);

    }

结果如下:
图片描述

演示修改

public static void main(String[] args) {
        //读取books文件中的内容
        Document document=Dom4JReaderUtils.getDocument();
        System.out.println("修改imooc-001的数据前");
        List<Book>bookList=getBookListFromXML(document);
        System.out.println(bookList);
        updateElementById(document, "imooc-001", "红楼梦", "曹雪芹", "190");
        System.out.println("修改imooc-001的数据后");
        bookList=getBookListFromXML(document);
        System.out.println(bookList);

    }

结果为:
图片描述

演示新增

public static void main(String[] args) {
        //读取books文件中的内容
        Document document=Dom4JReaderUtils.getDocument();
        System.out.println("新增前的数据");
        List<Book>bookList=getBookListFromXML(document);
        System.out.println("list中的size为"+bookList.size()+"数据为"+bookList);
        addElement(document);
        System.out.println("新增后的数据");
        bookList=getBookListFromXML(document);
        System.out.println("list中的size为"+bookList.size()+"数据为"+bookList);

    }

结果为:
图片描述

演示删除

    public static void main(String[] args) {
        //读取books文件中的内容
        Document document=Dom4JReaderUtils.getDocument();
        System.out.println("删除前的数据");
        List<Book>bookList=getBookListFromXML(document);
        System.out.println("list中的size为"+bookList.size()+"数据为"+bookList);
        removeElementById(document, "imooc-002");
        System.out.println("删除后的数据");
        bookList=getBookListFromXML(document);
        System.out.println("list中的size为"+bookList.size()+"数据为"+bookList);

    }

图片描述

  • 使用DOM4j动态生成XML文件
public class Dom4JTest {

    /**
     *使用Dom4J创建一个新的XML文档
     */
    public static void createXMLFile() {
        Document document = DocumentHelper.createDocument();
        Element root = DocumentHelper.createElement("students");  
        document.setRootElement(root);  
        root.addAttribute("学校", "南京大学").addAttribute("位置", "浙江杭州");      
        //给根节点添加孩子节点  
        Element element1 = root.addElement("学生");  
        element1.addElement("姓名").addAttribute("性别", "男").addText("关羽");  
        element1.addElement("年龄").addText("21");  

        Element element2 = root.addElement("学生");  
        element2.addElement("姓名").addAttribute("性别", "女").addText("小乔");  
        element2.addElement("年龄").addText("22");
        element2.addElement("爱好").addText("弹琴");
        OutputFormat format = OutputFormat.createPrettyPrint();// 创建文件输出的时候,自动缩进的格式
        XMLWriter writer = null;

        try {
            format.setEncoding("UTF-8");// 设置编码
            //创建XMLWriter对象的时候,为防止乱码最好传入FileOutStream作为参数
            writer = new XMLWriter(new FileOutputStream(new File("src//students.xml")), format);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

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

}

运行改代码后刷新目录得到以下XML文件
图片描述

关于DOM4j实现对XML的读取和生成就介绍到这里。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
25
获赞与收藏
75

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消