dom4j 简单使用

1,需要用到dom4j的jar包。为了打开xml方便,设计一个简单的封装类。

package cn.com.gtmc.glaf2.util;

import java.io.File;
import java.net.URISyntaxException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class XmlUtil {
    /**
     * @param path
     *            相对路径,相对于classes文件夹
     * @return Document
     *            org.dom4j.Document
     * @throws DocumentException
     */
    public static Document getDocument(String path) throws DocumentException, URISyntaxException {
        String filePath = XmlUtil.class.getClassLoader().getResource("").toURI().getPath() + path;

        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File(filePath));
        return doc;
    }

}

2,使用的例子

<?xml version="1.0" encoding="UTF-8"?>
<workbook>
    <worksheet index="0">
        <cell src="Supplier.remark" target="B3" description="备注" />
    </worksheet>
</workbook>
        try {
            Supplier obj = (Supplier)params.get("obj");
            
            Document doc = XmlUtil.getDocument("excel\\supplier-import.xml");
            Element root = doc.getRootElement();
            
            List nodes = root.selectNodes("worksheet/cell");
            Iterator it = nodes.iterator();
            while(it.hasNext()) {
               Element ele = (Element)it.next();
               String src = ele.attributeValue("src");
               String cellTarget = ele.attributeValue("target");
               if(src != null && !"".equals(src)) {
                   String[] splits = src.split("\\.");
                   String className = splits[0];
                   String filedName = splits[1];
                                   //。。。
               }
            }                

        } catch (Exception e) {
            LOG.error("", e);
        }

特别要注意,上面的Element.selectNodes方法,用到了XPath的语法,dom4j.jar里面是没有包含这个功能的,需要添加下面这个jar包(maven工程,非maven工程需要自己去下载),不然会报错。

        <!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>

猜你喜欢

转载自www.cnblogs.com/xiashengwang/p/8919048.html