package com.hunau.liuyong;
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官网 (里面有教程) http://dom4j.org/
public class Dom4jCreateXML {
public Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement( "root" );
Element author1 = root.addElement( "author" )
.addAttribute( "name", "月芽儿" )
.addAttribute( "location", "UK" )
.addText( "James Strachan" );
Element author2 = root.addElement( "author" )
.addAttribute( "name", "Bob" )
.addAttribute( "location", "US" )
.addText( "Bob McWhirter" );
return document;
}
public static void main(String[] args) throws Exception{
//FileWriter out = new FileWriter( "D:/test2.xml" );
Dom4jCreateXML djxml=new Dom4jCreateXML();
djxml.write(djxml.createDocument());
}
public void write(Document document) throws IOException {
// lets write to a file
XMLWriter writer = new XMLWriter(
new FileWriter( "d:/output.xml" )
);
writer.write( document );
writer.close();
//Pretty print the document to System.out
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter( System.out, format );
writer.write( document );
//格式化了XML输出,看效果,这个有用一些
//OutputFormat format = OutputFormat.createPrettyPrint();
/** 指定XML字符集编码 */
format.setEncoding("GBK");
writer = new XMLWriter(new FileWriter(new File("d:/output2.xml")),format);
writer.write(document);
writer.close();
//Compact format to System.out
format = OutputFormat.createCompactFormat();
writer = new XMLWriter( System.out, format );
writer.write( document );
}
}