dom4j 簡單使用
2018-04-23 14:42 xiashengwang 閱讀(776) 評論(0) 收藏 舉報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>
浙公網安備 33010602011771號