使用Hutool工具包解析、生成XML文件

说明:当我们在工作中需要将数据转为XML文件、或者读取解析XML文件时,使用Hutool工具包中的XMLUtil相关方法是最容易上手的方法,本文介绍如何使用Hutool工具包来解析、生成XML文件。

开始之前,需要导入Hutool工具包的依赖

xml 复制代码
<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>5.8.6</version>
</dependency>

XML 转 JavaBean

如下面这个XML文件

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<data>
    <books>
        <book>
            <title>《许三观卖血记》</title>
            <author>余华</author>
            <publish>作家出版社</publish>
        </book>
        <book>
            <title>《罪与罚》</title>
            <author>陀思妥耶夫斯基</author>
            <publish>浙江文艺出版社</publish>
        </book>
        <book>
            <title>《白夜》</title>
            <author>陀思妥耶夫斯基</author>
            <publish>上海译文出版社</publish>
        </book>
    </books>
</data>

经分析,从外至里,我们需要创建以下对象:

(data标签对象,里面包含了books标签对象)

java 复制代码
import cn.hutool.core.annotation.Alias;
import lombok.Data;

import java.io.Serializable;

@Data
public class DataBean implements Serializable {

    /**
     * 数据包
     */
    @Alias("books")
    private BooksBean books;
}

(books标签对象,里面有book对象,并且是一个集合)

java 复制代码
import cn.hutool.core.annotation.Alias;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

@Data
public class BooksBean implements Serializable {

    /**
     * 书籍列表
     */
    @Alias("book")
    private List<BookBean> books;
}

(book对象,里面是多个属性)

java 复制代码
import cn.hutool.core.annotation.Alias;
import lombok.Data;

import java.io.Serializable;

@Data
public class BookBean implements Serializable {

    /**
     * 书名
     */
    @Alias("title")
    private String title;

    /**
     * 作者
     */
    @Alias("author")
    private String author;

    /**
     * 出版社
     */
    @Alias("publish")
    private String publish;
}

需要注意,对应属性上面的注解以及注解里面的名称需要与xml中的标签名对应;

解析XML代码;

clike 复制代码
        // 读取xml文件
        String xml = FileUtil.readString(new File("data.xml"), "UTF-8");

        // 将xml转换为java对象
        Element rootElement = XmlUtil.getRootElement(XmlUtil.parseXml(xml));

        // 使用根节点下的直接 转成对象
        DataBean dataBean = XmlUtil.xmlToBean(rootElement, DataBean.class);

        // 输出对象数据
        System.out.println(dataBean.getBooks().getBooks());

解析完成

JavaBean 转 XML

对象转XML是相反的过程,先组装数据,成一个对象。然后依次创建节点标签,将数据放入到标签中。

java 复制代码
        // 制造数据
        BookBean bookBean = new BookBean();
        bookBean.setTitle("《活着》");
        bookBean.setAuthor("余华");
        bookBean.setPublish("作家出版社");

        // 创建Books对象
        List<BookBean> beans = new ArrayList<>();
        beans.add(bookBean);

        // 创建xml对象
        Document document = XmlUtil.createXml();

        // 创建data节点
        Element data = document.createElement("data");
        document.appendChild(data);

        // 创建books节点
        Element books = document.createElement("books");
        data.appendChild(books);

        // 创建book节点
        Element book = document.createElement("book");
        books.appendChild(book);

        // 填充数据
        for (BookBean bean : beans) {
            Element title = document.createElement("title");
            title.setTextContent(bean.getTitle());
            book.appendChild(title);

            Element author = document.createElement("author");
            author.setTextContent(bean.getAuthor());
            book.appendChild(author);

            Element publish = document.createElement("publish");
            publish.setTextContent(bean.getPublish());
            book.appendChild(publish);
        }

        // 将document对象转换为xml字符串
        String xmlStr = XmlUtil.toStr(document);

        // 输出
        System.out.println(xmlStr);

转换成功;

另外,这里的xml是未格式化的,可以通过下面这个方法,输出格式化后的xml

java 复制代码
    private String formatXml(Document document) {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            // 将 Document 转换为 Source
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new StringWriter());

            // 使用 Transformer 对象进行格式化
            transformer.transform(source, result);
            return result.getWriter().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

将上面的代码换成如下:

java 复制代码
        // 将document对象转换为xml字符串,并格式化
        String xmlStr = formatXml(document);

运行看效果

总结

使用Hutool工具包解析、生成XML文件,使用的是XmlUtil中的XmlUtil.xmlToBean()、XmlUtil.toStr()等方法,另外还有其他方法可供使用,可自行研究。

相关推荐
咩咩啃树皮27 分钟前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
鱟鲥鳚1 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
大模型码小白2 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
腾渊信息科技公司3 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地4 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
wuqingshun3141594 小时前
TCP超时重传机制是为了解决什么问题?
java
莫逸风7 小时前
【AgentScope 2.0】 0. 学习指南
java·llm·agent·agentscope
隔窗听雨眠7 小时前
Spring Boot在云原生时代的编程范式革新研究
spring boot·后端·云原生
z123456789867 小时前
2026最新两款AI编程工具深度对比实测
java·数据库·ai编程
yaoxin5211238 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python