依赖
<dependency><groupId>com.thoughtworks.xstream</groupId><artifactId>xstream</artifactId><version>1.4.18</version></dependency>
实体类
package com.itheima.util;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {private String name;private int age;
}
工具类
package com.itheima.one;import com.thoughtworks.xstream.XStream;import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;public class XmlUtils {private static final XStream xStream = new XStream();static {// 允许反序列化xStream.allowTypesByWildcard(new String[] { "**" });}/*** 将 Java 对象转换为 XML,并写入指定文件** @param <T> 要转换的 Java 对象类型* @param object 要转换的 Java 对象* @param filePath 输出的 XML 文件路径*/public static <T> void objectToXml(T object, String filePath) {// 为对象定义 XML 别名xStream.alias(object.getClass().getSimpleName(), object.getClass());StringWriter stringWriter = new StringWriter();stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");// 将对象转为 XML 字符串xStream.toXML(object, stringWriter);// 获取文件路径Path path = Paths.get(filePath);// 使用 NIO 的 BufferedWriter 将 XML 字符串写入文件try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {writer.write(stringWriter.toString());System.out.println("XML 内容已成功写入到文件:" + path.toString());} catch (IOException e) {System.err.println("写入 XML 文件时发生错误: " + e.getMessage());e.printStackTrace();}}/*** 从 XML 文件中读取数据并转换为 Java 对象** @param filePath XML 文件路径* @param clazz 要转换为的 Java 类* @param <T> 转换后的对象类型* @return 转换后的 Java 对象,如果读取或转换失败则返回 null*/public static <T> T xmlToObject(String filePath, Class<T> clazz) {Path path = Paths.get(filePath);// 验证文件是否存在if (!Files.exists(path)) {System.err.println("指定的文件不存在: " + filePath);return null;}try {String xml = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);return (T) xStream.fromXML(xml, clazz);} catch (IOException e) {System.err.println("读取 XML 文件时发生错误: " + e.getMessage());e.printStackTrace();} catch (ClassCastException e) {System.err.println("转换 XML 数据时发生错误: " + e.getMessage());e.printStackTrace();}return null;}
}
测试
package com.itheima.one;import com.itheima.one.XmlUtils;
import com.itheima.util.Person;public class Main {public static void main(String[] args) {// 假设有一个对象 person,你需要将其转换为 XMLPerson person = new Person("John", 30);String filePath = "D:/Desktop/person.xml";// 调用静态方法将对象转换为 XML 并写入文件XmlUtils.objectToXml(person, filePath);// 从 XML 文件中读取并转换为对象Person readPerson = XmlUtils.xmlToObject(filePath, Person.class);System.out.println(readPerson);}
}
输出结果:
XML 内容已成功写入到文件:D:\Desktop\person.xml
Person(name=John, age=30)
D:/Desktop/person.xml文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<Person><name>John</name><age>30</age>
</Person>