如何使用XStream将Book对象追加到XML文件并生成规范格式?
解决XStream追加XML时重复声明与格式化问题
当前代码每次调用updateBookList都会生成包含XML声明的完整XML片段,导致文件中出现重复声明,且输出无格式化。要实现单一声明+格式化节点的效果,可按以下方式修改:
修改后的代码
public void updateBookList(String title, String author, String publisher, int year, int numPages) { XStream xstream = new XStream(new StaxDriver()); xstream.alias("book", Book.class); // 禁用XStream自动输出XML声明 xstream.addDefaultImplementation(NoNameCoder.class, NameCoder.class); Book book = new Book(title, author, publisher, year, numPages); File xmlFile = new File("booklist.xml"); try (FileWriter fw = new FileWriter(xmlFile, true); BufferedWriter bw = new BufferedWriter(fw); // 使用PrettyPrintWriter实现格式化输出 PrettyPrintWriter out = new PrettyPrintWriter(bw)) { // 第一次创建文件时写入XML声明和换行 if (!xmlFile.exists() || xmlFile.length() == 0) { out.write("<?xml version=\"1.0\" ?>"); out.write("\n\n"); } // 仅序列化book节点,不输出XML声明 xstream.marshal(book, out); out.write("\n\n"); // 节点之间加空行分隔 } catch (IOException e) { e.printStackTrace(); // 替换为实际的异常处理逻辑 } }
关键改动说明
- 控制XML声明写入时机:通过判断文件是否为空,仅在首次创建时写入一次XML声明,避免重复。
- 启用格式化输出:使用
PrettyPrintWriter替代PrintWriter,自动生成带缩进的结构化XML内容。 - 禁用自动声明生成:通过配置XStream的编码规则,让序列化单个节点时不附带XML声明。
- 优化节点布局:每个book节点写入后添加空行,保持文件结构清晰易读。
补充安全配置(针对新版XStream)
如果使用的XStream版本较新,为避免序列化安全风险,可在初始化XStream后加入以下配置:
xstream.setupDefaultSecurity(xstream); xstream.allowTypes(new Class[]{Book.class});
内容的提问来源于stack exchange,提问作者Julles
相关产品推荐
相关产品推荐

