Example usage for javax.xml.xpath XPathExpression evaluate

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:com.laex.j2objc.AntDelegate.java

/**
 * Append exclude pattern to xml.// w  ww. j  a va  2 s.c  o m
 * 
 * @param path
 *            the path
 * @param pats
 *            the pats
 * @throws ParserConfigurationException
 *             the parser configuration exception
 * @throws SAXException
 *             the SAX exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws XPathExpressionException
 *             the x path expression exception
 * @throws CoreException
 *             the core exception
 * @throws TransformerException
 *             the transformer exception
 */
private void appendExcludePatternToXML(IFile path, String[] pats) throws ParserConfigurationException,
        SAXException, IOException, XPathExpressionException, CoreException, TransformerException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(path.getContents());

    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr = xpath.compile("project/target/move/fileset");

    Node node = (Node) expr.evaluate(dom, XPathConstants.NODE);
    NodeList children = node.getChildNodes();

    // don't why the last node in the xml should be indexed by length - 2
    Node excludeCopy = children.item(children.getLength() - 2).cloneNode(true);
    for (String pattern : pats) {
        if (StringUtils.isNotEmpty(pattern.trim())) {
            Node newnode = excludeCopy.cloneNode(true);
            newnode.getAttributes().getNamedItem("name").setNodeValue(pattern);
            node.appendChild(newnode);
        }
    }

    // Setup transformers
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(dom), new StreamResult(sw));
    String output = sw.getBuffer().toString();

    // save the ouput
    ByteArrayInputStream bis = new ByteArrayInputStream(output.getBytes("utf-8"));
    path.setContents(bis, 0, null);
}

From source file:net.solarnetwork.support.XmlSupport.java

/**
 * Extract a String value via an XPath expression.
 * //ww  w  .j a va  2s  . c om
 * @param xml
 *        the XML
 * @param xpath
 *        the XPath expression
 * @return the String
 */
public String extractStringFromXml(Node xml, XPathExpression xpath) {
    try {
        return (String) xpath.evaluate(xml, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Unable to extract string from XPath [" + xpath.toString() + "]", e);
    }
}

From source file:com.seajas.search.contender.service.exploration.ExplorationService.java

/**
 * Make an attempt to retrieve all feed links from the given HTML content.
 * /* w  ww  .j ava  2s  . com*/
 * @param htmlContent
 * @return List<String>
 */
public List<String> getIndirectlyAccessibleFeedLinks(final URI uri, final String htmlContent) {
    List<String> result = new ArrayList<String>();

    try {
        HtmlCleaner cleaner = new HtmlCleaner();

        TagNode node = cleaner.clean(htmlContent);

        Document document = new CustomDomSerializer(cleaner.getProperties(), true).createDOM(node);

        // Now try to extract the appropriate links

        XPath xpath = XPathFactory.newInstance().newXPath();

        try {
            XPathExpression xpathExpression = xpath.compile(
                    "//head/link[contains(translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'rss+xml') or contains(translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'atom+xml')]/@href");

            NodeList nodeList = (NodeList) xpathExpression.evaluate(document, XPathConstants.NODESET);

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node listNode = nodeList.item(i);

                if (listNode instanceof Attr) {
                    String resultUrl = ((Attr) listNode).getValue();

                    if (!StringUtils.hasText(resultUrl)) {
                        logger.warn("The given alternate-link tag contains no href - skipping");

                        continue;
                    }

                    try {
                        new URL(resultUrl.trim());

                        result.add(resultUrl.trim());
                    } catch (MalformedURLException e) {
                        try {
                            result.add(uri.resolve(resultUrl.trim()).normalize().toString());
                        } catch (IllegalArgumentException e2) {
                            logger.warn(
                                    "The given (presumably relative) URL is not valid - not adding to the result list",
                                    e2);
                        }
                    }
                } else
                    logger.error("Invalid node type " + listNode.getNodeType() + " - skipping");
            }
        } catch (XPathExpressionException e) {
            logger.error("Could not apply the given XPath expression to extract RSS alternate links", e);
        }

        // Now determine if the URLs are fully-qualified

    } catch (ParserConfigurationException e) {
        logger.info("Could not serialize the given content", e);

        return null;
    }

    return result;
}

From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java

boolean isViewable(Document doc) throws Exception {
    XPath xpath = xPathFactory.newXPath();
    // there are no namespaces in this xpath so a prefix resolver is not required
    String exp = "//*[@about='?this']";
    XPathExpression compiled = xpath.compile(exp);
    Object result = compiled.evaluate(doc, XPathConstants.NODE);
    return result != null;
}

From source file:android.databinding.tool.store.LayoutFileParser.java

private List<Node> get(Document doc, XPath xPath, String pattern) throws XPathExpressionException {
    final XPathExpression expr = xPath.compile(pattern);
    return toList((NodeList) expr.evaluate(doc, XPathConstants.NODESET));
}

From source file:ch.dbs.actions.bestellung.EZBJOP.java

/**
 * This class uses the official EZB/ZDB API from
 * http://services.dnb.de/fize-service/gvr/full.xml.
 */// w w  w  .  j  a va2 s  .  co  m
public EZBForm read(final String content) {

    final EZBForm ezbform = new EZBForm();

    try {

        if (content != null) {

            final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            final DocumentBuilder builder = domFactory.newDocumentBuilder();
            final Document doc = builder.parse(new InputSource(new StringReader(content)));

            final XPathFactory factory = XPathFactory.newInstance();
            final XPath xpath = factory.newXPath();

            // references electronic data
            //            final XPathExpression exprRefE = xpath.compile("//ElectronicData/References/Reference");
            //            final NodeList resultListRefE = (NodeList) exprRefE.evaluate(doc, XPathConstants.NODESET);
            //
            //            for (int i = 0; i < resultListRefE.getLength(); i++) {
            //                final Node firstResultNode = resultListRefE.item(i);
            //                final Element result = (Element) firstResultNode;
            //
            //                final EZBReference ref = new EZBReference();
            //
            //                // EZB URLs
            //                final String url = getValue(result.getElementsByTagName("URL"));
            //                ref.setUrl(url);
            //
            //                // Label for URLs
            //                final String label = getValue(result.getElementsByTagName("Label"));
            //                ref.setLabel(label);
            //
            //                ezbform.getReferencesonline().add(ref);
            //            }

            // electronic data
            final XPathExpression exprE = xpath.compile("//ElectronicData/ResultList/Result");
            final NodeList resultListE = (NodeList) exprE.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListE.getLength(); i++) {
                final Node firstResultNode = resultListE.item(i);
                final Element result = (Element) firstResultNode;

                final EZBDataOnline online = new EZBDataOnline();

                // state
                online.setState(Integer.valueOf(result.getAttribute("state")));
                // 0 free accessible
                if (online.getState() == JOPState.FREE.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.free");
                    // 1 partially free accesible
                } else if (online.getState() == JOPState.FREE_PARTIALLY.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.partially_free");
                    // 2 licensed ; 3 partially licensed
                } else if (online.getState() == JOPState.LICENSED.getValue()
                        || online.getState() == JOPState.LICENSED_PARTIALLY.getValue()) {
                    online.setAmpel("yellow");
                    online.setComment("availresult.abonniert");
                    // journal not online for periode
                } else if (online.getState() == JOPState.OUTSIDE_PERIOD.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.timeperiode");
                    // not indexed
                } else if (online.getState() == JOPState.NO_HITS.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.nohits");
                } else {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                }

                // title
                String title = getValue(result.getElementsByTagName("Title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    online.setTitle(Jsoup.parse(title).text());
                }

                online.setUrl(getValue(result.getElementsByTagName("AccessURL")));
                online.setLevel(getValue(result.getElementsByTagName("AccessLevel")));
                online.setReadme(getValue(result.getElementsByTagName("ReadmeURL")));
                // National licenses etc.
                online.setAdditional(getValue(result.getElementsByTagName("Additional")));

                ezbform.getOnline().add(online);
            }

            // Title not found
            if (resultListE.getLength() == 0) {
                final EZBDataOnline online = new EZBDataOnline();
                online.setAmpel("red");
                online.setComment("availresult.nohits");
                online.setState(JOPState.NO_HITS.getValue());

                ezbform.getOnline().add(online);
            }

            // references print data
            final XPathExpression exprRefP = xpath.compile("//PrintData/References/Reference");
            final NodeList resultListRefP = (NodeList) exprRefP.evaluate(doc, XPathConstants.NODESET);

            final EZBReference ref = new EZBReference();

            for (int i = 0; i < resultListRefP.getLength(); i++) {
                final Node firstResultNode = resultListRefP.item(i);
                final Element result = (Element) firstResultNode;

                // EZB URLs
                ref.setUrl(getValue(result.getElementsByTagName("URL")));

                // Label for URLs
                //                final String label = getValue(result.getElementsByTagName("Label"));
                ref.setLabel("availresult.link_title_print");

                ezbform.getReferencesprint().add(ref);
            }

            // print data
            final XPathExpression exprP = xpath.compile("//PrintData/ResultList/Result");
            final NodeList resultListP = (NodeList) exprP.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListP.getLength(); i++) {
                final Node firstResultNode = resultListP.item(i);
                final Element result = (Element) firstResultNode;

                final EZBDataPrint print = new EZBDataPrint();

                // state
                print.setState(Integer.valueOf(result.getAttribute("state")));

                // title
                String title = getValue(result.getElementsByTagName("Title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    print.setTitle(Jsoup.parse(title).text());
                }

                print.setLocation(getValue(result.getElementsByTagName("Location")));
                print.setCallnr(getValue(result.getElementsByTagName("Signature")));
                print.setCoverage(getValue(result.getElementsByTagName("Period")));

                // set previous extracted URL and label
                print.setInfo(ref);

                // in stock ; partially in stock
                if (print.getState() == JOPState.LICENSED.getValue()
                        || print.getState() == JOPState.LICENSED_PARTIALLY.getValue()) {
                    print.setAmpel("yellow");
                    print.setComment("availresult.print");
                    // only return if existing in Print
                    ezbform.getPrint().add(print);
                }
            }
        }

    } catch (final XPathExpressionException e) {
        LOG.error(e.toString());
    } catch (final SAXParseException e) {
        LOG.error(e.toString());
    } catch (final SAXException e) {
        LOG.error(e.toString());
    } catch (final IOException e) {
        LOG.error(e.toString());
    } catch (final ParserConfigurationException e) {
        LOG.error(e.toString());
    } catch (final Exception e) {
        LOG.error(e.toString());
    }

    return ezbform;
}

From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java

XPathExpression evaluateXPaths(XPathIterator iterator, Document doc) throws Exception {
    while (iterator.hasNext()) {
        XPathExpression exp = iterator.next();
        NodeList result = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
        boolean negativeTest = exp.toString().startsWith("-");
        int solutions = result.getLength();
        // a positive test should return exactly one solution
        boolean failure = ((solutions < 1 && !negativeTest)
                // a negative test should return no solutions
                || (solutions > 0 && negativeTest));
        if (failure)
            return exp; // fail
    }/*from  w  w w .  ja  va  2 s.  c  o m*/
    return null;
}

From source file:com.vimeo.VimeoUploadClient.java

/**
 * parse xml response/* ww w  .j av a2 s.c  o m*/
 * 
 * @param content
 * @param path
 * @param returnType
 * @return
 */
private Object path(String content, String path, QName returnType) {
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(content)));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile(path);
        return expr.evaluate(doc, returnType);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.mnxfst.testing.server.cfg.PTestServerConfigurationParser.java

/**
 * Evaluates the given expression on the referenced document into a result object of type string
 * @param expression//  w w w .  j a  va  2 s  . c o  m
 * @param document
 * @return
 * @throws XPathExpressionException
 */
protected String evaluateString(XPathExpression expression, Object document) throws XPathExpressionException {
    if (expression == null)
        throw new XPathExpressionException("Null is not a valid expression");
    if (document == null)
        throw new XPathExpressionException("An xpath expression must not be applied to a NULL document");

    return (String) expression.evaluate(document, XPathConstants.STRING);
}