【Java】用Dom4J写XML文件

package com.test.xml;

import java.io.File;
import java.io.PrintWriter;

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

public class Dom4jTest {
	public static void main(String[] args) throws Exception {
		Document document = DocumentHelper.createDocument();

		Element person = document.addElement("person");

		Element name = person.addElement("name");

		Element age = person.addElement("age");

		name.setText("cao");

		age.setText(24 + "");

		File dir = new File("xml");

		if (!dir.exists()) {

			dir.mkdir();

		}

		PrintWriter pw = new PrintWriter(new File("xml/result.xml"));

		OutputFormat format = OutputFormat.createPrettyPrint();

		format.setEncoding("utf-8");

		XMLWriter writer = new XMLWriter(pw, format);

		writer.write(document);
		
		pw.flush();
		
		pw.close();
	}
}

你可能感兴趣的:(java,xml)