List of usage examples for javax.xml.xpath XPathFactory newInstance
public static XPathFactory newInstance()
Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.
This method is functionally equivalent to:
newInstance(DEFAULT_OBJECT_MODEL_URI)
Since the implementation for the W3C DOM is always available, this method will never fail.
From source file:Main.java
/** * Creates an XPATH instance for querying with * //from w w w . j av a 2 s.c om * @return an XPATH instance */ public static XPath createXPath() { return XPathFactory.newInstance().newXPath(); }
From source file:Main.java
public static String toPrettyString(String xml) { int indent = 4; try {/* www . j a v a 2 s. c om*/ // Turn xml string into a document Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); // Remove whitespaces outside tags XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } // Setup pretty print options TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // Return pretty print xml string StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); } catch (Exception e) { System.out.println(xml); throw new RuntimeException( "Problems prettyfing xml content [" + Splitter.fixedLength(100).split(xml) + "]", e); } }
From source file:Main.java
private static XPath createXPath(NamespaceContext namespaceContext, XPathFunctionResolver functionResolver) { XPath xPath = XPathFactory.newInstance().newXPath(); if (namespaceContext != null) { xPath.setNamespaceContext(namespaceContext); }//from www. j a v a 2 s . c om if (functionResolver != null) { xPath.setXPathFunctionResolver(functionResolver); } return xPath; }
From source file:Main.java
/** * Counts the elements which results from the xpath expression. * /*from w w w. jav a 2s .c o m*/ * @param document the xml document. * @param xpath the expression * @param message The assert message. * @return Returns -1 if no element was found. */ public static int count(String message, Document document, String xpath) throws XPathExpressionException { XPathExpression expression = EXPRESSIONS.get(xpath); NodeList list = null; if (expression == null) { expression = XPathFactory.newInstance().newXPath().compile(xpath); EXPRESSIONS.put(xpath, expression); } if ((list = (NodeList) expression.evaluate(document.getDocumentElement(), XPathConstants.NODESET)) != null) { return list.getLength(); } return -1; }
From source file:Main.java
/** Evaluates an XPath. */ private static synchronized Object evalXPath(String expression, Object item, QName type) { if (xPath == null) xPath = XPathFactory.newInstance().newXPath(); try {/*from ww w .ja v a2 s.co m*/ XPathExpression exp = xPath.compile(expression); Object node = exp.evaluate(item, XPathConstants.NODE); return (node == null) ? null : exp.evaluate(item, type); } catch (XPathExpressionException e) { throw new AssertionError("Error initializing XPath instance for '" + expression + "': " + e); } }
From source file:Main.java
/** * Performs a xpath query on a document and returns the matching nodelist. * * @param context the Context where to start with the query * @param query the XPath-Query//from w ww. ja v a 2s. co m * @return nodelist of matches * @throws Exception on error */ public static NodeList query(Node context, String query) throws Exception { NodeList result = null; XPath xpath = XPathFactory.newInstance().newXPath(); try { result = (NodeList) xpath.evaluate(query, context, XPathConstants.NODESET); } catch (XPathExpressionException xpx) { throw new Exception("Error evaluating XPath: " + xpx.getMessage(), xpx); } return result; }
From source file:Main.java
/** * Extract the parameters specified in the XML document for the Element * specified by parent./* ww w . j ava 2 s .c o m*/ * * @param parent * - Parent Node. * @return * @throws Exception */ public static HashMap<String, Object> parseParams(Element parent) throws Exception { XPath xpath = XPathFactory.newInstance().newXPath(); // XPath Query for showing all nodes value XPathExpression expr = xpath.compile(_PARAM_NODE_PARAMS_); NodeList nodes = (NodeList) expr.evaluate(parent, XPathConstants.NODESET); if (nodes != null && nodes.getLength() > 0) { HashMap<String, Object> params = new HashMap<String, Object>(); for (int ii = 0; ii < nodes.getLength(); ii++) { Element elm = (Element) nodes.item(ii); String name = elm.getAttribute(_PARAM_ATTR_NAME_); String value = elm.getAttribute(_PARAM_ATTR_VALUE_); if (name != null && !name.isEmpty()) { params.put(name, value); } } return params; } return null; }
From source file:Main.java
public static Object executeXPath(Document dom, String xpath, QName returnType) throws XPathExpressionException { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xpath); return expr.evaluate(dom, returnType); }
From source file:Main.java
public static synchronized String evaluate(String path, Node node) throws RuntimeException { path = path.trim();/*from www .jav a 2 s. c o m*/ try { XPath xp = XPathFactory.newInstance().newXPath(); XPathExpression expr = xp.compile(path); String ret = expr.evaluate(node); return ret; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.github.born2snipe.project.setup.cli.maven.AssertXml.java
public static void assertTextAt(String expectedText, File file, String xpathQuery) { try {/*w w w . java 2 s . com*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); String text = xPath.compile(xpathQuery).evaluate(doc); assertEquals("Text @ " + xpathQuery, expectedText, text); } catch (Exception e) { throw new RuntimeException(e); } }