Example usage for javax.xml.xpath XPathFactory newXPath

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

Introduction

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

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java

/**
 * very useful: {@link http/*from  w w  w.j  a  v  a2s.c om*/
 * ://www.ibm.com/developerworks/library/x-javaxpathapi.html}
 * 
 * @param doc
 * @param path
 * @param scale
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
private String extractTextInternal(Document doc, String path)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    XPathFactory factory = XPathFactory.newInstance();

    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(namespaceContext);
    XPathExpression expr = xpath.compile(path);
    try {
        String result = (String) expr.evaluate(doc, XPathConstants.STRING);
        return result;
    } catch (Exception e) {
        log.error("XML extraction for path " + path + " failed: " + e.getMessage(), e);
        return "XML extraction for path " + path + " failed: " + e.getMessage();
    }
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.opinion.OpinionDocumentFactory.java

private OpinionDocument create(OpinionDocument document, OpinionCorpus corpus, Node node)
        throws XPathException {

    try {//w  w w  . j av  a2 s  .c om
        Validate.notNull(node, CannedMessages.NULL_ARGUMENT, "node");
    } catch (NullPointerException e) {
        throw new IllegalFactoryOptionsException(e);
    }

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    Double polarity = (Double) xpath.compile("./@polarity").evaluate(node, XPathConstants.NUMBER);

    return this.create(document, corpus, node.getTextContent().trim(), polarity);
}

From source file:com.dianping.zebra.shard.jdbc.base.SingleDBBaseTestCase.java

protected void parseCreateTableScriptFile() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document configDoc = builder/*  w  w w .jav  a  2  s .c  o m*/
            .parse(SingleDBBaseTestCase.class.getClassLoader().getResourceAsStream(getCreateTableScriptPath()));
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    NodeList tableScriptList = (NodeList) xpath.compile("/tables/table").evaluate(configDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < tableScriptList.getLength(); i++) {
        SingleCreateTableScriptEntry entry = new SingleCreateTableScriptEntry();
        Element ele = (Element) tableScriptList.item(i);
        entry.setTableName(ele.getAttribute("name"));
        entry.setCreateTableScript(ele.getTextContent());
        createdTableList.add(entry);
    }
}

From source file:com.fluidops.iwb.deepzoom.CXMLServlet.java

static void readImageCollectionFile(String collection) {
    InputStream stream = null;/* w ww  . ja v  a  2s  .  c  o m*/
    try {
        stream = new FileInputStream(collection);

        Document doc = null;

        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//I");
        NodeList result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < result.getLength(); i++) {
            Node node = result.item(i);
            NamedNodeMap map = node.getAttributes();
            String source = map.getNamedItem("Source").getNodeValue();
            String id = map.getNamedItem("Id").getNodeValue();

            source = source.substring("dzimages/".length(), source.lastIndexOf(".xml"));
            ids.put(source, id);
        }
    } catch (RuntimeException e) {
        logger.error(e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:edu.wisc.hrs.dao.BaseHrsSoapDao.java

protected String evaluateXPath(Node node, String expression) {
    final XPathFactory xpathFactory = XPathFactory.newInstance();
    final XPath xPath = xpathFactory.newXPath();
    final XPathExpression xpathExpression;
    try {/*from w w  w  .  j  a  va  2s. c  o  m*/
        xpathExpression = xPath.compile(expression);
    } catch (XPathExpressionException e) {
        return null;
    }

    try {
        return xpathExpression.evaluate(node);
    } catch (XPathExpressionException e) {
        return null;
    }
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.opinion.OpinionCorpusFactory.java

@Override
protected OpinionCorpusFactory addXmlPacket(OpinionCorpus corpus, InputStream input)
        throws ParserConfigurationException, SAXException, IOException, XPathException {

    Validate.notNull(corpus, CannedMessages.NULL_ARGUMENT, "corpus");
    Validate.notNull(input, CannedMessages.NULL_ARGUMENT, "input");

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*from  w w w  .ja  v  a 2s . c  o m*/
    Document doc = domFactory.newDocumentBuilder().parse(input);

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

    OpinionDocumentFactory opinionFactory;

    if ("document".equals(doc.getDocumentElement().getLocalName())) {
        opinionFactory = new OpinionDocumentFactory().setCorpus(corpus).setXmlNode(doc.getDocumentElement());
        corpus.addDocument(opinionFactory.create());
        return this;
    }

    Node corpusNode = (Node) xpath.compile("/corpus").evaluate(doc, XPathConstants.NODE);
    if (corpusNode == null) {
        corpusNode = Validate.notNull(doc.getDocumentElement(), CannedMessages.NULL_ARGUMENT, "/corpus");
    }

    String title = (String) xpath.compile("./@title").evaluate(corpusNode, XPathConstants.STRING);
    String description = (String) xpath.compile("./@description").evaluate(corpusNode, XPathConstants.STRING);
    String language = (String) xpath.compile("./@language").evaluate(corpusNode, XPathConstants.STRING);

    if (StringUtils.isNotEmpty(title)) {
        corpus.setTitle(title);
    }

    if (StringUtils.isNotEmpty(description)) {
        corpus.setDescription(description);
    }

    if (StringUtils.isNotEmpty(language)) {
        corpus.setLanguage(language);
    }

    NodeList documentNodes = (NodeList) xpath.compile("./document").evaluate(corpusNode,
            XPathConstants.NODESET);
    if (documentNodes == null || documentNodes.getLength() == 0) {
        documentNodes = corpusNode.getChildNodes();
        Validate.isTrue(documentNodes != null && documentNodes.getLength() > 0, CannedMessages.NULL_ARGUMENT,
                "/corpus/document");
    }

    for (int index = 0; index < documentNodes.getLength(); index++) {
        opinionFactory = new OpinionDocumentFactory().setCorpus(corpus).setXmlNode(documentNodes.item(index));
        corpus.addDocument(opinionFactory.create());
    }

    return this;
}

From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java

public HashMap<String, String> extractValues(Document xml, String path) {
    try {//  w  w w  .  j a v  a  2s  .  c  om
        HashMap<String, String> resultMap = new HashMap<String, String>();

        XPathFactory factory = XPathFactory.newInstance();

        XPath xpath = factory.newXPath();
        xpath.setNamespaceContext(namespaceContext);
        XPathExpression expr = xpath.compile(path);

        NodeList list = (NodeList) expr.evaluate(xml, XPathConstants.NODESET);
        if (list != null) {
            for (int i = 0; i < list.getLength(); i++) {
                Node n = list.item(i);
                String content = n.getTextContent();
                if (content != null) {
                    resultMap.put(n.getLocalName(), content);
                }
            }
        }
        return resultMap;
    } catch (Exception e) {
        log.error("Could not parse XML " + " searching for path " + path + ": " + e.getMessage(), e);
        return null;
    }
}

From source file:net.javacrumbs.springws.test.util.DefaultXmlUtil.java

@SuppressWarnings("unchecked")
public boolean isSoap(Document document) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(SOAP_NAMESPACE_CONTEXT);
    try {/*from   w w  w .j  a  v a 2  s .  c o m*/
        for (Iterator iterator = SOAP_NAMESPACE_CONTEXT.getBoundPrefixes(); iterator.hasNext();) {
            String prefix = (String) iterator.next();
            if ((Boolean) xpath.evaluate("/" + prefix + ":Envelope", document, XPathConstants.BOOLEAN)) {
                return true;
            }
        }
    } catch (XPathExpressionException e) {
        logger.warn(e);
    }
    return false;
}

From source file:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java

private String getConfigValue(String setting, String name, Document doc) throws XPathExpressionException {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression userExpr = xpath
            .compile("tagme/setting[@name=\"" + setting + "\"]/param[@name=\"" + name + "\"]/@value");
    return userExpr.evaluate(doc);
}

From source file:com.oracle.tutorial.jdbc.ProductInformationTable.java

public void populateTable(String fileName)
        throws SQLException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    // factory.setNamespaceAware(true);
    factory.setNamespaceAware(true);//w w  w  . ja va  2s . c  o  m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    NodeList nodes = (NodeList) xPath.evaluate("/coffee-product-information/item[coffee = 'Columbian']", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node currentNode = nodes.item(i);
        // Retrieve the description element

        currentNode.normalize();

        if (currentNode == null) {
            System.out.println("Current node is null");
        }

        //      System.out.println(currentNode.getTextContent());

        Node descriptionNode = (Node) xPath.evaluate("description", currentNode, XPathConstants.NODE);

        if (descriptionNode == null) {
            System.out.println("DescriptionNode is null");
        } else {

            System.out.println(descriptionNode.getTextContent());

            NodeList descriptionNodeChildren = descriptionNode.getChildNodes();
            System.out.println("Description node has " + descriptionNodeChildren.getLength() + " child nodes");
            Node descNodeChild = descriptionNode.getFirstChild();
            System.out.println("Only child node type: " + descNodeChild.getNodeType());
        }

        //      System.out.println("Description: " + descriptionNode.getNodeValue());

        // System.out.println(nodes.item(i).getNodeValue());
    }

}