1.引入依赖
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
2.生成xml
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
public class Dom4jXml {
@Test
public void test() {
long start = System.currentTimeMillis();
createXml();
System.out.println("运行时间: "+ (System.currentTimeMillis() - start) / 1000 + "s");
}
public static void createXml() {
try {
// 创建document对象
Document document = DocumentHelper.createDocument();
// 创建根节点rss
Element rss = document.addElement("rss");
// 向rss节点添加属性
rss.addAttribute("version", "2.0");
// 向rss节点添加子节点
Element channel = rss.addElement("channel");
Element title = channel.addElement("title");
title.setText("国内最新新闻");
// 设置生成xml的格式
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
// 生成xml文件
File file = new File("rss.xml");
System.out.println("file = " + file.getAbsolutePath());
XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
// 设置是否转义,默认使用转义字符
writer.setEscapeText(false);
writer.write(document);
writer.close();
System.out.println("生成xml文件成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("生成xml文件失败");
}
}
}
3.生成结果
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>国内最新新闻</title>
</channel>
</rss>