Dom4j操作xml文件
xml文件在工程中经常会用到,如web.xml、spring的相关配置、Mybatis的xml文件等等,很多开源框架都有对xml文件的解析。下面用dom4j来写一个小demo,操作xml文件。
1、pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cust</groupId> <artifactId>base</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>base Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/dom4j/dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>base</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
2、装载数据实体
package com.operaterXml; /** * 需写入/读取的实体类 */ public class Student { private String name; private String address; public Student(String name, String address) { this.name = name; this.address = address; } public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; } public String getName() { return name; } public String getAddress() { return address; } }
3、写入xml文件
package com.operaterXml; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @ClassName WriterOperaterXml * @Description 写入xml * @Author snails * @Version 1.0 */ public class WriterOperaterXml { public static void main(String[] args) throws DocumentException, IllegalAccessException, IOException { // 获取数据信息 List<Student> stuInfo = getStuInfo(); File simpleXml = new File("src/simpleXml.xml"); // 获取document对象 Document document = getDocument(stuInfo); // 写入xml文件 writeXml(simpleXml, document); } /** * 获取Document对象 * @param stuList * @return * @throws DocumentException * @throws IllegalAccessException * @throws IOException */ public static Document getDocument(List<Student> stuList) throws DocumentException, IllegalAccessException, IOException { // 创建document对象 Document document = DocumentHelper.createDocument(); // 创建根节点 Element root = document.addElement("root"); // 生成子节点 Element header = root.addElement("header"); // Element body = root.addElement("body"); // 生成子节点header内容 header.addElement("ver").setText("1.0"); header.addElement("date").setText(DateFormat.getDateInstance().format(new Date())); header.addElement("number").setText("1"); // 生成自子节点body及其子节点info内容 Element body = root.addElement("body"); for (Student stu : stuList) { Element info = body.addElement("info"); Field[] declaredFields = stu.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); Element element = info.addElement(field.getName()); element.setText(String.valueOf(field.get(stu))); } } return document; } /** * 将数据流写入xml文件 * @param file * @param document * @throws IOException */ public static void writeXml(File file, Document document) throws IOException { XMLWriter xmlWriter = null; FileOutputStream fos = null; try{ fos = new FileOutputStream(file); // 生成xml格式 OutputFormat prettyPrint = OutputFormat.createPrettyPrint(); xmlWriter = new XMLWriter(fos, prettyPrint); // 是否使用转义,默认使用转义 xmlWriter.setEscapeText(false); // 将流写入xml文件 xmlWriter.write(document); } finally { if(fos != null){ fos.close(); } if(xmlWriter != null){ xmlWriter.close(); } } } /**获取数据信息 * @return */ public static List<Student> getStuInfo(){ ArrayList<Student> students = new ArrayList<>(); students.add(new Student("张三", "四川")); students.add(new Student("李四", "福建")); students.add(new Student("王五", "海南")); return students; } }
4、生成xml文件
5、解析xml文件
package com.operaterXml; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.File; import java.util.List; /** * @ClassName ReaderOperaterXml * @Description 读取xml * @Author snails * @Version 1.0 */ public class ReaderOperaterXml { public static void main(String[] args) throws Exception { File file = new File("src/simpleXml.xml"); parseXml(file); } /** * 解析xml文件 * @param file * @throws DocumentException */ public static void parseXml(File file) throws DocumentException { // 获取document对象 Document doc = new SAXReader().read(file); // 获取根节点信息 Element rootElement = doc.getRootElement(); System.out.println("----------------------header元素节点下的内容----------------------"); List<Element> headerChildNodes = rootElement.element("header").elements(); for (int i = 0; i < headerChildNodes.size(); i++) { System.out.println("header元素节点下子节点的文本节点名称:" + headerChildNodes.get(i).getName() + "; 子节点的文本节点内容: " + headerChildNodes.get(i).getText()); } System.out.println("----------------------body元素节点下的内容 info----------------------"); // 获取body节点下的子节点 List<Element> bodyChildNodes = rootElement.element("body").elements("info"); for (Element ele: bodyChildNodes) { // 获取info节点下的子节点 List<Element> elements = ele.elements(); for (int i = 0; i < elements.size(); i++) { System.out.println("info元素节点下子节点的文本节点名称:" + elements.get(i).getName() + "; 子节点的文本节点内容: " + elements.get(i).getText()); } } } }
6、解析结果
以上是利用dom4j的原生API写的一个小demo。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)