dom4j 是一个用java处理xml非常好的开源包,其实java自带的dom也很好用,但是java没有直接写入xml格式的类,所以在保存xml格式的数据时,先将数据转化成dom结构,最后保存java的dom结构,以下是《java核心技术》上的一段代码,在我的工程中也调试通过了。
// save DOM tree to xml file
public static void saveDOM2XML(Document document, String xmlFilename) {
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transform;
transform = tf.newTransformer();
DOMSource source = new DOMSource(document);
transform.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transform.setOutputProperty(OutputKeys.INDENT, "yes");
// PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
FileOutputStream file = new FileOutputStream(xmlFilename);
StreamResult result = new StreamResult(file);
transform.transform(source, result);
} catch (TransformerConfigurationException e) {
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (TransformerException e) {
System.out.println(e.getMessage());
}
}
输入dom类型数据和要保存为xml文件的地址。