1、引入依赖
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.1</version>
</dependency>
2、代码示例
public class Test {
public static void main(String[] args) {
// 获取Document对象
Document doc = DocumentHelper.createDocument();
// 添加根元素
Element root = doc.addElement("persons");
// 在根元素下添加子节点book
Element person = root.addElement("person");
// 给book节点添加id属性
person.addAttribute("id", "007");
// 在book下添加子节点并赋值
person.addElement("name").addText("张三");
person.addElement("sex").addText("男");
person.addElement("age").addText("18");
// 输出到文件中
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
XMLWriter writer = null;
try {
FileWriter fileWriter = new FileWriter("D:/_temp/person.xml");
writer = new XMLWriter(fileWriter, outputFormat);
writer.write(doc);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
(提示:若需要在控制台中打印出XML
的内容,可将FileWriter
替换为StringWriter
。)
3、打印结果
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="007">
<name>张三</name>
<sex>男</sex>
<age>18</age>
</person>
</persons>