用xml存java实体对象数据

package test.fortest;

import java.io.File;
import java.io.FileOutputStream;
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 WriteJavaEntityToXMl {
	public static void main(String args[]) {
	     //创建xml文件
             Document document = DocumentHelper.createDocument();
	     //添加根元素
	     Element root = document.addElement("root");
	     //添加子元素,并设置元素属性和文本
	     Element author1 = root.addElement( "author" )
	            .addAttribute("name", "James")
	            .addAttribute("location", "UK")
	            .addText("James Strachan");
	        
	     Element author2 = root.addElement("author")
	            .addAttribute("name", "Bob")
	            .addAttribute("location", "US")
	            .addText("Bob McWhirter");
	     
	     //用XMLWriter类写xml文件
	     XMLWriter xmlWriter = null;
	     //文件路径
	     String outputPath = "D:"+File.separator + "ForLearn" + File.separator + 
	"Example" + File.separator + "mavenEx" + File.separator  + "exampleF" + File.separator +
	"src"+ File.separator  + "main" + File.separator  + "webapp" + File.separator +
	"WEB-INF" + File.separator + "authors.xml";;
	     try {
		    OutputFormat format = OutputFormat.createPrettyPrint();
		    format.setLineSeparator("\r\n");
			format.setEncoding("utf-8");
			xmlWriter = new XMLWriter(new FileOutputStream(outputPath), format);
			xmlWriter.write(document);
		} catch (IOException exp) {
			exp.printStackTrace();
		} finally {
			if(xmlWriter != null) {
				try {
					xmlWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

输出文件如下:

authors.xml

<?xml version="1.0" encoding="utf-8"?>

<root>
  <author name="James" location="UK">James Strachan</author>
  <author name="Bob" location="US">Bob McWhirter</author>
</root>




你可能感兴趣的:(用xml存java实体对象数据)