1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package com.ochafik.xml;
20
21 import java.lang.ref.SoftReference;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25
26 import javax.xml.xpath.XPath;
27 import javax.xml.xpath.XPathConstants;
28 import javax.xml.xpath.XPathExpression;
29 import javax.xml.xpath.XPathExpressionException;
30 import javax.xml.xpath.XPathFactory;
31
32 import org.w3c.dom.Node;
33 import org.w3c.dom.NodeList;
34
35 import com.ochafik.lang.SyntaxUtils;
36
37 public class XPathUtils {
38 public static Map<String, SoftReference<XPathExpression>> xPathExpressionsCache = new HashMap<String, SoftReference<XPathExpression>>();
39 private static SoftReference<XPath> sharedXPath;
40 public static XPath getSharedXPath() {
41 XPath xPath = null;
42 if (sharedXPath != null)
43 xPath = sharedXPath.get();
44 if (xPath == null) {
45 XPathFactory xPathFactory = XPathFactory.newInstance();
46 sharedXPath = new SoftReference<XPath>(xPath = xPathFactory.newXPath());
47 }
48 return xPath;
49 }
50 public static List<Node> findNodesByXPath(String xPathString, Object source) throws XPathExpressionException {
51 return XMLUtils.list((NodeList)getXPathExpression(xPathString).evaluate(source, XPathConstants.NODESET));
52 }
53 public static Iterable<Node> findNodesIterableByXPath(String xPathString, Object source) throws XPathExpressionException {
54 return SyntaxUtils.iterable((NodeList)getXPathExpression(xPathString).evaluate(source, XPathConstants.NODESET));
55 }
56 public static Node findNodeByXPath(String xPathString, Object source) throws XPathExpressionException {
57 NodeList list = (NodeList)getXPathExpression(xPathString).evaluate(source, XPathConstants.NODESET);
58 int len = list.getLength();
59 return len == 0 ? null : list.item(0);
60 }
61 public static String findStringByXPath(String xPathString, Object source) throws XPathExpressionException {
62 return (String)getXPathExpression(xPathString).evaluate(source, XPathConstants.STRING);
63 }
64 public static XPathExpression getXPathExpression(String xPathString) throws XPathExpressionException {
65 SoftReference<XPathExpression> ref = xPathExpressionsCache.get(xPathString);
66 XPathExpression expression = ref == null ? null : ref.get();
67 if (expression == null)
68 xPathExpressionsCache.put(xPathString, new SoftReference<XPathExpression>(expression = getSharedXPath().compile(xPathString)));
69
70 return expression;
71 }
72
73 }