Example usage for javax.xml.xpath XPath evaluate

List of usage examples for javax.xml.xpath XPath evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPath evaluate.

Prototype

public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate an XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:net.bpelunit.test.util.TestUtil.java

public static Node getNode(Element literalData, NamespaceContextImpl context, String string)
        throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(context);/*w  w  w.j a va  2 s. com*/
    return (Node) xpath.evaluate(string, literalData, XPathConstants.NODE);
}

From source file:com.betfair.testing.utils.cougar.assertions.AssertionUtils.java

private static void doDomSorting(Document doc, XPath xpath, String x)
        throws XPathExpressionException, IOException {
    NodeList parentNodes = (NodeList) xpath.evaluate(x, doc, XPathConstants.NODESET);
    for (int i = 0; i < parentNodes.getLength(); i++) {
        Node n = parentNodes.item(i);
        List<Node> allKids = new ArrayList<>(n.getChildNodes().getLength());
        for (int j = n.getChildNodes().getLength() - 1; j >= 0; j--) {
            allKids.add(n.removeChild(n.getFirstChild()));
        }/* w  ww.  ja  v a  2 s  . com*/
        final Map<Node, String> kidsToString = new HashMap<>();

        for (Node k : allKids) {
            kidsToString.put(k, toString(k));
        }
        Collections.sort(allKids, new Comparator<Node>() {
            @Override
            public int compare(Node o1, Node o2) {
                return kidsToString.get(o1).compareTo(kidsToString.get(o2));
            }
        });
        for (Node k : allKids) {
            n.appendChild(k);
        }
    }
}

From source file:io.wcm.testing.mock.osgi.OsgiMetadataUtil.java

public static Set<String> getServiceInterfaces(Document document) {
    Set<String> serviceInterfaces = new HashSet<>();

    if (document != null) {
        try {//  w  ww . j a  v a2s  . c  om
            XPath xpath = XPATH_FACTORY.newXPath();
            xpath.setNamespaceContext(NAMESPACE_CONTEXT);
            NodeList nodes = (NodeList) xpath.evaluate(
                    "/components/component[1]/service/provide[@interface!='']", document,
                    XPathConstants.NODESET);
            if (nodes != null) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    String serviceInterface = node.getAttributes().getNamedItem("interface").getNodeValue();
                    if (StringUtils.isNotBlank(serviceInterface)) {
                        serviceInterfaces.add(serviceInterface);
                    }
                }
            }
        } catch (XPathExpressionException ex) {
            throw new RuntimeException("Error evaluating XPath.", ex);
        }
    }

    return serviceInterfaces;
}

From source file:io.wcm.testing.mock.osgi.OsgiMetadataUtil.java

public static Map<String, Object> getProperties(Document document) {
    Map<String, Object> props = new HashMap<>();

    if (document != null) {
        try {//from   ww  w.  j a v  a  2 s.  co m
            XPath xpath = XPATH_FACTORY.newXPath();
            xpath.setNamespaceContext(NAMESPACE_CONTEXT);
            NodeList nodes = (NodeList) xpath.evaluate(
                    "/components/component[1]/property[@name!='' and @value!='']", document,
                    XPathConstants.NODESET);
            if (nodes != null) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    String name = node.getAttributes().getNamedItem("name").getNodeValue();
                    String value = node.getAttributes().getNamedItem("value").getNodeValue();
                    String type = null;
                    Node typeAttribute = node.getAttributes().getNamedItem("type");
                    if (typeAttribute != null) {
                        type = typeAttribute.getNodeValue();
                    }
                    if (StringUtils.equals("Integer", type)) {
                        props.put(name, Integer.parseInt(value));
                    } else {
                        props.put(name, value);
                    }
                }
            }
        } catch (XPathExpressionException ex) {
            throw new RuntimeException("Error evaluating XPath.", ex);
        }
    }

    return props;
}

From source file:com.twentyn.patentExtractor.PatentDocumentFeatures.java

private static Map<String, Integer> extractMoleculeCounts(Map<String, Integer> moleculeCounts, Document doc)
        throws ParserConfigurationException, XPathExpressionException {
    if (doc != null) {
        /* This uses //MOLECULE instead of //MOLECULE//text(), as the latter finds all text for all molecules
         * instead of text for each molecule.  We could also do a secondary traversal of each MOLECULE fragment,
         * but running XPath queries over XPath results is a major pain.  Instead, we'll grab the MOLECULE nodes
         * and recursively extract the text content one molecule at a time. */
        XPath xpath = Util.getXPathFactory().newXPath();
        NodeList nodes = (NodeList) xpath.evaluate(MOLECULE_PATH, doc, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            List<String> nameList = appendTextContent(new LinkedList<String>(), nodes.item(i));
            String moleculeName = StringUtils.join(nameList, " ");
            Integer count = moleculeCounts.get(moleculeName);
            if (count == null) {
                count = 0;/*from ww w  .ja v  a  2 s  .  c om*/
            }
            moleculeCounts.put(moleculeName, count + 1);
        }
    }
    return moleculeCounts;
}

From source file:Main.java

/**
 * getStringListFromXPath//from w  w w  . j  a  va 2  s  .co  m
 * Gets a list of strings from an xml.
 * @param rootNode The root node to perform the listExpression on. 
 * @param listExpression Evaluated on the rootNode, gets a NodeList.
 * @return A list of the text contents of the nodes returned by evaluating the listExpression.
 */
public static List<String> getStringListFromXPath(Node rootNode, XPath xpath, String listExpression) {
    synchronized (xpath) {
        if (rootNode instanceof Document)
            rootNode = ((Document) rootNode).getDocumentElement();
        Vector<String> result = new Vector<String>();
        try {
            NodeList nodes = (NodeList) xpath.evaluate(listExpression, rootNode, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++) {
                result.addElement(nodes.item(i).getTextContent());
            }
        } catch (Exception e) {
            System.err.println("Error evaluating xpath expression: " + listExpression);
            e.printStackTrace();
        }
        return result;
    }
}

From source file:com.twentyn.patentExtractor.Util.java

public static DocumentType identifyDocType(Document dom) throws XPathExpressionException {
    XPath xpath = null;
    xpath = getXPathFactory().newXPath();
    for (Map.Entry<String, DocumentType> entry : NODE_NAME_TO_DOC_TYPE.entrySet()) {
        Node top = (Node) xpath.evaluate("/" + entry.getKey(), dom, XPathConstants.NODE);
        if (top != null) {
            return entry.getValue();
        }/*from  ww w. ja  v  a2  s  .  c o m*/
    }
    return DocumentType.UNKNOWN;
}

From source file:Main.java

public static Object parseRequestObjectFromSoap(String soapXml) throws Exception {
    Object result = null;/*  w  w  w. j a v  a  2 s.com*/

    if (soapXml != null && soapXml.trim().length() > 0) {
        DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
        xmlFact.setNamespaceAware(true);

        DocumentBuilder builder = xmlFact.newDocumentBuilder();
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        StringReader xsr = new StringReader(soapXml);
        InputSource is = new InputSource(xsr);
        Document doc = builder.parse(is);

        //Node requestNode = (Node) xpath.evaluate("/soap:Envelope/soap:Body/*", doc, XPathConstants.NODE);
        Node requestNode = (Node) xpath.evaluate("/*[local-name()='Envelope']/*[local-name()='Body']/*", doc,
                XPathConstants.NODE);

        JAXBContext ctx = JAXBContext.newInstance("xo.xoi.orderentry.ebonding");
        Unmarshaller unmarshaller = ctx.createUnmarshaller();
        result = unmarshaller.unmarshal(requestNode);
    }

    return result;
}

From source file:apiconnector.TestDataFunctionality.java

public static String toPrettyString(String xml, int indent) throws Exception {
    // 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);
    }//from   w ww .  j a  va  2 s.  c om

    // 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, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Return pretty print xml string
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
    return stringWriter.toString();
}

From source file:com.streak.logging.utils.AnalysisUtility.java

public static void fetchCloudStorageUris(String bucketName, String startKey, String endKey,
        HttpRequestFactory requestFactory, List<String> urisToProcess, boolean readSchemas) throws IOException {
    String bucketUri = "http://commondatastorage.googleapis.com/" + bucketName;
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(bucketUri + "?marker=" + startKey));
    HttpResponse response = request.execute();

    try {//  w w w  .ja v a 2  s  . c o  m
        Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getContent());
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xPath.evaluate("//Contents/Key/text()", responseDoc,
                XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            String key = nodes.item(i).getNodeValue();
            if (key.compareTo(endKey) >= 0) {
                break;
            }
            if (key.endsWith(".schema") ^ readSchemas) {
                continue;
            }
            if (readSchemas) {
                key = key.substring(0, key.length() - ".schema".length());
            }
            urisToProcess.add("gs://" + bucketName + "/" + key);
        }
    } catch (SAXException e) {
        throw new IOException("Error parsing cloud storage response", e);
    } catch (ParserConfigurationException e) {
        throw new IOException("Error configuring cloud storage parser", e);
    } catch (XPathExpressionException e) {
        throw new IOException("Error finding keys", e);
    }
}