TransformerFactory用于创建Transformer将DOM Document写入XML文件:先用DocumentBuilder构建Document,再配置Transformer启用缩进、UTF-8编码等属性,最后通过transform(DOMSource, StreamResult)完成落盘。
核心就一句话:用 transformerfactory 创建 transformer,再调用 transform() 方法把内存里的 document 对象写入文件。整个过程不涉及解析已有 xml,而是纯“从零构建 → 写出文件”。
准备一个合法的 DOM 树
持久化前必须有可输出的 Document 实例。不能直接 new,得通过 DocumentBuilder 构建:
- 用 DocumentBuilderFactory.newInstance() 获取工厂
- 调用 newDocumentBuilder() 得到 builder
- 执行 builder.newDocument() 获得空 Document 对象
- 用 createElement()、appendChild() 等方法逐步组装节点(比如创建 <root><item id="1"/></root>)
配置 Transformer 并启用格式化输出
默认生成的 XML 是一行式、无缩进的。如需可读性,需在 Transformer 上设置属性:
- 调用 transformer.setOutputProperty(OutputKeys.INDENT, "yes") 启用缩进
- 指定缩进量:transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
- 强制编码为 UTF-8:transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8")
- 声明 XML 版本与编码:transformer.setOutputProperty(OutputKeys.VERSION, "1.0")
执行转换并落盘到文件
这是最关键的一步,注意参数封装方式:
- 源数据封装为 DOMSource:new DOMSource(document)
- 目标位置封装为 StreamResult:new StreamResult(new File("output.xml"))
- 调用 transformer.transform(source, result) 即完成写入
- 无需手动 flush 或 close —— StreamResult 内部会自动处理文件流
异常与健壮性要点
实际工程中要捕获三类典型异常:
- ParserConfigurationException:DocumentBuilder 初始化失败(如工厂配置非法)
- TransformerConfigurationException:TransformerFactory 无法实例化 Transformer(如系统缺少 XSLT 支持)
- TransformerException:转换过程出错(常见于 document 为 null 或文件路径不可写)
建议在 finally 块中确保文件句柄释放(如果手动用了 FileOutputStream),但使用 StreamResult(File) 时通常无需额外干预。

















