Skip to content

Instantly share code, notes, and snippets.

@jankronquist
Created May 10, 2011 14:47
Show Gist options
  • Select an option

  • Save jankronquist/964612 to your computer and use it in GitHub Desktop.

Select an option

Save jankronquist/964612 to your computer and use it in GitHub Desktop.

Revisions

  1. jankronquist created this gist May 10, 2011.
    44 changes: 44 additions & 0 deletions SimpleXPath.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    /**
    * 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;
    }
    }