Created
May 10, 2011 14:47
-
-
Save jankronquist/964612 to your computer and use it in GitHub Desktop.
Simple, thread-safe xpath with namespace support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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