下面是一个工具类,以XPath方式获取XML元素值,此工具类于上海期货交易所的一个系统项目中创建,代码如下:
java 代码
- /**
- *
- */
- package com.test.utils.toolkit;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.net.MalformedURLException;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import org.dom4j.Document;
- import org.dom4j.DocumentException;
- import org.dom4j.Element;
- import org.dom4j.Node;
- import org.dom4j.io.SAXReader;
- /**
- * @author shjy.nicholas
- *
- */
- public class XMLToolkit {
- private String fileName = null ;
- private Document doc = null ;
- public XMLToolkit(String fileName) throws MalformedURLException, DocumentException, FileNotFoundException {
- this.fileName = fileName ;
- this.doc = readDocument() ;
- }
- private Document readDocument()
- throws MalformedURLException, DocumentException, FileNotFoundException {
- SAXReader reader = new SAXReader();
- Document document = reader.read(new File(this.fileName));
- return document;
- }
- public Element getRootElement() {
- return this.doc.getRootElement();
- }
- // 获取唯一节点的值
- public String getNodeValue(String path) {
- Node node = this.doc.selectSingleNode(path);
- String value = node.getText() ;
- return value;
- }
- // 获取多个同名节点的值
- public List getNodesValue(String path) {
- List list = this.doc.selectNodes(path);
- Iterator it = list.iterator() ;
- List resultList = new ArrayList() ;
- while(it.hasNext()) {
- Node node = (Node)it.next() ;
- resultList.add(node.getText()) ;
- }
- return resultList ;
- }
- public static void main(String[] args) {
- try {
- XMLToolkit xmlTool = new XMLToolkit("home/datasource.xml") ;
- String value = xmlTool.getNodeValue("//datasources/datasource/driver") ;
- System.out.println("value: " + value) ;
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (DocumentException e) {
- e.printStackTrace();
- }
- }
- }