`

xml文件解析之Dom4j

    博客分类:
  • xml
阅读更多

以下示例比较简单,仅供初学者参考。

示例引用包:dom4j-1.6.1

 

读取xml文件:

import java.io.ByteArrayInputStream;
import java.io.File;   
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;

import org.dom4j.Attribute;   
import org.dom4j.Document;
import org.dom4j.DocumentException;   
import org.dom4j.Element;   
import org.dom4j.ProcessingInstruction;   
import org.dom4j.VisitorSupport;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;


public class XmlReaderDom4j {
	
	public static void main(String[] args){
		//readGB2312();
		readUTF8();
	}
	
	public static void readGB2312(){
		SAXReader reader = new SAXReader();
        File file = new File("src/students.xml");
        
        try {
            Document doc = reader.read(file);
            doc.accept(new MyVistor());
            
        } catch (DocumentException e) {
            e.printStackTrace();
        }
	}
	
	
	public static void readUTF8(){
		try{			
	        SAXReader reader = new SAXReader();
	        OutputFormat format = OutputFormat.createPrettyPrint();
	        format.setEncoding("UTF-8"); //设置XML文件的编码格式

	     File file = new File("src/author.xml");
	        if(file.exists()){
	        	Document document = reader.read(file); //  读取XML文件 
	        	Element root = document.getRootElement(); //  得到根节点
	        	
	        	for(Iterator i = root.elementIterator(); i.hasNext();){
	        		Element e = (Element) i.next();
	                System.out.println(e.getName());
	                System.out.println(e.getPath());
	                System.out.println(e.getText());
	                System.out.println(e.getStringValue());
	                
	                for(Iterator j = e.attributeIterator();j.hasNext();){
	                	Attribute attribute = (Attribute) j.next();
	                	System.out.println(attribute.getStringValue());
	                }
	             }   
	        }else{
	        	System.out.println("文件没找到");
	        }

		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	/**  
	 * 获取Dom4j的Document对象  
	  * @param data  
	 * @param charset  
	 * @return  
	 */  
	public static Document getDocument(String data, String charset) {	       
	    SAXReader reader = new SAXReader();
	    Document document = null;
	    InputStreamReader utfreader = null;
	    InputStream in = null;
	       
	    try {   
	        in = new ByteArrayInputStream(data.getBytes());
	        utfreader = new InputStreamReader(in, charset);
	        document = reader.read(utfreader);
	        
	    }catch (Exception e) {
	    	e.printStackTrace();
	    	
	    }finally {   
	        try {   
	            in.close();   
	        }   
	        catch (IOException e) {
	        	e.printStackTrace();
	        }
	    }
	    
	    return document;     
	}
	
	
	/**
	 * 内部类
	 * @author Administrator
	 *
	 */
	public static class MyVistor extends VisitorSupport {
        public void visit(Attribute node) {
            System.out.println("** Attibute:" + node.getName() + "="  
                    + node.getValue());
        }
  
        public void visit(Element node) {
            if (node.isTextOnly()) {
            	System.out.println("** Element:" + node.getName() + "="  
                        + node.getText());   
            }else{
                System.out.println("--------" + node.getName() + "-------");   
            }
        }   
  
        @Override  
        public void visit(ProcessingInstruction node) {
            System.out.println("** PI:"+node.getTarget()+" "+node.getText());   
        }   
    }
}

 

 author.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
<author name="詹姆斯" location="UK">小皇帝</author>
<author name="科比" location="US">Bob McWrirter</author>
</root>

 

 

 生成XML文件:

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;


public class XmlWriterDom4j {
	
    public static void main(String[] args) {   
        try {
            XMLWriter writer = new XMLWriter(new FileWriter("src/author.xml"));   
            Document doc = createDoc();
            writer.write(doc);
            writer.close();   
  
            // Pretty print the document to System.out   
            // 設置了打印的格式,将读出到控制台的格式进行美化
            OutputFormat format = OutputFormat.createPrettyPrint();   
            writer = new XMLWriter(System.out, format);
            writer.write(doc);
  
        } catch (IOException e) {   
             e.printStackTrace();
        }   
    }
	
    public static Document createDoc() {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("root");
        Element author1 = root.addElement("author")
        		.addAttribute("name","James")
        		.addAttribute("location", "UK")
                .addText("Jame Strachan");
        
        Element author2 = root.addElement("author")
        		.addAttribute("name", "Bob")
                .addAttribute("location", "US")
                .addText("Bob McWrirter");
        
        return doc;
    }

}

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics