dom4j 输出xml 完整例子

dom4j 输出xml 完整例子如下:

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;



/**
 * dom4j 输出xml
 * 
 * @version 2012-11-28
 * @author www.jsjtt.com
 * @since JDK1.6
 * 
 */
public class Dom4jTest {

	public static void main( String arg[] ) {
////输出xml格式
// <?xml version="1.0" encoding="UTF-8"?>
//
// <books>
// <book id="1">
// <name>java</name>
// <author>jsjtt.com</author>
// <price>100</price>
// </book>
// </books>
		XMLWriter writer = null;// 声明写XML的对象
		String filePath = "books.xml";
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding( "UTF-8" );// 设置XML文件的编码格式

		File file = new File( filePath );
		// 新建student.xml文件并新增内容
		Document document = DocumentHelper.createDocument();
		//
		Element root = document.addElement( "books" );
		Element student = root.addElement( "book" );
		student.addAttribute( "id", "1" );
		Element id = student.addElement( "name" );
		id.setText( "java" );
		Element name = student.addElement( "author" );
		name.setText( "jsjtt.com" );
		Element age = student.addElement( "price" );
		age.setText( "100" );

		try {
			writer = new XMLWriter( new FileWriter( file ), format );
			writer.write( document );
			writer.close();
		}
		catch ( IOException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
来源://作者:/更新时间:2012-11-28
相关文章
评论:
验证码:
匿名评论: