日期:2014-05-17 浏览次数:20857 次
package org.sl.xml; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.util.List; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; /** * 以xpath方式读取xml * @author Shanl * */ public class XPathHelper { private File file = null; private boolean cache = false; private static Logger logger = Logger.getLogger(XPathHelper.class); /** * 构造器<br> * 相当于XPathHelper(res, true); * @param res 资源名 */ public XPathHelper(String res){ this(res, true); } /** * 构造器<br> * 注:这个方法会在系统中查找与res匹配的资源,如果找不到则抛出RunntimeException * @param res 资源名 * @param cahce 是否缓存XML */ public XPathHelper(String res, boolean cache){ this.cache = cache; URL url = ClassLoader.getSystemResource(res); if(null == url){ throw new RuntimeException(res + " not found."); } String protocol = url.getProtocol(); String path = url.toString(); path = path.replaceFirst(protocol + ":/", ""); file = new File(path); if(!file.exists()){ throw new RuntimeException(res + " not found."); } } /** * 返回xpath所表示的结点数 * @param xpath * @return */ public int countNode(String xpath){ Document fileDocument = readDocument(); if(!findXPath(xpath)){ return 0; } List es = fileDocument.selectNodes(xpath); if(null == es){ return 0; }else{ return es.size(); } } /** * 以xpath方式得到结果的文本 * @param xpath * @return */ public String getText(String xpath){ String text = ""; Document fileDocument = readDocument(); if(!findXPath(xpath)){ return ""; } Node node = fileDocument.selectSingleNode(xpath); text = node.getText(); return text; } /** * 以xpath方式得到结点某属性的值 * @param xpath * @param attrName * @return */ public String getAttribute(String xpath, String attrName){ String attr = ""; Document fileDocument = readDocument(); if(!findXPath(xpath)){ return ""; } List es = fileDocument.selectNodes(xpath); attr = ((Element)es.get(0)).attributeValue(attrName); return attr; } /** * 查找xpath是否存在 * @param xpath * @return 存在返回true,否则返回false; */ public boolean findXPath(