神秘的 J2ee 殿堂

·古之学者必有师·做学者亦要做师者·FIGHTING·

Dom4j构建、解析XML实例

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

posted on 2008-07-11 13:42 月芽儿 阅读(992) 评论(0)  编辑  收藏 所属分类: J2EE学习摘录


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(2)

随笔分类

随笔档案

相册

搜索

最新评论

阅读排行榜

评论排行榜