首页 > 代码库 > java 生成 xml 文件

java 生成 xml 文件

  解析会了,那接着来学学生成~

  同样的引入依赖:

import java.io.File;
import java.io.FileOutputStream;

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

  注意处理异常:

public static void main(String[] args) throws Exception {

}

  创建树:

Document doc = DocumentHelper.createDocument();
//增加根节点
Element books = doc.addElement("books");
//增加子元素
Element book1 = books.addElement("book");
Element title1 = book1.addElement("title");
Element author1 = book1.addElement("author");
    
Element book2 = books.addElement("book");
Element title2 = book2.addElement("title");
Element author2 = book2.addElement("author");

  为相应节点增加属性:

book1.addAttribute("id", "001");
title1.setText("Harry Potter");
author1.setText("J K. Rowling");
          
book2.addAttribute("id", "002");
title2.setText("Learning XML");
author2.setText("Erik T. Ray");

  接下来是输出,设置编码,创建 File 对象:

OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
File file = new File("writeBooks.xml");

  根据创建的 File 对象,来生成 XMLWriter 对象:

XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);

  最后,将创建的 Document 对象写入 XMLWriter 对象:

writer.write(doc);

 

java 生成 xml 文件