Example usage for javax.xml.xpath XPathConstants NODESET

List of usage examples for javax.xml.xpath XPathConstants NODESET

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODESET.

Prototype

QName NODESET

To view the source code for javax.xml.xpath XPathConstants NODESET.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:Main.java

/** Evaluates an XPath returning null if not found. <br>
 *  <br>//from w w  w  .j a  va2 s.c  o  m
 *  This is intended for use with pre-defined XPaths stored as constants,
 *  where runtime exceptions should not be possible.
 *  @param expression The XPath expression to evaluate.
 *  @param item       The {@link Node} or other item to evaluate the XPath on.
 *  @param type       The type to return, this must be one of the following:
 *                    {@link String}, {@link CharSequence}, {@link Boolean},
 *                    {@link Node}, {@link NodeList}, {@link Double}, or
 *                    {@link Number}.
 *  @throws AssertionError If the nested call to <tt>XPath.newInstance(path)</tt>
 *                         throws an {@link XPathExpressionException}.
 */
public static <T> T evalXPath(String expression, Object item, Class<T> type) {
    Object val;

    if (type == String.class)
        val = evalXPath(expression, item, XPathConstants.STRING);
    else if (type == CharSequence.class)
        val = evalXPath(expression, item, XPathConstants.STRING);
    else if (type == Boolean.class)
        val = evalXPath(expression, item, XPathConstants.BOOLEAN);
    else if (type == Boolean.TYPE)
        val = evalXPath(expression, item, XPathConstants.BOOLEAN);
    else if (type == Node.class)
        val = evalXPath(expression, item, XPathConstants.NODE);
    else if (type == NodeList.class)
        val = evalXPath(expression, item, XPathConstants.NODESET);
    else if (type == Double.class)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else if (type == Double.TYPE)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else if (type == Number.class)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else
        throw new IllegalArgumentException("Invalid type given " + type);

    return type.cast(val);
}

From source file:com.rackspace.api.clients.veracode.responses.AppListResponse.java

private Map<String, String> buildAppMap() {
    Map<String, String> applications = new HashMap<String, String>();

    NodeList applicationNodes = null;

    try {//from ww w.j  a v  a 2s  . c om
        XPathExpression expression = xpath.compile(XPATH_EXPRESSION);

        applicationNodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }

    if (applicationNodes != null) {
        for (int i = 0; i < applicationNodes.getLength(); i++) {
            Node currentNode = applicationNodes.item(i);

            applications.put(currentNode.getAttributes().getNamedItem("app_name").getNodeValue(),
                    currentNode.getAttributes().getNamedItem("app_id").getNodeValue());
        }
    }

    return applications;
}

From source file:Main.java

private static NodeList getNodeList(String xmlContent, String expression)
        throws XPathExpressionException, SAXException, IOException, ParserConfigurationException {

    Document document = parse(xmlContent, CHARSET_UTF8);
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xpath.evaluate(expression, document.getDocumentElement(),
            XPathConstants.NODESET);

    return nodeList;
}

From source file:de.egore911.versioning.deployer.performer.PerformCheckout.java

public void perform(Node serverDeploymentsDeploymentNode) throws XPathExpressionException {
    NodeList checkoutOperations = (NodeList) checkoutXpath.evaluate(serverDeploymentsDeploymentNode,
            XPathConstants.NODESET);
    for (int j = 0; j < checkoutOperations.getLength(); j++) {
        Node checkoutOperation = checkoutOperations.item(j);
        String target = (String) targetXpath.evaluate(checkoutOperation, XPathConstants.STRING);
        String git = (String) gitXpath.evaluate(checkoutOperation, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(git)) {
            performGit(target, git);//from  www.j a v  a  2  s.c  om
        } else {
            String svn = (String) svnXpath.evaluate(checkoutOperation, XPathConstants.STRING);
            if (StringUtils.isNotEmpty(svn)) {
                performSvn(target, svn);
            } else {
                LOG.warn("Neither SVN nor git used for server configuration");
            }
        }
    }
}

From source file:com.autentia.tnt.xml.UtilitiesXPath.java

public static List<List> ExtractReport(String folderReport) {
    List reportList = null;//from  ww  w  .  j  ava  2 s  .  c  o  m
    List filesList = null;
    try {
        reportList = new ArrayList<List>();
        filesList = UtilitiesXML.filesFromFolder(folderReport);

        for (int i = 0; i < filesList.size(); i++) {
            List<List> tmp = new ArrayList<List>();
            Document doc = UtilitiesXML.file2Document(filesList.get(i).toString());
            XPath xpath = XPathFactory.newInstance().newXPath();

            if (log.isDebugEnabled()) {
                log.debug("\n>> Nombre del informe: ");
            }

            expression = "/jasperReport[@name]";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            nameReport = UtilitiesXML.printAttribute("name", nodes);
            nameReport.add(UtilitiesXML.cleanReport(filesList.get(i).toString()));

            if (log.isDebugEnabled()) {
                log.debug(nameReport.toString());
                log.debug("Parametros: ");
            }

            expression = "/jasperReport/parameter[@name]";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersName = UtilitiesXML.printAttribute("name", nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersName.toString());
                log.debug("Clases: ");
            }

            expression = "/jasperReport/paremeter[@class]";
            nameClass = UtilitiesXML.printAttribute("class", nodes);

            if (log.isDebugEnabled()) {
                log.debug(nameClass.toString());
                log.debug("Descripcion de Parametros: ");
            }

            expression = "/jasperReport/parameter/parameterDescription";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersDescription = UtilitiesXML.nodes2String(nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersDescription.toString());
                log.debug("Valores por defectos: ");
            }

            expression = "/jasperReport/parameter/defaultValueExpression";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersDefaultValue = UtilitiesXML.nodes2String(nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersDefaultValue.toString());
                log.debug("\n------------------------------------");
            }

            tmp.add(nameReport);
            tmp.add(parametersName);
            tmp.add(nameClass);
            tmp.add(parametersDescription);
            tmp.add(parametersDefaultValue);
            reportList.add(tmp);

        }
        log.debug("Lista de informes:" + reportList);

    } catch (Exception e) {
        log.error(e);
    }
    return reportList;

}

From source file:com.digitalpebble.storm.crawler.parse.filter.ContentFilter.java

@Override
public void filter(String URL, byte[] content, DocumentFragment doc, ParseResult parse) {

    ParseData pd = parse.get(URL);

    // TODO determine how to restrict the expressions e.g. regexp on URL
    // or value in metadata

    // iterates on the expressions - stops at the first that matches
    for (XPathExpression expression : expressions) {
        try {//from  ww  w  .jav a 2 s . co m
            NodeList evalResults = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
            if (evalResults.getLength() == 0) {
                continue;
            }
            StringBuilder newText = new StringBuilder();
            for (int i = 0; i < evalResults.getLength(); i++) {
                Node node = evalResults.item(i);
                newText.append(node.getTextContent()).append("\n");
            }

            // ignore if no text captured
            if (StringUtils.isBlank(newText.toString())) {
                LOG.debug("Found match for doc {} but empty text extracted - skipping", URL);
                continue;
            }

            // give the doc its new text value
            LOG.debug("Restricted text for doc {}. Text size was {} and is now {}", URL, pd.getText().length(),
                    newText.length());

            pd.setText(newText.toString());

            return;
        } catch (XPathExpressionException e) {
            LOG.error("Caught XPath expression", e);
        }
    }

}

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  www.j  av a2  s. c  om*/
    // /**
    // * @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

/**
 * Gets the node list from the given xml file and the given xpath expression.
 * //from   ww w .j a  v a 2s  . com
 * @param xml
 *            the xml file as string.
 * @param xpathExpression
 *            the xpath expression as string.
 * @return the node list
 * @throws XPathExpressionException
 *             the x path expression exception
 * @throws ParserConfigurationException
 *             the parser configuration exception
 * @throws SAXException
 *             the sAX exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static NodeList getNodeList(String xml, String xpathExpression)
        throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(xml);
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile(xpathExpression);

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    return nodes;
}

From source file:Main.java

/**
 * Find the node matching the xpath in the xml document
 *
 * @param doc   the xml document// ww w.  java2s . c  om
 * @param xpath the xpath expression
 * @return the node list matching the xpath, null if not found
 */
public static NodeList findNodeByXpath(Document doc, String xpath) {
    try {
        return (NodeList) xPath.compile(xpath).evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        return null;
    }
}