首先,用Eclipse新建一个工程,然后导入dom4j-1.6.1.jar包,然后新一个类,代码如下:
Dom4jTest.java
import org.dom4j.*; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import java.io.*; public class Dom4jTest { public static void main(String args[]) { Document doc = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement("students"); doc.setRootElement(root); Element stu1 = root.addElement("student"); Element name = stu1.addElement("name"); Element age = stu1.addElement("age"); name.setText("张三"); age.setText("23"); Element stu2 = root.addElement("student"); Element name2 = stu2.addElement("name"); Element age2 = stu2.addElement("age"); name2.setText("李四"); age2.setText("24"); try { //输出样式 OutputFormat outFmt = new OutputFormat(" ", true); outFmt.setEncoding("GB2312"); //输出xml文件 XMLWriter xml = new XMLWriter(new FileWriter("F://test.xml"),outFmt); xml.write(doc); xml.flush(); } catch (IOException e) { e.printStackTrace(); } } }
test.xml
张三 23 李四 24