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:au.edu.rmit.GalagoSearchClient.java

protected NodeList xpathGetNodeList(Document doc, String expr)
        throws XPathExpressionException, UnsupportedEncodingException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    return (NodeList) xpath.compile(expr).evaluate(doc, XPathConstants.NODESET);
}

From source file:Main.java

/**
 * Gets the node list from the given xml file and the given xpath expression.
 * //from   w w w.  ja  v a2 s. c om
 * @param xml
 *            the xml
 * @param xpathExpression
 *            the xpath expression
 * @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(final File xml, final String xpathExpression)
        throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
    final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    final DocumentBuilder builder = domFactory.newDocumentBuilder();
    final Document doc = builder.parse(xml);
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final XPathExpression expr = xpath.compile(xpathExpression);

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

From source file:com.cordys.coe.ac.httpconnector.samples.JIRABrowserResponseHandler.java

/**
 * @see com.cordys.coe.ac.httpconnector.samples.JIRAResponseHandler#buildXMLResponse(int,org.apache.commons.httpclient.HttpMethod,
 *      org.w3c.dom.Document, com.eibus.xml.nom.Document)
 *//*from ww w. j  av  a2s . c  o  m*/
@Override
protected void buildXMLResponse(int resNode, HttpMethod httpMethod, org.w3c.dom.Document document, Document doc)
        throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xpath.evaluate("//table[@class='grid']/tr[@class='vcard']", document,
            XPathConstants.NODESET);

    int nrOfUsers = nodeList.getLength();

    if (nrOfUsers > 0) {
        for (int count = 0; count < nrOfUsers; count++) {
            Node userNode = nodeList.item(count);

            int tuple = doc.createElementWithParentNS("tuple", null, resNode);

            int old = doc.createElementWithParentNS("old", null, tuple);
            int user = doc.createElementWithParentNS("user", null, old);

            // Get the name
            String username = (String) xpath.evaluate(".//span[@class='username']/text()", userNode,
                    XPathConstants.STRING);

            doc.createElementWithParentNS("username", username, user);

            // Get the email address
            String emailAddress = (String) xpath.evaluate(".//span[@class='email']/text()", userNode,
                    XPathConstants.STRING);

            doc.createElementWithParentNS("email", emailAddress, user);

            // Get the full name
            String fn = (String) xpath.evaluate(".//span[@class='fn']/text()", userNode, XPathConstants.STRING);

            doc.createElementWithParentNS("fullname", fn, user);

            // Get the groups for this user
            NodeList nl = (NodeList) xpath.evaluate(".//td/a[../br]/text()", userNode, XPathConstants.NODESET);
            int groups = doc.createElementWithParentNS("groups", null, user);

            for (int groupsCount = 0; groupsCount < nl.getLength(); groupsCount++) {
                String group = nl.item(groupsCount).getNodeValue();
                doc.createElementWithParentNS("group", group, groups);
            }
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("No users found");
    }
}

From source file:Main.java

private static NodeList getNodeList(Document document, String expression) throws XPathExpressionException {

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

    return nodeList;
}

From source file:com.github.born2snipe.project.setup.cli.maven.AssertXml.java

public static void assertElementExist(String expectedText, File file, String xpathQuery) {
    try {//from w  ww  . ja  v  a 2s. com
        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)) {
                return;
            }
        }
        Assert.fail("We expected to find " + expectedText + "\nFile Contents:\n"
                + IOUtils.toString(new FileInputStream(file)));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.fritaly.svngraph.History.java

public History(Document document) throws XPathExpressionException, ParseException {
    Validate.notNull(document, "The given document is null");

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

    NodeList nodes = (NodeList) xpath.evaluate("/log/logentry", document.getDocumentElement(),
            XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        final Revision revision = new Revision((Element) nodes.item(i));

        revisions.put(revision.getNumber(), revision);
    }/*from  w w  w.j av a 2  s .  co m*/

    System.out.println(String.format("Parsed %d revisions", revisions.size()));
}

From source file:Main.java

public static List<Node> evaluateNodeListXPath(final Document document, final XPathExpression expression)
        throws XPathExpressionException {
    notNull(document);//from ww w  .jav  a 2s .  c o  m
    notNull(expression);

    final List<Node> result = new LinkedList<Node>();

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

    for (int node = 0; node < nodeList.getLength(); node++) {
        result.add(nodeList.item(node));
    }

    return result;
}

From source file:de.dplatz.padersprinter.control.TripService.java

public Observable<Trip> query(TripQuery query) {
    final HtmlCleaner htmlCleaner = new HtmlCleaner();
    final DomSerializer domSerializer = new DomSerializer(new CleanerProperties());
    final XPath xpath = XPathFactory.newInstance().newXPath();

    return httpClient.get(query).map(htmlCleaner::clean).flatMap(tagNode -> {
        try {/*from w  w  w  . j  av  a 2 s.  c  o m*/
            return Observable.just(domSerializer.createDOM(tagNode));
        } catch (ParserConfigurationException pce) {
            return Observable.error(pce);
        }
    }).flatMap(doc -> {
        try {
            return Observable.just((NodeList) xpath.evaluate(TRIP_NODES_XPATH, doc, XPathConstants.NODESET));
        } catch (XPathExpressionException xee) {
            return Observable.error(xee);
        }
    }).flatMap(nodeList -> {
        List<Node> nodes = new LinkedList<>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            nodes.add(nodeList.item(i));
        }
        logger.info("HTML contains " + nodes.size() + " result-panels.");
        return Observable.from(nodes);
    }).flatMap(tripNode -> parseTrip(tripNode).map(Observable::just).orElseGet(Observable::empty));
}

From source file:br.gov.lexml.parser.documentoarticulado.LexMLUtil.java

public static String formatLexML(String xml) {
    String retorno = null;/*from w w w. j  a  va  2 s  .c  o m*/
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        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);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);

        transformer.transform(new DOMSource(document), streamResult);

        retorno = stringWriter.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return retorno;

}

From source file:Main.java

public static final String indenting(Node rootNode) throws XPathExpressionException, TransformerException {

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", rootNode,
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }//from  w w  w .java 2 s  .c om

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);

    transformer.transform(new DOMSource(rootNode), streamResult);

    return stringWriter.toString();
}