简单的Dom4j写入XML文件例子

package com.dom.Service;

import java.io.File;
import java.io.FileWriter;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Test4 {

	public static void main(String[] args) {
		try {
			
			SAXReader reader = new SAXReader();
			String file = "test.xml";
			Document document = reader.read(new File(file));
			Element root = document.getRootElement();
			System.out.println(root.getName());
			
			root.addElement("forth").addAttribute("name", "forth").addAttribute("sex", "女");
			
			FileWriter writer = new FileWriter(file);
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("GBK");
			XMLWriter xmlWriter = new XMLWriter(writer,format);
			xmlWriter.write(document);
			writer.close();
			xmlWriter.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 

你可能感兴趣的:(xml)