Skip to content

Instantly share code, notes, and snippets.

@jankronquist
Created May 10, 2011 14:47
Show Gist options
  • Save jankronquist/964612 to your computer and use it in GitHub Desktop.
Save jankronquist/964612 to your computer and use it in GitHub Desktop.
Simple, thread-safe xpath with namespace support
/**
* Thread-safe xpath with namespace support.
*/
public class SimpleXPath {
private final String expression;
public SimpleXPath(String expression) {
this.expression = expression;
}
public String evaluate(String xml) {
return this.evaluate(new InputSource(new StringReader(xml)));
}
public String evaluate(InputSource source) {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(MyNamespaceContext.getInstance());
try {
XPathExpression expr = xpath.compile(expression);
return expr.evaluate(source);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
}
class MyNamespaceContext {
private static SimpleNamespaceContext instance;
static {
instance = new SimpleNamespaceContext();
instance.addNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
// TODO: add your namespaces here
}
private MyNamespaceContext() {
}
public static NamespaceContext getInstance() {
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment