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
public static Iterable<Node> eval(Node element, String path) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // xpath.setNamespaceContext(new NamespaceContext() { ////from w w w .ja va 2 s .c o m // /** // * @WARNING this code will work only if the namespace is present at // * each node of the xml dom and within the xpath queries. // * Otherwise you can fix like that: // * // * <pre> // * // FIXME: this is a // * hack!! if ("atom".equals(prefix)) return // * "http://www.w3.org/2005/Atom"; but it wont work with // * </pre> // * // * different namespaces // * @see // javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String) // */ // public String getNamespaceURI(String prefix) { // String namespace = DOMUtil.lookupNamespaceURI(node, prefix); // return namespace; // } // // public String getPrefix(String namespaceURI) { // String prefix = node.lookupPrefix(namespaceURI); // return prefix; // } // // public Iterator<?> getPrefixes(final String namespaceURI) { // return new Iterator<String>() { // String ns = getPrefix(namespaceURI); // // public boolean hasNext() { // return ns != null; // } // // public String next() { // String r = ns; // ns = null; // return r; // } // // public void remove() { // } // // }; // } // }); XPathExpression expr = xpath.compile(path); final NodeList result = (NodeList) expr.evaluate(element, XPathConstants.NODESET); return new Iterable<Node>() { public Iterator<Node> iterator() { return new Iterator<Node>() { int len = result.getLength(); int pos; public boolean hasNext() { return pos < len; } public Node next() { if (pos >= len) { return null; } return result.item(pos++); } public void remove() { throw new IllegalAccessError(); } }; } }; }
From source file:Main.java
public static final String[] executeXPathExpression(InputSource inputSource, String xpathExpression, String namespace) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException, TransformerException { // optional namespace spec: xmlns:prefix:URI String nsPrefix = null;//from w ww.j av a2s. c o m String nsUri = null; if (namespace != null && namespace.startsWith("xmlns:")) { String[] nsDef = namespace.substring("xmlns:".length()).split("="); if (nsDef.length == 2) { nsPrefix = nsDef[0]; nsUri = nsDef[1]; } } // Parse XML to DOM DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); Document doc = dbFactory.newDocumentBuilder().parse(inputSource); // Find nodes by XPATH XPathFactory xpFactory = XPathFactory.newInstance(); XPath xpath = xpFactory.newXPath(); // namespace? if (nsPrefix != null) { final String myPrefix = nsPrefix; final String myUri = nsUri; xpath.setNamespaceContext(new NamespaceContext() { public String getNamespaceURI(String prefix) { return myPrefix.equals(prefix) ? myUri : null; } public String getPrefix(String namespaceURI) { return null; // we are not using this. } public Iterator<?> getPrefixes(String namespaceURI) { return null; // we are not using this. } }); } XPathExpression expr = xpath.compile(xpathExpression); NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); List<String> lines = new ArrayList<>(); for (int i = 0; i < nodes.getLength(); i++) { lines.add((indenting(nodes.item(i)))); } return lines.toArray(new String[lines.size()]); }
From source file:Main.java
public static String findInXml(String xml, String xpath) { try {/*from ww w.j av a2s . co m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // if (systemId.contains("foo.dtd")) { return new InputSource(new StringReader("")); // } else { // return null; // } } }); Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); XPathFactory xPathfactory = XPathFactory.newInstance(); XPathExpression expr = xPathfactory.newXPath().compile(xpath); return (String) expr.evaluate(doc, XPathConstants.STRING); } catch (Throwable t) { throw new RuntimeException(t); } }
From source file:Main.java
/** * Returns the string value of the named attribute in an XML file at the coordinates specified by the passed XPath expression * @param fileName The file name//from ww w . j ava 2s. c om * @param xPathExpression The XPath expression * @param attributeName The attribute name * @return the attribute valye */ public static String getAttribute(String fileName, String xPathExpression, String attributeName) { try { Document document = parseXML(new File(fileName)); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression xpathExpression = xpath.compile(xPathExpression); Node node = (Node) xpathExpression.evaluate(document, NODE); return getAttributeValueByName(node, attributeName); } catch (Exception e) { throw new RuntimeException("Failed to extract element from:" + fileName, e); } }
From source file:com.thinkbiganalytics.feedmgr.nifi.NifiTemplateParser.java
/** * @param nifiTemplate the nifi template xml string * @return the name of the template/*from ww w . j a va 2 s . c o m*/ */ public static String getTemplateName(String nifiTemplate) throws ParserConfigurationException, XPathExpressionException, IOException, SAXException { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); InputSource source = new InputSource(new StringReader(nifiTemplate)); String name = (String) xpath.evaluate("/template/name", source, XPathConstants.STRING); return name; }
From source file:com.github.born2snipe.project.setup.cli.maven.AssertXml.java
public static void assertElementDoesExist(String expectedText, File file, String xpathQuery) { try {/*from w w w. jav a2 s. c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.compile(xpathQuery).evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { String text = nodes.item(i).getTextContent(); if (text.equals(expectedText)) { Assert.fail("We expected to NOT find " + expectedText); } } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:Main.java
private static Node getNodeObject(String xpathString, Document doc) throws XPathExpressionException { // Create a xptah object //logger.debug("Getting the node by using xpath " + xpathString); XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); XPathExpression expr = xpath.compile(xpathString); Node node = (Node) expr.evaluate(doc, XPathConstants.NODE); //logger.debug("Returning the Node object from xml file"); return node;/* w w w.j a v a2s.c o m*/ }
From source file:uk.ac.ebi.intact.dataexchange.psimi.solr.util.IntactSolrUtils.java
public static SchemaInfo retrieveSchemaInfo(SolrServer solrServer) throws IOException { SchemaInfo schemaInfo = new SchemaInfo(); if (solrServer instanceof CommonsHttpSolrServer) { final CommonsHttpSolrServer solr = (CommonsHttpSolrServer) solrServer; final String url = solr.getBaseURL() + "/admin/file/?file=schema.xml"; final GetMethod method = new GetMethod(url); final int code = solr.getHttpClient().executeMethod(method); XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/schema/fields/field"; InputStream stream = method.getResponseBodyAsStream(); InputSource inputSource = new InputSource(stream); try {/* w w w . j a va2 s. c o m*/ NodeList nodes = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { final String fieldName = nodes.item(i).getAttributes().getNamedItem("name").getNodeValue(); schemaInfo.addFieldName(fieldName); } } catch (XPathExpressionException e) { e.printStackTrace(); } finally { stream.close(); } } else if (solrServer instanceof HttpSolrServer) { final HttpSolrServer solr = (HttpSolrServer) solrServer; final String url = solr.getBaseURL() + "/admin/file/?file=schema.xml"; final HttpUriRequest method = new HttpGet(url); final HttpResponse response = solr.getHttpClient().execute(method); XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/schema/fields/field"; InputStream stream = response.getEntity().getContent(); InputSource inputSource = new InputSource(stream); try { NodeList nodes = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { final String fieldName = nodes.item(i).getAttributes().getNamedItem("name").getNodeValue(); schemaInfo.addFieldName(fieldName); } } catch (XPathExpressionException e) { e.printStackTrace(); } finally { stream.close(); } } else { throw new IllegalArgumentException( "Cannot get schema for SolrServer with class: " + solrServer.getClass().getName()); } return schemaInfo; }
From source file:Main.java
static public XPath getXPath() { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); return xpath; }
From source file:Main.java
public static Object getXMLValue(String xml, String xQuery, QName resultType) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(xml))); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xPath = xPathfactory.newXPath(); XPathExpression xPathExpression = xPath.compile(xQuery); return xPathExpression.evaluate(doc, resultType); }