思路是先生成一个xml再利用IO流写到磁盘中去。

生成思路就是注释

package cn.liu.xmtest;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 创建一个xml
 * @author Administrator
 *
 */
public class Demo02 {
	public static void main(String[] args) throws Exception {
		/**
		 * one构建xml的内容
		 */
		//1.先创建一个Document对象,代表xml
		Document doc = DocumentHelper.createDocument();
		//2.创建根元素
		Element root = doc.addElement("Data");
		//3.创建子元素
		Element sunele = root.addElement("student");
		//4.子元素创建属性
		sunele.addAttribute("id", "1");
		//5.给子元素ele再创建一些子元素
		Element name = sunele.addElement("name");
		Element course = sunele.addElement("course");
		Element score = sunele.addElement("score");
		//6.给上面ele子元素添加文本信息
		name.addText("WangTong");
		course.addText("java");
		score.addText("89");
		/**
		 * 利用IO流把xml写出去
		 */
		FileWriter os = new FileWriter(new File("src\\createXml.xml"));
		doc.write(os);
		os.flush();
		os.close();
	}
}

运行结果:

<?xml version="1.0" encoding="UTF-8"?>
<Data><student id="1"><name>WangTong</name><course>java</course><score>89</score></student></Data>

很乱,没有清晰的嵌套,如何形成清晰嵌套?

OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter os = new XMLWriter(new FileWriter(new
		File("src\\createXml04.xml")), format);

 在来生成xml:

package cn.liu.xmtest;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

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

public class Demo03 {
	public static void main(String[] args) throws Exception {
		/**
		 * one构建xml的内容
		 */
		//1.先创建一个Document对象,代表xml
		Document doc = DocumentHelper.createDocument();
		//2.创建根元素
		Element root = doc.addElement("Data");
		//3.创建子元素
		Element sunele = root.addElement("student");
		//4.子元素创建属性
		sunele.addAttribute("id", "1");
		//5.给子元素ele再创建一些子元素
		Element name = sunele.addElement("name");
		Element course = sunele.addElement("course");
		Element score = sunele.addElement("score");
		//6.给上面ele子元素添加文本信息
		name.addText("WangTong");
		course.addText("java");
		score.addText("89");
		
		//再给根元素增加一个元素
		Element sunele2 = root.addElement("student").addAttribute("id", "2");
		sunele2.addElement("name").addText("WangTong");
		sunele2.addElement("course").addText("java");
		sunele2.addElement("score").addText("58");
		
		/**
		 * 利用IO流把xml写出去
		 */
		/**
		 *  FileWriter os = new FileWriter(new File("src\\createXml02.xml"));
			doc.write(os);
			os.flush();
			os.close();
		 */
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter os = new XMLWriter(new FileWriter(new
		File("src\\createXml04.xml")), format);
		os.write(doc);
		// [8] 关闭资源
		os.close();
	}
}

运行结果: 

java 如何创建xml文件怎么打开 java创建xml对象_java 如何创建xml文件怎么打开