List of usage examples for javax.xml.xpath XPathExpression XPathExpression
XPathExpression
From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java
XPathExpression conjoinXPaths(Document fragment, String base) throws Exception { String path = "//*"; final Element e = fragment.getDocumentElement(); if (e == null) return null; final XPathIterator conjunction = new XPathIterator(e, base); if (conjunction.hasNext()) { path += "["; boolean first = true; while (conjunction.hasNext()) { if (!first) path += " and "; XPathExpression x = conjunction.next(); String exp = x.toString(); boolean positive = true; if (exp.startsWith("-")) { positive = false;//from w w w.j av a2 s. c o m exp = exp.substring(1); } // remove the initial '/' exp = exp.substring(1); if (positive) path += exp; else path += "not(" + exp + ")"; first = false; } path += "]"; } XPath xpath = xPathFactory.newXPath(); // add namespace prefix resolver to the xpath based on the current element xpath.setNamespaceContext(new AbstractNamespaceContext() { public String getNamespaceURI(String prefix) { // for the empty prefix lookup the default namespace if (prefix.isEmpty()) return e.lookupNamespaceURI(null); for (int i = 0; i < conjunction.contexts.size(); i++) { NamespaceContext c = conjunction.contexts.get(i); String ns = c.getNamespaceURI(prefix); if (ns != null) return ns; } return null; } }); final String exp = path; final XPathExpression compiled = xpath.compile(path); if (verbose) System.out.println(exp); return new XPathExpression() { public String evaluate(Object source) throws XPathExpressionException { return compiled.evaluate(source); } public String evaluate(InputSource source) throws XPathExpressionException { return compiled.evaluate(source); } public Object evaluate(Object source, QName returnType) throws XPathExpressionException { return compiled.evaluate(source, returnType); } public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException { return compiled.evaluate(source, returnType); } public String toString() { return exp; } }; }