2007-12-23 19:28:04 +00:00
|
|
|
|
|
|
|
package net.sourceforge.tuned;
|
|
|
|
|
|
|
|
|
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.List;
|
|
|
|
|
|
|
|
import javax.xml.xpath.XPath;
|
|
|
|
import javax.xml.xpath.XPathConstants;
|
2008-03-02 17:02:37 +00:00
|
|
|
import javax.xml.xpath.XPathExpression;
|
|
|
|
import javax.xml.xpath.XPathExpressionException;
|
2007-12-23 19:28:04 +00:00
|
|
|
import javax.xml.xpath.XPathFactory;
|
|
|
|
|
|
|
|
import org.w3c.dom.Node;
|
|
|
|
import org.w3c.dom.NodeList;
|
|
|
|
|
|
|
|
|
|
|
|
public class XPathUtil {
|
|
|
|
|
2008-02-07 22:05:59 +00:00
|
|
|
public static Node selectNode(String xpath, Object node) {
|
2007-12-23 19:28:04 +00:00
|
|
|
try {
|
2008-03-02 17:02:37 +00:00
|
|
|
return (Node) getXPath(xpath).evaluate(node, XPathConstants.NODE);
|
2007-12-23 19:28:04 +00:00
|
|
|
} catch (Exception e) {
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2008-02-09 17:53:08 +00:00
|
|
|
public static Node selectFirstNode(String xpath, Object node) {
|
2008-03-02 17:02:37 +00:00
|
|
|
try {
|
|
|
|
NodeList nodeList = (NodeList) getXPath(xpath).evaluate(node, XPathConstants.NODESET);
|
|
|
|
|
|
|
|
if (nodeList.getLength() <= 0)
|
|
|
|
return null;
|
|
|
|
|
|
|
|
return nodeList.item(0);
|
|
|
|
} catch (Exception e) {
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
2008-02-09 17:53:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2008-02-07 22:05:59 +00:00
|
|
|
public static List<Node> selectNodes(String xpath, Object node) {
|
2007-12-23 19:28:04 +00:00
|
|
|
try {
|
2008-03-02 17:02:37 +00:00
|
|
|
NodeList nodeList = (NodeList) getXPath(xpath).evaluate(node, XPathConstants.NODESET);
|
2007-12-23 19:28:04 +00:00
|
|
|
|
|
|
|
ArrayList<Node> nodes = new ArrayList<Node>(nodeList.getLength());
|
|
|
|
|
|
|
|
for (int i = 0; i < nodeList.getLength(); i++) {
|
|
|
|
nodes.add(nodeList.item(i));
|
|
|
|
}
|
|
|
|
|
|
|
|
return nodes;
|
|
|
|
} catch (Exception e) {
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2008-02-07 22:05:59 +00:00
|
|
|
public static String selectString(String xpath, Object node) {
|
2007-12-23 19:28:04 +00:00
|
|
|
try {
|
2008-03-02 17:02:37 +00:00
|
|
|
return ((String) getXPath(xpath).evaluate(node, XPathConstants.STRING)).trim();
|
2007-12-23 19:28:04 +00:00
|
|
|
} catch (Exception e) {
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2008-03-02 17:02:37 +00:00
|
|
|
private static XPath xpathObject = XPathFactory.newInstance().newXPath();
|
|
|
|
|
|
|
|
|
|
|
|
private static synchronized XPathExpression getXPath(String xpath) throws XPathExpressionException {
|
|
|
|
return xpathObject.compile(xpath);
|
|
|
|
}
|
2007-12-23 19:28:04 +00:00
|
|
|
}
|