import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/** *//**
*
* @author bulktree Email: [email protected]
* @date Aug 3, 2008
*/
public class XmlTest02 {
public Document createDocument() throws DocumentException {
/**//*
* 產生 一個document對象
*/
Document doc = DocumentHelper.createDocument();
/**//*
* 添加一個跟元素
*/
Element root = doc.addElement("Students");
Element child1 = root.addElement("student");
/**//*
* 設置屬性ID
*/
child1.addAttribute("ID", "001");
Element subChild1 = child1.addElement("name");
subChild1.setText("bulktree");
Element subChild2 = child1.addElement("age");
subChild2.setText("22");
Element subChild3 = child1.addElement("sex");
subChild3.setText("男");
Element child2 = root.addElement("student");
child2.addAttribute("ID", "002");
child2.addElement("name").setText("laoshulin");
child2.addElement("age").setText("22");
child2.addElement("sex").setText("女");
return doc;
}
public void writerDocument() throws Exception {
/**//*
* 格式化輸出
*/
OutputFormat of = new OutputFormat(" ", true);
/**//*
* 輸出到屏幕
*/
// XMLWriter xmlWriter = new XMLWriter(System.out, of);
/**//*
* 輸出到流中
*/
XMLWriter xmlWriter = new XMLWriter(new FileWriter("student.xml"), of);
xmlWriter.write(this.createDocument());
xmlWriter.close();
}
public static void main(String[] args) throws Exception {
new XmlTest02().writerDocument();
}
}