Example usage for javax.xml.xpath XPathFactory newInstance

List of usage examples for javax.xml.xpath XPathFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newInstance.

Prototype

public static XPathFactory newInstance() 

Source Link

Document

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.

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: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   w ww .  j  ava2  s.co 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: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  a va 2s. 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:com.cloudseal.spring.client.namespace.Utility.java

public static void removeNode(final Element rootElement, final String xPathLocation)
        throws XPathExpressionException {
    final XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new CloudSealNamespaceContext());
    final Node node = (Node) xPath.evaluate(xPathLocation, rootElement, XPathConstants.NODE);
    final short nodeType = node.getNodeType();

    switch (nodeType) {
    case Node.ELEMENT_NODE:
        final Node parent = node.getParentNode();
        parent.removeChild(node);/*  w  w  w .  j a va2 s  .  c  o  m*/
        break;

    case Node.ATTRIBUTE_NODE:
        final Attr attribute = (Attr) node;
        final Element element = attribute.getOwnerElement();
        element.removeAttributeNode(attribute);
        break;

    default:
        throw new IllegalArgumentException("Not supported node type: " + nodeType);
    }
}

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 w  w.  j  a v  a  2s .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)) {
                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:org.objenesis.tck.OsgiTest.java

protected String[] getTestBundlesNames() {
    String version = getImplementationVersion(Objenesis.class);
    // Null means we are an IDE, not in Maven. So we have an IDE project dependency instead
    // of a Maven dependency with the jar. Which explains why the version is null (no Manifest
    // since there's no jar. In that case we get the version from the pom.xml and hope the Maven
    // jar is up-to-date in the local repository
    if (version == null) {
        try {//w ww . ja v  a  2s  .  c  o  m
            XPathFactory xPathFactory = XPathFactory.newInstance();
            final XPath xPath = xPathFactory.newXPath();
            XPathExpression xPathExpression;
            try {
                xPathExpression = xPath.compile("/project/parent/version");
            } catch (final XPathExpressionException e) {
                throw new RuntimeException(e);
            }

            final DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
            xmlFact.setNamespaceAware(false);
            final DocumentBuilder builder = xmlFact.newDocumentBuilder();
            final Document doc = builder.parse(new File("pom.xml"));
            version = xPathExpression.evaluate(doc);
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }
    return new String[] { "org.objenesis, objenesis, " + version };
}

From source file:org.ow2.chameleon.fuchsia.push.base.subscriber.tool.HubDiscovery.java

public String hasHub(Document doc) {
    String hub = null;//  w  w w .  j a v a 2  s .  c  om

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    XPathExpression xPathExpression;

    try {
        xPathExpression = xPath.compile("/feed/link[@rel='hub']/@href");
        hub = xPathExpression.evaluate(doc);
        if ((hub == null) || (hub.length() == 0)) {
            xPathExpression = xPath.compile("//link[@rel='hub']/@href");
            hub = xPathExpression.evaluate(doc);
        }

        if (hub.length() == 0) {
            return null;
        }

        return hub;

    } catch (XPathExpressionException e) {
        LOGGER.error("XPathExpression invalid", e);
        return null;
    }
}

From source file:hoot.services.utils.XmlDocumentBuilder.java

/**
 * Creates an XPATH instance for querying with
 * /*from   w w w  .  j  av  a 2 s.c  o  m*/
 * @return an XPATH instance
 */
public static XPath createXPath() {
    XPathFactory factory = XPathFactory.newInstance();
    return factory.newXPath();
}

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 ww  .  jav a  2  s  .  com

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