dom4j操作xml基礎

        DOM是用與平臺和語言無關的方式表示XML文檔的官方W3C標準,是以層次結構組織的節點或信息片斷的集合,它總是把文檔看成一個文檔樹,SAX處理能夠立即開始,而不是等待所有的數據被處理,對於大型文檔來說是個巨大的優點,JDOM無疑轉爲Java平臺設計,它簡化與XML的交互並且比使用DOM更快,但是它大量的試用具體類操作從而降低了操作的靈活性,dom4j代表了全新的開發結果,集成的XPath支持、XML Schema支持以及用於大文檔或流化文檔的基於事件的處理,它大量的使用了接口定義,提供了比JDOM大得多的靈活性。下面是一個簡單的生成xml例子:
package org.bulktree.xml;

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();
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章