1 /* 2 * aTunes 3 * Copyright (C) Alex Aranda, Sylvain Gaudard and contributors 4 * 5 * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors 6 * 7 * http://www.atunes.org 8 * http://sourceforge.net/projects/atunes 9 * 10 * This program is free software; you can redistribute it and/or 11 * modify it under the terms of the GNU General Public License 12 * as published by the Free Software Foundation; either version 2 13 * of the License, or (at your option) any later version. 14 * 15 * This program is distributed in the hope that it will be useful, 16 * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 * GNU General Public License for more details. 19 */ 20 21 package net.sourceforge.atunes.utils; 22 23 import javax.xml.xpath.XPath; 24 import javax.xml.xpath.XPathConstants; 25 import javax.xml.xpath.XPathExpressionException; 26 import javax.xml.xpath.XPathFactory; 27 28 import org.w3c.dom.Node; 29 import org.w3c.dom.NodeList; 30 31 /** 32 * Utility methods for XPath 33 * @author alex 34 * 35 */ 36 public final class XPathUtils { 37 XPathUtils()38 private XPathUtils() {} 39 40 private static volatile ThreadLocal<XPath> xPath; 41 42 /** 43 * Evaluates a XPath expression from a XML node, returning a Node object. 44 * 45 * @param expression 46 * A XPath expression 47 * @param node 48 * The Node for which this expression should be evaluated 49 * 50 * @return The result of evaluating the XPath expression to the given Node 51 * or <code>null</code> if an exception occured 52 */ evaluateXPathExpressionAndReturnNode(String expression, Node node)53 public static Node evaluateXPathExpressionAndReturnNode(String expression, Node node) { 54 try { 55 return (Node) getXPath().get().evaluate(expression, node, XPathConstants.NODE); 56 } catch (XPathExpressionException e) { 57 return null; 58 } 59 } 60 61 /** 62 * Evaluates a XPath expression from a XML node, returning a NodeList. 63 * 64 * @param expression 65 * A XPath expression 66 * @param node 67 * The NodeList for which this expression should be evaluated 68 * 69 * @return The result of evaluating the XPath expression to the given or 70 * <code>null</code> if an ecxception occured NodeList 71 */ evaluateXPathExpressionAndReturnNodeList(String expression, Node node)72 public static NodeList evaluateXPathExpressionAndReturnNodeList(String expression, Node node) { 73 try { 74 return (NodeList) getXPath().get().evaluate(expression, node, XPathConstants.NODESET); 75 } catch (XPathExpressionException e) { 76 return null; 77 } 78 } 79 getXPath()80 private static ThreadLocal<XPath> getXPath() { 81 if (xPath == null) { 82 xPath = new ThreadLocal<XPath>() { 83 @Override 84 protected XPath initialValue() { 85 return XPathFactory.newInstance().newXPath(); 86 } 87 }; 88 } 89 return xPath; 90 } 91 } 92