Dom4j初步封装

     2015.07.23 去年做爬虫的时候用了dom4j做了xml的生成,读取,今天有仔细看了有关dom4j的资料,对dom4j进行了初步的封装。封装了读取文档和写入文档的操作。

     2015.07.24 今天对dom4jDemo又做了扩展,使用XPath,实现了获取指定id的元素,和根据tagName获取一个List的集合。

     XPath初步理解:

     //    从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置

    /   从根节点选取

    //tagName 在文档中选取名称为tagName的全部Element

    //*  XPath可以使用通配符*,表示选取全部的元素

    //*[@attribute='arrtibuteValue']  选取属性为attribute,且属性值为attributeValue的所有元素。

package com.zxt.xmlparser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * @author 赵笑天
 *
 * @time 2015年7月23日
 * 
 */
public class Dom4jDemo {
    //最初解析文件的句柄
    private SAXReader saxReader ;
    //指向内存中的Document对象
    private Document doc;
    //指向要操作的文件
    private File file;
    
    public Dom4jDemo(String filePath) throws Exception{
        saxReader = new SAXReader();
        file = new File(filePath);
        
        if(!file.exists()){
            file.createNewFile();
        }
        
        setDoc(saxReader.read(file));
    }
    
    public Document getDoc() {
        return doc;
    }

    public void setDoc(Document doc) {
        this.doc = doc;
    }
    
    
    public void write2Xml() throws Exception{
        //创建输出模式的时候用有缩进的格式,便于查看
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        OutputStream os = new FileOutputStream(file);
        XMLWriter xmlWriter = new XMLWriter(os,outputFormat);
        xmlWriter.write(doc);
    }
    
    
    /**
     * @param id 某元素的id属性,其中id是唯一的,不能重复的
     * 
     * @return e Element,根据元素id返回的id,如果没有则返回空值
     * 
     * */
    public Element getElementById(String idValue){
        Element e = null;
        
        String xPath = "//*[@id='"+idValue+"']";
        
        e = (Element) doc.selectSingleNode(xPath);
        
        return e;
    }
    
    /**
     * @param tagName 标签的名称
     * 
     * @return List Element元素的List集合,如果没有则返回null
     * 
     * */
    public List getElementsByTagName(String tagName){
        List els = null;
        
        String xPath = "//"+tagName+"";
        
        els = doc.selectNodes(xPath);
        
        return els;
    }
}



你可能感兴趣的:(Dom4j初步封装)